##
##
## #template("name.vm")
## Searches for the given velocity template and interprets it.
## Only the velocity parser is executed on the file.
## The template is searched in the following locations, in this order:
## - as a property of the XWikiSkins object attached to the current skin document
## - as an attachment to the current skin document
## - as a file in the directory corresponding to the current skin
## - the above 3 locations corresponding to the base skin
## - the above 3 locations corresponding to the default skin
## - as a file in the /templates/ directory
##
#macro(template $tname)
$xwiki.parseTemplate($tname)
#end
##
##
## #renderTemplate("name.vm")
## Searches for the given velocity template and renders it.
## The template is searched in the following locations, in this order:
## - as a property of the XWikiSkins object attached to the current skin document
## - as an attachment to the current skin document
## - as a file in the directory corresponding to the current skin
## - the above 3 locations corresponding to the base skin
## - the above 3 locations corresponding to the default skin
## - as a file in the /templates/ directory
##
#macro(renderTemplate $tname )
$xwiki.renderTemplate($tname)
#end
##
##
## #includeTopic("Space.Document")
## Includes another fully rendered document inside the current response.
## The topic is interpreted and rendered exactly as if it were viewed in a separate response,
## meaning that the $doc variable will point to the included document. The resulting string is
## wrapped with {pre}...{/pre}, in order to prevent double-rendering.
## The platform prevents recursive includes.
## This macro is useful for creating composite documents from smaller parts, or the other way around,
## splitting a large document into smaller distinct chunks which can be edited in parallel.
##
#macro(includeTopic $topic)
$xwiki.includeTopic($topic)
#end
##
##
## #includeMacros("Space.Document")
## Includes the content of another document as velocity macros. Because of the way the velocity
## engine works, trying to place macros in another document and including it with another method
## will not have the expected result. Other than making the macros available, it works just as
## #includeForm($topic)
##
#macro(includeMacros $topic)
$xwiki.includeForm($topic)
#end
##
##
## #includeForm("Space.Document")
## Includes another fully rendered document inside the current response.
## The included content is interpreted and rendered in the current context, meaning that $doc will
## point to the current document (the includer), and not the included one. The resulting string is
## wrapped with {pre}...{/pre}, in order to prevent double-rendering.
## The platform prevents recursive includes.
## This macro is the core of the document-template-sheet functionality of XWiki, where a document
## has an XObject attached to it, its content consists of the "#includeForm('Some.Sheet')" statement,
## and the sheet works just as if it were actually inside the document's content.
##
#macro(includeForm $topic)
$xwiki.includeForm($topic)
#end
##
##
## #includeInContext("Some.Document")
## Alias for #includeForm
##
#macro(includeInContext $topic)
$xwiki.includeForm($topic)
#end
##
##
## #includeServlet("/xwiki/bin/view/Some/Document?params")
## Invokes on the server another servlet corresponding to the passed URL, and returns the output.
## This is done using standard servlet mechanisms (javax.servlet.RequestDispatcher#include).
##
#macro(includeServlet $url)
<!-- including $url -->
$xwiki.invokeServletAndReturnAsString($url)
<!-- included $url -->
#end
##
##
## #versions()
## Displays links to the last 4 versions (including the current one), and to the full history
## page of the current document.
##
#macro(versions)
#foreach($rev in $tdoc.getRecentRevisions(4))
<a href="$doc.getURL("view", "rev=$rev")">$rev</a><span class="xwikisep"> | </span>
#end
#if ($tdoc.realLanguage!="")
<a href="$doc.getURL("view", "xpage=diff&amp;language=${tdoc.realLanguage}")">$msg.get("diff")</a><span class="xwikisep"> | </span>
#else
<a href="$doc.getURL("view", "xpage=diff")">$msg.get("history")</a><span class="xwikisep"> | </span>
#end
#end
##
##
## #errorMarkup()
## Display all queued Struts errors
##
#macro(errorMarkup)
  #if ($errors && $!errors.exist() )
    <ul>
    #foreach ($e in $errors.all )
      $e
    #end
    </ul>
  #end
#end
##
##
## #errorMarkupForProperty("prop")
## Display all queued Struts errors for a particular property
##
#macro(errorMarkupForProperty $property)
  #if ($errors && $!errors.exist($property) )
    <ul>
    #foreach ($er in $errors.get($property))
      $er
    #end
    </ul>
  #end
#end
##
##
## #jabber("jabberId")
## Displays the status for the given Jabber id
##
#macro(jabber $id)
<img src="http://edgar.netflint.net/status.php?jid=${id}&amp;type=image&amp;iconset=phpbb" alt="jabber $id" />
#end
##
##
## #skype("skypeId")
## Displays the status for the given Skype id
##
#macro(skype $id)
<a href="skype:${id}?call"><img width="182" height="44" src="http://mystatus.skype.com/bigclassic/${id}" style="border: none;"></a>
#end
##
##
## #yahoo("yahooId")
## Displays the status for the given Yahoo! id
##
#macro(yahoo $id)
<img border="0" src="http://opi.yahoo.com/online?u=${id}&amp;m=g&amp;t=1" alt="yahoo $id" />
#end
##
##
## #aim("aimId")
## Displays the status for the given AIM id
##
#macro(aim $id)
#set($onurl = "${escapetool.url(${request.scheme})}://${escapetool.url(${request.serverName})}${xwiki.getSkinFile('aimonline.gif')}")
#set($offurl = "${escapetool.url(${request.scheme})}://${escapetool.url(${request.serverName})}${xwiki.getSkinFile('aimoffline.gif')}")
<img border="0" src="http://big.oscar.aol.com/nvludo?on_url=${escapetool.url(${onurl})}&amp;off_url=${escapetool.url(${offurl})}" alt="Online detector"></a>
#end
##
##
## #msn("msnId")
## Displays the status for the given MSN id
##
#macro(msn $id)
#set($onurl = "${escapetool.url(${request.serverName})}${xwiki.getSkinFile('msnonline.gif')}")
#set($offurl = "${escapetool.url(${request.serverName})}${xwiki.getSkinFile('msnoffline.gif')}")
<img border="0" src="http://turdinc.kicks-ass.net:6969/msn/${id}/onurl=${escapetool.url(${onurl})}/offurl=${escapetool.url(${offurl})}/unknownurl=${escapetool.url(${offurl})}" />
#end
##
##
## #im("XWiki.Username")
## Displays the instant messaging account status of the given user. The IM network and the account
## name are taken from the user profile.
##
#macro(im $user)
#set($userdoc = $xwiki.getDocument($user))
#set($userobj = $userdoc.getObject("XWiki.XWikiUsers"))
#set($imtype = $userdoc.display("imtype","view",$userobj))
#set($imaccount = $userdoc.display("imaccount","view",$userobj))
#if($imtype=="Yahoo")
#yahoo("$imaccount")
#end
#if($imtype=="AIM")
#aim("$imaccount")
#end
#if($imtype=="MSN")
#msn("$imaccount")
#end
#if($imtype=="Jabber")
#jabber("$imaccount")
#end
#if($imtype=="Skype")
#skype("$imaccount")
#end
#end
##
##
## #sign("XWiki.Username")
## Displays a "signature", a link to the user's profile page.
##
#macro(sign $username)
#if($username.indexOf(".")==-1)
#set($username = "XWiki.${username}")
#end
#if($xwiki.exists("$username"))
$xwiki.getUserName("$username")
#else
$xwiki.getUserName("xwiki:${username}")
#end
#end

#macro(includeHelp $pagename)
  #if($xwiki.exists("xwiki:XWiki.${pagename}"))
    $xwiki.includeForm("xwiki:XWiki.${pagename}",false)
  #else
    #if($xwiki.exists("XWiki.${pagename}"))
      $xwiki.includeForm("XWiki.${pagename}",false)
    #end
  #end
#end

#macro(flickr $rss)
{rss:feed=${rss}|full=1}
#end

#macro(flickrtag $tag)
#flickr("http://www.flickr.com/services/feeds/photos_public.gne?tags=${tag}&format=rss_200")
#end

#macro(flickruser $id)
#flickr("http://www.flickr.com/services/feeds/photos_public.gne?id=${id}&format=rss_200")
#end

#macro(flickrusertag $id $tag)
#flickr("http://www.flickr.com/services/feeds/photos_public.gne?id=${id}&tags=${tag}&format=rss_200")
#end

#macro(map $address $cp $linktext)
<a href="http://www.viamichelin.com/viamichelin/fra/dyn/controller/mapPerformPage?strAddress=${address}&amp;strLocation=&amp;strCP=${cp}&amp;strCountry=1424&amp;x=30&amp;y=9">${linktext}</a>
#end

#macro(mindmap $mindmap $width $height)
#if(!$width)
#set($width="100%")
#end
#if(!$height)
#set($height="600")
#end
#if(!$mindmap)
#set($mindmap = "")
#set($mmurl = "")
#else
#if($mindmap.startsWith("http"))
#set($mmurl = $mindmap)
#else
#set($mmurl1 = $doc.getAttachmentURL($mindmap,"download"))
#set($mmurl = "${escapetool.url(${request.scheme})}://${escapetool.url(${request.serverName})}:${escapetool.url(${request.serverPort})}${mmurl1}")
#end
#end
<applet code="freemind.main.FreeMindApplet.class" archive="${escapetool.xml(${request.contextPath})}/freemind/freemind.jar" width="${escapetool.xml(${width})}" height="${escapetool.xml(${height})}">
<param name="type" value="application/x-java-applet;version=1.4" />
<param name="scriptable" value="false" />
<param name="modes" value="freemind.modes.browsemode.BrowseMode" />
<param name="browsemode_initial_map" value="$mmurl" />
<param name="initial_mode" value="Browse" />
<param name="selection_method" value="selection_method_direct" />
</applet>
#end

#macro(toc $pinit $pmax $pnumbered)
#set($init = $pinit)
#set($max = $pmax)
#set($numbered = $pnumbered)
 #set ($int = 0)
 #set ($boolean = false)
 #if ($init == "")
  #set ($init = 2)
 #else
  #set ($init = $int.valueOf($init))
 #end
 #if ($max == "")
  #set ($max = 6)
 #else
  #set ($max = $int.valueOf($max))
 #end
 #if ($numbered == "")
  #set ($numbered = false)
 #else
  #set ($numbered = $boolean.valueOf($numbered))
 #end
 #set ($tocData = ${tdoc.getTOC($init, $max, $numbered)})
 #set ($xcontext.tocData = $tocData)
 #set ($lastLevel = $init - 1)
 #set ($depth = 0)
 #set ($openeditem = true)
<div class="toc">
 #foreach ($tocEntry in $tocData.entrySet())
  #set ($level = $tocEntry.value.level)
  #if ($level > $lastLevel)
   #set ($to = $lastLevel + 1)
   #set ($iter = [$level .. $to])
   #foreach ($n in $iter)
    #if($openeditem)
      #set($openeditem = false)
    #else
<li>
    #end
<ul class="tocLevel">
    #set ($depth = $depth + 1)
   #end
  #elseif ($level < $lastLevel)
   #set ($to = $level + 1)
   #set ($iter = [$lastLevel .. $to])
</li>
   #foreach ($n in $iter)
</ul>
</li>
    #set ($depth = $depth - 1)
   #end
  #else
</li>
  #end
 <li class="tocEntry"><a href="#$tocEntry.key">$!tocEntry.value.numbering $xwiki.parseContent($tocEntry.value.text)</a>
  #set ($lastLevel = $level)
  #set($openeditem = true)
 #end
 #if ($depth > 0)
  #set ($levels = [1 .. $depth])
  #foreach($level in $levels)
 </li>
</ul>#end
 #end
</div>
#end

##
## Warning: Written in syntax xwiki/1.0, there is no way to properly escape the links
## Do not use
##
#macro(exportPackage)
#set($export = $request.get("export"))
#if ($export == "1")
  #set($dateFormat = "dd MMM yyyy ? HH:mm")
  #set($diff = $request.get("diff"))
  #set($SpaceName = $request.get("SpaceName"))

  1.1 Space : $SpaceName

  <form method="POST" action="$doc.getName()?export=2">

#set($docs = $xwiki.getSpaceDocsName($SpaceName))
  <table border="1" style="text-align:center;">
  <tr><td>Name</td><td>Export</td><td colspan="3">Default Action</td></tr>
  <tr><td colspan="2"></td><td>overwrite</td><td>merge objects</td><td>skip</td></tr>
  #foreach ($doc in $docs)
    #if ($xwiki.hasAccessLevel("view", "${xcontext.database}:${SpaceName}.${doc}"))

    <tr><td>[${doc}>${SpaceName}.${doc}]</td><td><input type="checkbox" name="ToExport" value="${SpaceName}.${doc}" /></td><td><input type="radio" name="${SpaceName}.${doc}_default" value="overwrite" checked="true" /></td> <td><input type="radio" name="${SpaceName}.${doc}_default" value="merge" /></td> <td><input type="radio" name="${SpaceName}.${doc}_default" value="skip" /></td> </tr>

    #end
  #end
  </table>

  #if($SpaceName != "XWiki")


    1.1 Space : XWiki

    #set($docs = $xwiki.getSpaceDocsName("XWiki"))
    <table border="1" style="text-align:center;">
    <tr><td>Name</td><td>Export</td><td colspan="3">Default Action</td></tr>
    <tr><td colspan="2"></td><td>overwrite</td><td>merge objects</td><td>skip</td></tr>
    #foreach ($doc in $docs)
      #if ($xwiki.hasAccessLevel("view", "${xcontext.database}:XWiki.${doc}"))

      <tr><td>[${doc}>XWiki.${doc}]</td><td><input type="checkbox" name="ToExport" value="XWiki.${doc}" /></td><td><input type="radio" name="XWiki.${doc}_default" value="overwrite" checked="true" /></td> <td><input type="radio" name="XWiki.${doc}_default" value="merge" /></td> <td><input type="radio" name="XWiki.${doc}_default" value="skip" /></td> </tr>

      #end
    #end
    </table>
  #end

  <input type="submit" name="submitted" value="Valider">
  </form>



#elseif ($export == "2")
  #set($ToExport = $request.getParameterValues("ToExport"))
  $response.setContentType("application/zip")
  #set($export = $xwiki.export)
  #foreach ($itemexp in $ToExport)
    #set($defaultAction = $request.get("${itemexp}_default"))
    $export.add($itemexp, $defaultAction)
  #end
  $export.export()
#else
  <form method="POST" action="$doc.getName()?export=1">
  Select the space you want to export : <br />
  #set($spaces = $xwiki.getSpaces())
  <select name="SpaceName">
  #foreach ($space in $spaces)
    <option value="$space">$space</option>
  #end

  </select>
  <input type="submit" name="submitted" value="Valider">
  </form>
#end
#end

##
## Warning: Written in syntax xwiki/1.0, there is no way to properly escape the links
## Do not use
##
#macro(importPackage)
#set($toexport = $request.get("export"))
#if($toexport == "1")
  #set($appName = $request.get("App"))
  #set($alist = $doc.getAttachmentList())
  #foreach ($oAttach in $alist)
    #if ($oAttach.getFilename() == $appName)
      #set($import = $xwiki.import)
      $import.importPackage($oAttach.getContent())

      #set($docs = $import.getDocuments())

      #foreach($docInfo in $docs)
        #set($right = "")
        #set($right = $request.get("$docInfo.getFullName()_default"))
        #if($right)
          $import.setDocumentAction($docInfo.getFullName(), $right)
        #end
      #end


      #set($ret = $import.install())
      $import.getTestInstallToString($ret)
    #end
  #end


#else
  #set($alist = $doc.getAttachmentList())
  #if ($alist.size() == 0)
    Add the package in attachment
  #end
  #foreach ($oAttach in $alist)
    #set($import = $xwiki.import)

    1.1 $oAttach.getFilename()

    $import.importPackage($oAttach.getContent())

    1.1.1 Infos

    Author : $import.getAuthor() <br />
    Name : $import.getName() <br />
    Description : $import.getDescription() <br />
    Licence : $import.getLicence() <br />
    Version : $import.getVersion() <br />

    #set($canInstall = $import.testInstall())
    install : $import.getTestInstallToString($canInstall)

    1.1.1 Status of each Files
    #set($docs = $import.getDocuments())

    <form method="POST" action="$request.getRequestURL()?export=1">
    <input type="hidden" name="App" value="$oAttach.getFilename()" />
    <table border="1" style="text-align:center;">
    <tr><td>Name</td><td>infos</td><td colspan="3">Action</td></tr>
    <tr><td colspan="2"></td><td>overwrite</td><td>merge objects</td><td>skip</td></tr>


    #foreach($docInfo in $docs)


      <tr><td>[$docInfo.getFullName()>$docInfo.getFullName()]</td> <td>__$import.getTestInstallToString($docInfo.isInstallable())__</td>
#if($import.getTestInstallToString($docInfo.isInstallable()) == "Already exist")
  #if ($import.getActionToString($docInfo.getDefaultAction()) == "overwrite")
    <td><input type="radio" name="$docInfo.getFullName()_default" value="overwrite" checked="true" /></td>
  #else
    <td><input type="radio" name="$docInfo.getFullName()_default" value="overwrite" /></td>
  #end
  #if ($import.getActionToString($docInfo.getDefaultAction()) == "merge")
    <td><input type="radio" name="$docInfo.getFullName()_default" value="merge" checked="true" /></td>
  #else
   <td><input type="radio" name="$docInfo.getFullName()_default" value="merge" /></td>
  #end
  #if ($import.getActionToString($docInfo.getDefaultAction()) == "skip")
    <td><input type="radio" name="$docInfo.getFullName()_default" value="skip" checked="true" /></td> </tr>
  #else
    <td><input type="radio" name="$docInfo.getFullName()_default" value="skip" /></td> </tr>
  #end
#else
  <td colspan="3"></td>
#end


    #end
    </table>
    #if ($canInstall != 0)
      1.1.1 You can install this application
      <input type="submit" name="submitted" value="Valider">
    #else
      1.1.1 You can't install this application.
    #end
    </form>
  #end
#end

#end
###
###    Separator
###
### Insert a span containing a |
###
#macro(sep)
<span class="separator"> | </span>
#end


###
###    useravatar
###
### Display the avatar of a user, or a standard image if the user has no avatar
###
### @param username The name of the user whose avatar will be displayed
###
#macro(resizedUserAvatar $username $size)
  #if(!$picturelist)
    #set($picturelist = $util.hashMap)
  #end
  #if(!$picturelist.containsKey("${username}--${size}"))
    #set($picture = "<img class='avatar avatar_${escapetool.xml(${size})}' src='")
    #if ($xwiki.getDocument($username).getObject('XWiki.XWikiGroups'))
      #set ($picture = $picture.concat($xwiki.getSkinFile('icons/xwiki/noavatargroup.png', true)))
    #else
      #set ($picture = $picture.concat($xwiki.getSkinFile('icons/xwiki/noavatar.png', true)))
    #end
    #set($picture = $picture.concat("' alt='${xwiki.getUserName($username, false)}' title='${xwiki.getUserName($username, false)}'/>"))
    #set($profiledoc = $xwiki.getDocument($username))
    #if (!$profiledoc.isNew())
      #if($profiledoc.attachmentList.size() != 0)
        #set($profileobj = $profiledoc.getObject('XWiki.XWikiUsers', 0))
        #if($profileobj.avatar && $profileobj.avatar != "")
          #foreach ($attach in $profiledoc.attachmentList)
            #if($attach.filename == $profileobj.avatar)
              #set($pictureurl = $profiledoc.getAttachmentURL($profileobj.avatar))
              #set($picture = "<img src='")
              #set($picture = $picture.concat($pictureurl))
              #if ($size > 0)
                #set($picture = $picture.concat("?width=${escapetool.xml(${size})}&amp;height=${escapetool.xml(${size})}&amp;keepAspectRatio=true"))
              #end
              #set($picture = $picture.concat("' alt='"))
              #set($picture = $picture.concat(${xwiki.getUserName($username, false)}))
              #set($picture = $picture.concat("' title='"))
              #set($picture = $picture.concat(${xwiki.getUserName($username, false)}))
              #set($picture = $picture.concat("'/>"))
              #break
            #end
          #end
        #end
      #end
    #end
    #set ($discard = $!picturelist.put("${username}--${size}", $picture))
  #end
  $picturelist.get("${username}--${size}")##
#end
#macro(largeUserAvatar $username)
  #resizedUserAvatar($username 120)
#end
#macro(mediumUserAvatar $username)
  #resizedUserAvatar($username 50)
#end
#macro(smallUserAvatar $username)
  #resizedUserAvatar($username 30)
#end
###
###    useravatar
###
### Display the avatar of a user, or a standard image if the user has no avatar
###
### @param username The name of the user whose avatar will be displayed
###
#macro(useravatar $username)
  #resizedUserAvatar($username 0)
#end

###
###    mimetypeimg
###
### Display an icon according to the mimetype
###
### @param mime The reported mimetype of the file
### @param fname The name of the file
###
#macro(mimetypeimg $mime $fname)
  #set($idx = $fname.lastIndexOf('.'))
  #set($idx = $idx + 1)
  #if(($idx != 0) && ($idx != -1))
    #set($ext = $fname.substring($idx))
  #else
    #set($ext = '')
  #end
  ## Map mimetypes to their corresponding icons
  #if(!$mimetypeMap)
    #set($mimetypeMap = $util.hashMap)
    ## images
    #set($discard = $mimetypeMap.put('image/svg+xml',                      ['vector', 'SVG']))
    #set($discard = $mimetypeMap.put('application/svg+xml',                ['vector', 'SVG']))
    #set($discard = $mimetypeMap.put('image/svg',                          ['vector', 'SVG']))
    #set($discard = $mimetypeMap.put('image/svg+xml',                      ['vector', 'SVG']))
    #set($discard = $mimetypeMap.put('image/',                             ['picture', 'Image']))
    ## text
    #set($discard = $mimetypeMap.put('text/html',                          ['html', 'HTML']))
    #set($discard = $mimetypeMap.put('text/css',                           ['css', 'CSS']))
    #set($discard = $mimetypeMap.put('text/',                              ['page_white_text', 'Text']))
    ## documents
    #set($discard = $mimetypeMap.put('application/xml',                    ['page_white_code', 'XML']))
    #set($discard = $mimetypeMap.put('application/pdf',                    ['page_white_acrobat', 'PDF']))
    #set($discard = $mimetypeMap.put('application/postscript',             ['page_red', 'PS']))
    #set($discard = $mimetypeMap.put('application/msword',                 ['page_white_word', 'DOC']))
    #set($discard = $mimetypeMap.put('application/powerpoint',             ['page_white_powerpoint', 'PPT']))
    #set($discard = $mimetypeMap.put('application/vnd.ms-powerpoint',      ['page_white_powerpoint', 'PPT']))
    #set($discard = $mimetypeMap.put('application/vnd.oasis.opendocument', ['page', 'OpenOffice']))
    #set($discard = $mimetypeMap.put('application/x-shockwave-flash',      ['page_white_flash', 'SWF']))
    ## archives
    #set($discard = $mimetypeMap.put('application/x-tar',                  ['page_white_compressed', 'TAR']))
    #set($discard = $mimetypeMap.put('application/x-gzip',                 ['page_white_compressed', 'GZ']))
    #set($discard = $mimetypeMap.put('application/x-gtar',                 ['page_white_compressed', 'GZ']))
    #set($discard = $mimetypeMap.put('application/zip',                    ['page_white_zip', 'ZIP']))
    #set($discard = $mimetypeMap.put('application/java-archive',           ['cup', 'JAR']))
    #set($discard = $mimetypeMap.put('audio/',                             ['music', 'Audio']))
    #set($discard = $mimetypeMap.put('video/',                             ['film', 'Video']))
  #end
  #if(!$extensionMap)
    ## Map extensions to their corresponding icons
    #set($extensionMap = $util.hashMap)
    ## media
    #set($discard = $extensionMap.put('ogg',      ['music', 'Audio']))
    #set($discard = $extensionMap.put('flac',     ['music', 'Audio']))
    #set($discard = $extensionMap.put('ogv',      ['film', 'Video']))
    #set($discard = $extensionMap.put('mk',       ['film', 'Video']))
    #set($discard = $extensionMap.put('avi',      ['film', 'Video']))
    #set($discard = $extensionMap.put('divx',     ['film', 'Video']))
    #set($discard = $extensionMap.put('mov',      ['film', 'Video']))
    #set($discard = $extensionMap.put('flv',      ['page_white_flash', 'SWF']))
    #set($discard = $extensionMap.put('fla',      ['page_white_flash', 'SWF']))
    #set($discard = $extensionMap.put('swf',      ['page_white_flash', 'SWF']))
    ## office
    #set($discard = $extensionMap.put('odp',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('odt',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('odf',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('sxw',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('stw',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('ods',      ['page', 'OpenOffice']))
    #set($discard = $extensionMap.put('xls',      ['page_white_excel', 'XLS']))
    ## archives
    #set($discard = $extensionMap.put('bz',       ['page_white_compressed', 'BZ']))
    #set($discard = $extensionMap.put('bz2',      ['page_white_compressed', 'BZ']))
    #set($discard = $extensionMap.put('tbz',      ['page_white_compressed', 'BZ']))
    #set($discard = $extensionMap.put('gz',       ['page_white_compressed', 'GZ']))
    #set($discard = $extensionMap.put('tgz',      ['page_white_compressed', 'GZ']))
    #set($discard = $extensionMap.put('rar',      ['page_white_compressed', 'RAR']))
    #set($discard = $extensionMap.put('7z',       ['page_white_zip', 'ZIP']))
    ## development
    #set($discard = $extensionMap.put('sql',      ['database', 'SQL']))
    #set($discard = $extensionMap.put('php',      ['page_white_php', 'PHP']))
    #set($discard = $extensionMap.put('c',        ['page_white_c', 'C']))
    #set($discard = $extensionMap.put('cpp',      ['page_white_cplusplus', 'C++']))
    #set($discard = $extensionMap.put('c++',      ['page_white_cplusplus', 'C++']))
    #set($discard = $extensionMap.put('cs',       ['page_white_csharp', 'C#']))
    #set($discard = $extensionMap.put('h',        ['page_white_h', 'H']))
    #set($discard = $extensionMap.put('ruby',     ['page_white_ruby', 'RUBY']))
    #set($discard = $extensionMap.put('java',     ['page_white_cup', 'JAVA']))
    #set($discard = $extensionMap.put('js',       ['script', 'JS']))
    #set($discard = $extensionMap.put('php',      ['page_white_php', 'PHP']))
    #set($discard = $extensionMap.put('csproj',   ['page_white_visualstudio', 'VS']))
    #set($discard = $extensionMap.put('sln',      ['page_white_visualstudio', 'VS']))
    #set($discard = $extensionMap.put('res',      ['page_white_visualstudio', 'VS']))
    ## data
    #set($discard = $extensionMap.put('ics',      ['date', 'Calendar']))
    #set($discard = $extensionMap.put('eml',      ['email', 'EMail']))
    #set($discard = $extensionMap.put('vcf',      ['vcard', 'vCard']))
    #set($discard = $extensionMap.put('vcard',    ['vcard', 'vCard']))
    ## executables
    #set($discard = $extensionMap.put('exe',      ['cog', 'EXE']))
    #set($discard = $extensionMap.put('bat',      ['application_xp_terminal', 'Script']))
    #set($discard = $extensionMap.put('sh',      ['application_xp_terminal', 'Script']))
  #end
  #if($mimetypeMap.containsKey($mime))
    #set($image = $mimetypeMap.get($mime).get(0))
    #set($text = $mimetypeMap.get($mime).get(1))
  #elseif($extensionMap.containsKey($ext))
    #set($image = $extensionMap.get($ext).get(0))
    #set($text = $extensionMap.get($ext).get(1))
  #else
    #set($mimetypePrefix = $mime.indexOf('/'))
    #set($mimetypePrefix = $mimetypePrefix + 1)
    #set($mimetypePrefix = $mime.substring(0, $mimetypePrefix))
    #if($mimetypeMap.containsKey($mimetypePrefix))
      #set($image = $mimetypeMap.get($mimetypePrefix).get(0))
      #set($text = $mimetypeMap.get($mimetypePrefix).get(1))
    #else
      #set($image = 'page_white')
      #set($text = 'Attachment')
    #end
  #end
  <img src="$xwiki.getSkinFile("icons/silk/${image}.gif")" alt="${text}" title="${text}"/>
#end
###
###    packName
###
### Display a shorter version of a string
###
### @param name The processed string
###
#macro(packName $name)
#if(!$maxnamelength)
#set($maxnamelength = 25)
#end
#set($idx = $name.lastIndexOf("."))
#if(($idx != 0) && ($idx != -1))
#set($ext = $name.substring($idx))
#else
#set($ext = "")
#set($idx = $name.length())
#end
#set($fname = $name.substring(0, $idx))
#if($fname.length() > $maxnamelength)$fname.substring(0, $maxnamelength)~$ext#else$name#end
#end

#macro(xwikiobjectfield $fielddoc $fieldname $fieldtext $action)
<div class="xmblabel">$fieldtext</div>
<div class="xmbfield">
#if($fieldname!="")
$fielddoc.display($fieldname, $action)
#end
</div>
#end

#macro(formfield $fieldtext $html)
<div class="xmblabel">$fieldtext</div>
<div class="xmbfield">
$html
</div>
#end

#macro(defaultDisplayObj $document $obj)
 #set($class = $obj.xWikiClass)
 #foreach($prop in $class.properties)
  #formfield(${prop.prettyName} $document.display($prop.getName(), "edit", $obj))
 #end
#end

#macro(defaultViewDisplayObj $document $obj)
 #set($class = $obj.xWikiClass)
 #foreach($prop in $class.properties)
  #formfield(${prop.prettyName} $document.display($prop.getName(), "view", $obj))
 #end
#end

##
## Formats a date according to the ISO8601 standard
##
#macro(formatdateISO $date)
#set($tz = $xwiki.formatDate($date, "Z"))
#set($tz = "${tz.substring(0, 3)}:${tz.substring(3)}")
$xwiki.formatDate($date, "yyyy-MM-dd")T$xwiki.formatDate($date, "HH:mm:ss")$tz#end

##
## Formats a username like a fn (hCard microformat)
##
#macro(userfn $username)
#set($fn = $xwiki.getUserName($username))
#if($fn.indexOf("<a") >= 0)
#set($fn = $fn.replaceAll("<a", '<a class="url fn"'))
#else
#set($fn = "<span class='fn'>$fn</span>")
#end
$fn
#end

###
###
### Macros for "foot notes"
###
### TODO:
###       Make Radeox macros
###       Support in wysiwyg
###
###
#macro(footnote $text)
#if(!$page_footnotes)
#set($page_footnotes = $util.arrayList)
#set($footnote_group_id = 1)
#end
#set($discard = $page_footnotes.add($text))
#set($processedText = $text.replaceAll('[*~<>_-]', ''))
#set($footnote_id = $page_footnotes.size())
<sup class="footnoteRef" id="footnoteref_${footnote_group_id}_${footnote_id}"><a href="#footnote_${footnote_group_id}_${footnote_id}" title="$msg.get('core.footnotes.gotofootnote', [${footnote_id}]): {pre}$processedText{/pre}">$footnote_id</a></sup>#end
##
##
##
#macro(putFootnotes)
#if($page_footnotes && ($page_footnotes.size() > 0))
<ol class="footnotes">
#foreach($footnote in $page_footnotes)
<li id="footnote_${footnote_group_id}_${velocityCount}">
 <a class="footnoteBackRef" title="$msg.get("core.footnotes.backtoref")" href="#footnoteref_${footnote_group_id}_${velocityCount}">^</a>
  $footnote</li>
#end
</ol>
#set($discard = $page_footnotes.clear())
#set($footnote_group_id = $footnote_group_id + 1)
#end
#end
##
##
##  Generate navigation links for paged documents
## Deprecated, replaced by #printPagedViewLinks
##
#macro(pagedViewLinks $itemsPerPage $totalPages $crtPageNumber)
#if($totalPages > 0)
<div class="pagedNavigation">
#if($crtPageNumber > 0)
#set($prevPage = $crtPageNumber - 1)
<span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=0&amp;ipp=${itemsPerPage}")">$msg.get("web.paging.firstPage")</a></span>
<span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${prevPage}&amp;ipp=${itemsPerPage}")">$msg.get("web.paging.previousPage")</a></span>
#else
<span class="pagedLink inactive">$msg.get("web.paging.firstPage")</span>
<span class="pagedLink inactive">$msg.get("web.paging.previousPage")</span>
#end
#set($displayCrtPageNumber = $crtPageNumber + 1)
#set($displayTotalPages = $totalPages + 1)
<span class="pagedStatus">$msg.get("web.paging.pageNumberOf", [$displayCrtPageNumber, $displayTotalPages])</span>
#if($crtPageNumber < $totalPages)
#set($nextPage = $crtPageNumber + 1)
<span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${nextPage}&amp;ipp=${itemsPerPage}")">$msg.get("web.paging.nextPage")</a></span>
<span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${totalPages}&amp;ipp=${itemsPerPage}")">$msg.get("web.paging.lastPage")</a></span>
#else
<span class="pagedLink inactive">$msg.get("web.paging.nextPage")</span>
<span class="pagedLink inactive">$msg.get("web.paging.lastPage")</span>
#end
</div>
#end
#end
##
##
##  Generate navigation links for paged documents. It will use the URL parameters "ipp" to forward
## the number of items per page, and "page" to indicate a certain page. The actual range (in items,
## not in pages) can be computer using #preparePagedViewParams. The macro does not print anything
## if only one page exists and $alwaysDisplay is not set to true. Does not alter any variables.
##
## @param itemsPerPage The number of items per page, will be forwarded in the links to other pages.
## @param totalPages The total number of pages, starting at 1.
## @param currentPageNumber The currently displayed page, starting at 1.
## @param additionalQueryParams Query string fragment that should be put in the links. Should not
##        start or end with ? or &
## @param alwaysDisplay Force display of the links, even if there is only one page in total.
##
#macro(printPagedViewLinks $itemsPerPage $totalPages $currentPageNumber $additionalQueryParams $alwaysDisplay)
  ## Only display if there are more than 1 pages or we explicitely require it.
  #if(($totalPages > 1) || $alwaysDisplay)
    <div class="pagedNavigation">
    #if($currentPageNumber > 1)
      #set($currentPageNumber = $currentPageNumber - 1)
      <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=1&amp;ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&amp;$additionalQueryParams#end">$msg.get("web.paging.firstPage")</a></span>
      <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${currentPageNumber}&amp;ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&amp;$additionalQueryParams#end">$msg.get("web.paging.previousPage")</a></span>
      #set($currentPageNumber = $currentPageNumber + 1)
    #else
      <span class="pagedLink inactive">$msg.get("web.paging.firstPage")</span>
      <span class="pagedLink inactive">$msg.get("web.paging.previousPage")</span>
    #end
    <span class="pagedStatus">$msg.get("web.paging.pageNumberOf", [$currentPageNumber, $totalPages])</span>
    #if($currentPageNumber < $totalPages)
      #set($currentPageNumber = $currentPageNumber + 1)
      <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${currentPageNumber}&amp;ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&amp;$additionalQueryParams#end">$msg.get("web.paging.nextPage")</a></span>
      <span class="pagedLink"><a href="$doc.getURL($xcontext.action, "page=${totalPages}&amp;ipp=${itemsPerPage}")#if("$!additionalQueryParams" != "")&amp;$additionalQueryParams#end">$msg.get("web.paging.lastPage")</a></span>
      #set($currentPageNumber = $currentPageNumber - 1)
    #else
      <span class="pagedLink inactive">$msg.get("web.paging.nextPage")</span>
      <span class="pagedLink inactive">$msg.get("web.paging.lastPage")</span>
    #end
    </div>
  #end
#end
##
##
##  Used together with #printPagedViewLinks, computes the range of items to show and the
## variables used by #printPagedViewLinks, $currentPageNumber, $itemsPerPage, $totalPages.
##
## @param totalItems The total number of items that need to be displayed.
## @param defaultItemsPerPage The default number of items per page, if no override is found in the
##        URL. If 0, then display all items.
## @sets startAt The first item to display (inclusive).
## @sets endAt The last item to display (exclusive).
## @sets itemsPerPage The requested number of items per page.
## @sets totalPages The total number of pages according to the requested number of items per page
##        and total items. Starts at 1.
## @sets currentPageNumber The current page displayed. If the requested page is not available (out
##        of range), then it will be corrected to a valid number. Starts at 1.
##
#macro(preparePagedViewParams $totalItems $defaultItemsPerPage)
  ## Reuse existing variable, in case it is manually overriden somewhere else
  #if(!$itemsPerPage)
    #if($request.ipp)
      #set($itemsPerPage = $util.parseInt($request.ipp))
    #else
      #set($itemsPerPage = $defaultItemsPerPage)
    #end
  #end
  ## Page numbers start at 1 outside this macro, but for internal computations we use 0-indexed values.
  #set($currentPageNumber = $util.parseInt($request.page) - 1)
  #if($currentPageNumber < 0)
    #set($currentPageNumber = 0)
  #end
  ## The first item to show. Must be >= 0.
  #set($startAt = $itemsPerPage * $currentPageNumber)
  #if($startAt < 0)
    #set($startAt = 0)
  #end
  ## The last item to show (exclusive). Must be <= total number of items.
  #set($endAt = $itemsPerPage * ($currentPageNumber + 1))
  #if(($endAt > $totalItems) || ($itemsPerPage == 0))
    #set($endAt = $totalItems)
  #end
  ## Never show the items after the last one... They don't exist!
  #if($startAt >= $endAt)
    #set($startAt = $endAt - 1)
  #end
  ## Compute the total number of pages.
  #if($itemsPerPage == 0)
    #set($totalPages = 1)
  #else
    #set($totalPages = ($totalItems - 1) / $itemsPerPage + 1)
  #end
  ## The requested page might not be available, so correct it to correspond to the displayed items.
  #set($currentPageNumber = $startAt / $itemsPerPage + 1)
#end
##
##
## Macro to set a page break used in print, pdf and rtf mode
##
#macro(pagebreak)
<p style="page-break-before: always;" />
#end
##
##
## Macro to include children of a page
##
#set($clevel = 1)
## Deprecated name, use #includeChildren
#macro(includeChilds $page)
 #includeChildren($page false)
#end
## Deprecated name, use #includeChildren
#macro(includeChilds $page $withPageBreaks)
  #includeChildren($page $withPageBreaks)
#end
## Macro to include children at multiple levels
#macro(includeChildren $page $withPageBreaks)
 #if($clevel!=0)
  #foreach($childDocName in $xwiki.searchDocuments("where doc.parent='$page' order by doc.creationDate"))
    #set($childDoc = $xwiki.getDocument($childDocName))
    #if(($childDoc)&&($childDoc.getSpace()!="Panels")&&($childDoc.getSpace()!="XWiki"))
     #if($withPageBreaks)
     #pagebreak()
     #end
     $childDoc.getRenderedContent()
     #set($clevel = $xwiki.add($clevel,-1))
     #includeChildren($childDocName $withPageBreaks)
     #set($clevel = $xwiki.add($clevel,1))
    #end
  #end
 #end
#end

## Macro to include linked pages
#macro(includeLinks $page)
 #includeLinks($page false)
#end
## Macro to include linked pages at multiple levels
#macro(includeLinks $page $withPageBreaks)
 #if($clevel!=0)
  #set($pageDoc = $xwiki.getDocument($page))
  #foreach($child in $pageDoc.getLinks())
    #set($childDocName = $child.getLink())
    #set($childDoc = $xwiki.getDocument($childDocName))
    #if(($childDoc)&&($childDoc.getSpace()!="Panels")&&($childDoc.getSpace()!="XWiki"))
     #if($withPageBreaks)
     #pagebreak()
     #end
     $childDoc.getRenderedContent()
     #set($clevel = $xwiki.add($clevel,-1))
     #includeLinks($childDocName $withPageBreaks)
     #set($clevel = $xwiki.add($clevel,1))
    #end
  #end
 #end
#end

###
###    Panel header
###
### Generate the starting html code for a panel
###
### @param title The panel caption title
###
#macro(panelheader $title)
#set($cookieName = "${xcontext.user}_${panel}")
#set($expanded = $xwiki.getUserPreferenceFromCookie($cookieName))
#if(!$expanded)
  #set($expanded = 'expanded')
#end
## Note: We pass the Panel name as an HTML class attribute so that it's possible to style
## the Panels selectively using CSS.
#set ($specialClassAttribute = "")
#if ($paneldoc && $paneldoc != "")
  #set ($specialClassAttribute = $util.convertToAlphaNumeric($paneldoc.name))
#end
<div class="panel $expanded $specialClassAttribute">
<h1 class="xwikipaneltitle" onclick="XWiki.togglePanelVisibility(this.parentNode, '${cookieName}');">$title</h1>
<div class="xwikipanelcontents">
#end

#macro(panelhiddenheader $title)
## Note: We pass the Panel name as an HTML class attribute so that it's possible to style
## the Panels selectively using CSS.
#set ($specialClassAttribute = "")
#if ($paneldoc && $paneldoc != "")
  #set ($specialClassAttribute = $util.convertToAlphaNumeric($paneldoc.name))
#end
<div class="panel expanded $specialClassAttribute">
<h1 class="xwikipaneltitle hidden">$title</h1>
<div class="xwikipanelcontents">
#end

#macro(largepanelheader $title)
#set($cookieName = "${xcontext.user}_${panel}")
#set($expanded = $xwiki.getUserPreferenceFromCookie($cookieName))
#if(!$expanded)
  #set($expanded = 'expanded')
#end
## Note: We pass the Panel name as an HTML class attribute so that it's possible to style
## the Panels selectively using CSS.
#set ($specialClassAttribute = "")
#if ($paneldoc && $paneldoc != "")
  #set ($specialClassAttribute = $util.convertToAlphaNumeric($paneldoc.name))
#end
<div class="large panel $expanded $specialClassAttribute">
<h1 class="xwikipaneltitle" onclick="XWiki.togglePanelVisibility(this.parentNode, '${cookieName}');">$title</h1>
<div class="xwikipanelcontents">
#end

###
###    Panel footer
###
### Generate the ending html code for a panel
###
#macro(panelfooter)
</div>
</div>
#end

###
###    Display Panel
###
### Extract and display the panel code from the panel object
###
#macro(displaypanel $name)
  #set ($pobj = "")
  ## Since Velocity does not do any assignment if the RHS is null we need to reset the paneldoc
  ## as otherwise the previously set panel will be displayed. getDocument() returns null if the
  ## user doesn't have the right to view a document.
  #set ($paneldoc = "")
  #set ($paneldoc = $xwiki.getDocument($name))
  #if ($paneldoc != "")
    #set ($pobj = $paneldoc.getObject("Panels.PanelClass"))
    #if (!$pobj)
      ## discarded
    #else
      $!doc.display("content", "view", $pobj)
    #end
  #end
#end

#macro(displayPropName $prop)
#if($msg.get("$class.getName()_$prop.name") == "$class.getName()_$prop.name")
$prop.prettyName#else
$msg.get($prop.name)#end
#end

###
###    Display Panel content
###
###
#macro(displaypanelcontent $doc $obj)
$doc.display("content", $obj)
#end

###
###    Toplevel Menu entry with subitems
###
### Generate a menu entry and start the subitem section
###
### @param actionurl The URL this entry points to
### @param linktext The menu item text
###
#macro(xwikitopmenuentrystart $actionurl $linktext $id $class)
#set($sep = '__SEPARATOR__')
<div id="$id" class="$id topmenuentry dropdownmenuentry #if($actionurl == '')dropdownnolink#end $!class" onmouseover="showsubmenu(this);" onmouseout="hidesubmenu(this);">
<span class="tme-extensible">
  #if (!$linktext.contains($sep)) <a class="tme"#if ($actionurl != '') href="$actionurl"#end><strong>$linktext</strong></a>
  #else
    #set ($linktextwords = $linktext.split($sep))
    <span class="tmetype">$linktextwords.get(0): </span><a class="tme hastype" href="$actionurl"><strong>$linktextwords.get(1)</strong></a>
  #end
  <span class="menuarrow">&#9660;</span><span class="hidden menucolon">: </span>
</span><span class="submenu hidden">
#end

###
###    Toplevel Menu entry without subitems
###
### Generate a menu entry withut subitems
###
### @param actionurl The URL this entry points to
### @param linktext The menu item text
###
#macro(xwikitopmenuentry $actionurl $linktext $id $class)
#set($sep = '__SEPARATOR__')
<div id="$id" class="$id topmenuentry $!class">
  #if (! $linktext.contains($sep)) <a class="tme" href="$actionurl"><strong>$linktext</strong></a>
  #else
    #set ($linktextwords = $linktext.split($sep))
    <span class="tmetype">$linktextwords.get(0): </span><a class="tme hastype" href="$actionurl"><strong>$linktextwords.get(1)</strong></a>
  #end
</div>
#end

###
###    Menu subitem entry
###
### Generate a submenu entry
###
### @param actionurl The URL this entry points to
### @param linktext The menu item text
###
#macro(submenuitem $actionurl $linktext $linkid $class)
<span class="submenuitem $!class"><a href="$actionurl" id="$linkid" class="$linkid">$linktext</a></span>
#end

###
###    Menu disabled subitem entry
###
### Generate a disabled submenu entry
###
### @param text The menu item text
###
#macro(submenuitemdisabled $text)
<span class="submenuitem disable">$text</span>
#end

###
###    Toplevel Menu entry separator
###
#macro(xwikitopmenuseparator)
<div class="topmenuentry"><span class="separator">&raquo;</span></div>
#end

###
###    Menu submenu separator
###
#macro(submenuseparator)
<span class="submenuseparator">&nbsp;</span>
#end

###
###    Toplevel Menu entry end
###
### End the subitem section
###
#macro(xwikitopmenuentryend)
</span></div>
#end

###
###    Message box
###
#macro(xwikimessageboxstart $title $message)
    <div class="centered">
    <fieldset class="xwikimessage">
      <legend><span>$title</span></legend>
      <p class="xwikimessage">$message</p>
#end
#macro(xwikimessageboxend)
    </fieldset>
    </div>
#end

#macro(xwikimessagebox $title $message $urlyes $urlno $msgyes $msgno)
#xwikimessageboxstart($title $message)
      <div class="buttons"><a href="$urlyes" class="buttonwrapper"><input type="button" class="button" value="$msgyes" onclick="location='$urlyes'; return false;"/></a><a href="$urlno" class="buttonwrapper"><input type="button" class="button" value="$msgno" onclick="location='$urlno'; return false;"/></a></div>
#xwikimessageboxend()
#end

#macro(xwikimessageboxfield $fielddoc $fieldname $fieldtext $html)
<div class="xmblabel">$fieldtext</div>
<div class="xmbfield">
#if($fieldname!="")
$fielddoc.display($fieldname, "edit")
#end
#if($html!="")
$html
#end
</div>
#end

#macro(xwikimessageboxsubmit $submittext)
<div class="xmbbutton">
<input type="submit" value="$submittext" />
</div>
#end


###
###    message
###

#macro(warning $text)
<div class="warningmessage"><span class="messagetype">$msg.get("warning"): </span>$text</div>
#end

#macro(error $text)
<div class="errormessage"><span class="messagetype">$msg.get("error"): </span>$text</div>
#end

#macro(info $text)
<div class="infomessage">$text</div>
#end

#macro(message $text)
<div class="plainmessage">$text</div>
#end

#macro (floatingbox $text)
<div class="floatinginfobox">$text</div>
#end

#macro (startfloatingbox)
<div class="floatinginfobox">
#end

#macro (endfloatingbox)
</div>
#end

###
###    Display in page panels layout
###
###
#macro(displayPanelLayout $nbcolumns $panelNameList)
  <div class="panellayoutcontainer-${nbcolumns}col">
    #set($lastColumnId = ($nbcolumns - 1))
    #foreach($colId in [0..$lastColumnId])
      <div class="panellayoutcol">
        #foreach($panelName in $panelNameList)
          #if($panelName && ($panelName != "") && (((($velocityCount - 1) + $nbcolumns) % $nbcolumns) == $colId))
            #displaypanel($panelName)
          #end
        #end
      </div>
    #end
  </div>
#end

#**
 * Displays a public google calendar with all buttons and displays
 * The size of the display is 800x600
 *
 * This macro displays the public part of the calendar specified. However if the visiting user is logged in in Google Calendar and has rights to the private part of the calendar then the information will be displayed.
 *
 * @param id ID of the google account to display the calendar for
 *#
#macro(googlecal $id)
{pre}
<iframe src="http://www.google.com/calendar/embed?height=600&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id.replaceAll("@","%40")}&amp;color=%232952A3" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe>
{/pre}
#end

#**
 * Displays a public google calendar with all buttons and displays and a custom size
 *
 * @param id ID of the google account to display the calendar for
 * @param width Width of the calendar
 * @param height Height of the calendar
 *#
#macro(googlecalsize $id $width $height)
#if($width=="")
#set($width = "800")
#end
#if($height=="")
#set($height = "600")
#end
{pre}
<iframe src="http://www.google.com/calendar/embed?height=${height}&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id.replaceAll("@","%40")}&amp;color=%232952A3" style=" border-width:0 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe>
{/pre}
#end

#**
 * Displays a private google calendar with all buttons
 *
 * @param id ID of the google account to display the calendar for
 * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro
 *#
#macro(googlecalprivate $id $token)
{pre}
<iframe src="http://www.google.com/calendar/embed?pvttk=${token}&amp;height=600&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id.replaceAll("@","%40")}&amp;color=%232952A3" style=" border-width:0 " width="800" height="600" frameborder="0" scrolling="no"></iframe>
{/pre}
#end

#**
 * Displays a private google calendar with all buttons
 *
 * @param id ID of the google account to display the calendar for
 * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro
 * @param width Width of the calendar
 * @param height Height of the calendar
 *#
#macro(googlecalprivatesize $id $token $width $height)
#if($width=="")
#set($width = "800")
#end
#if($height=="")
#set($height = "600")
#end
{pre}
<iframe src="http://www.google.com/calendar/embed?pvttk=${token}&amp;height=${height}&amp;wkst=1&amp;bgcolor=%23FFFFFF&amp;src=${id.replaceAll("@","%40")}&amp;color=%232952A3" style=" border-width:0 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe>
{/pre}
#end

#**
 * Displays a public or private google calendar with a wide range of settings
 * You can check the effect of these settings using the Google Calendar Embed Helper
 * http://www.google.com/calendar/embedhelper
 *
 * @param id ID of the google account to display the calendar for
 * @param token Private token giving access to the Calendar. This token is 32 chars long and can be retrieved in the "Agenda Details" when accessing your "Private URL" of your calendar. You should use this parameter with care as it will display all your calendar events to anybody that can access the page in which you use this macro
 * @param width Width of the calendar
 * @param height Height of the calendar
 * @param showTitle 0 to not show the title
 * @param showNav 0 to not show the navigation buttons allowing to switch to previous/next week or month
 * @param showDate 0 to not show the current period displayed
 * @param showPrint 0 to not show the print button
 * @param showTabs 0 to not show the tabs allowing to switch between MONTH,WEEK,AGENDA mode
 * @param showCalendars 0 to not show the calendars list drop down button
 * @param showTz Show a message saying the timezone of the dates/hours
 * @param mode Default mode to display (empty is Month display, WEEK is Week dispaly, AGENDA is the event display)
 * @param language Language to display in (en,fr,de,..)
 * @param bgcolor Background color of the calendar in the form #255455
 * @param color Color of the events in the form #234567
 * @param ctz Timezone in which to display the calendar. Leave empty for default calendar Timezone
 * @param border Border in pixels (1,2,3)
 *#
#macro(googlecalcustom $id $token $width $height $showTitle $showNav $showDate $showPrint $showTabs $showCalendars $showTz $mode $language $bgcolor $color $ctz $border)
#if($width=="")
#set($width = "800")
#end
#if($height=="")
#set($height = "600")
#end
#if($color!="")
#set($color = $color.replaceAll("#","%23"))
#else
#set($color = "%232952A3")
#end
#if($bgcolor!="")
#set($bgcolor = $bgcolor.replaceAll("#","%23"))
#else
#set($bgcolor = "%232952A3")
#end
{pre}
<iframe src="//www.google.com/calendar/embed?showTitle=${showTitle}&amp;showNav=${showNav}&amp;showDate=${showDate}&amp;showPrint=${showPrint}&amp;showTabs=${showTabs}&amp;showCalendars=${showCalendars}&amp;showTz=${showTz}&amp;mode=${mode}&amp;height=${height}&amp;wkst=2&amp;hl=${language}&amp;bgcolor=${bgcolor}&amp;src=${id.replaceAll("@","%40")}&amp;color=${color}&amp;ctz=${ctz}" style=" border:solid ${border}px #777 " width="${width}" height="${height}" frameborder="0" scrolling="no"></iframe>
{/pre}
#end
#**
 * Displays a list of documents.
 * Only documents that the current user is allowed to view will be displayed.
 *
 * @param docNames list of document names.
 * @param displaySpaces true to group documents by space.
 * @param blacklistedSpaces spaces to exclude from the list.
 *#
#macro(displayDocumentList $docNames $displaySpaces $blacklistedSpaces)
  #set($documentList = $util.getArrayList())
  #foreach($docName in $docNames)
    #if($xwiki.hasAccessLevel("view", $xcontext.user, $docName))
      #set($document = $xwiki.getDocument($docName).getTranslatedDocument())
      #if(!$blacklistedSpaces.contains($document.getSpace()))
        #set($discard = $documentList.add($document))
      #end
    #end
  #end
  #if($documentList.size() > 0)
    #set($previousSpace = "")
    <ul class="xlist">
      #foreach($document in $documentList)
        #if ($document.getSpace() != $previousSpace && $displaySpaces)
          #if($velocityCount > 1) </ul></div></li> #end ## Close previous space item if needed
          <li class="xitem space"><div class="xitemcontainer">$document.getSpace()<ul class="xlist"> ## Open new space item
          #set($previousSpace = $document.getSpace())
        #end
        <li class="xitem page"><div class="xitemcontainer"><a href="$document.getURL()">$escapetool.xml($document.getDisplayTitle())</a></div></li>
      #end
      #if($displaySpaces)
        </ul></div></li> ## Close last space item
      #end
    </ul>
  #end
#end
#**
 * Set a variable from request parameters.
 * If the parameter is not present in the request and the variable has not been set
 * earlier in the script, set it to the default value.
 *
 * Note that request parameters will be cast to the type of the defaultValue.
 * Handled types: ArrayList, Boolean, Integer, Float, Long, Double.
 *
 * @param variable the variable to set.
 * @param variableName name of the variable in the calling script and in the request parameters.
 * @defaultValue if the variable has not been set before and is not set in the HTTP request, it is set to this value.
 *#
#macro(setVariableFromRequest $variable $variableName $defaultValue)
  #set($isList = false)
  ## Try to get the variable value from HTTP request.
  #if($defaultValue.class == "class java.util.ArrayList")
    #set($isList = true)
    #set($httpParam = $util.getArrayList())
    #set($rawHttpParam = $request.getParameterValues("${variableName}"))
    #foreach($param in $rawHttpParam)
      #set($discard = $httpParam.add($param))
    #end
    #set($rawHttpParam = "")
  #else
    #set($httpParam = $request.getParameter("${variableName}"))
    #if("$!httpParam" != "")
      #if($defaultValue.class == "class java.lang.Boolean")
        #set($httpParam = $util.parseBoolean($httpParam))
      #elseif($defaultValue.class == "class java.lang.Integer")
        #set($httpParam = $util.parseInt($httpParam))
      #elseif($defaultValue.class == "class java.lang.Float")
        #set($httpParam = $util.parseFloat($httpParam))
      #elseif($defaultValue.class == "class java.lang.Long")
        #set($httpParam = $util.parseLong($httpParam))
      #elseif($defaultValue.class == "class java.lang.Double")
        #set($httpParam = $util.parseDouble($httpParam))
      #end
    #end
  #end
  #if(!$isList && "$!httpParam" != "" || $isList && $httpParam.size() > 0)
    #set($variable = $httpParam)
    #set($httpParam = "")
  #end
  ## If the variable has not been set from velocity, fallback on default.
  #if("$!variable" == "")
    #set($variable = $defaultValue)
  #end
#end
#**
 * Displays a submit button, i.e. an <tt>input</tt> element with <tt>type=submit</tt>.
 * For styling purposes, the button is wrapped in a span element.
 * @param name The value of the <tt>name</tt> attribute
 * @param shortcut The keyboard shortcut for this button. The value will be displayed
 *        as the title of the element. The actual shortcut is attached elsewhere, in
 *        the javascript code.
 * @param value The value of the <tt>value</tt> attribute, i.e. the text displayed on
 *        the button.
 *#
#macro(submitButton $name $shortcut $value)
<span class="buttonwrapper"><input class="button" type="submit" name="$name"#if($keyboardShortcutsEnabled) title="$shortcut"#end value="$value"/></span>
#end
#**
 * Displays a submit button for the editor. This macro calls submitButton,
 * composing all its parameters based on the action's identifier and the
 * identifier of the corresponding localized resources.
 * @param action The identifier of the button's action.
 * @param resourceIdentifier The key used to identify the localized resources.
 *#
#macro(editActionButton $action $resourceIdentifier)
#submitButton("action_${action}", $msg.get("core.shortcuts.edit.${resourceIdentifier}"), $msg.get($resourceIdentifier))
#end

#**
 * Display a human-readable file size
 *
 * @param $size the size in bytes to display in a human readable format
 *#
#macro(dynamicsize $sz)
#if($sz < 1024)
$sz bytes##
#else
#set($ksz = $mathtool.div($sz, 1024))
#set($ksz = $mathtool.roundTo(1, $ksz))
#if($ksz < 1024)
${ksz}kb##
#else
#set($Msz = $mathtool.div($sz, 1048576))
#set($Msz = $mathtool.roundTo(1, $Msz))
${Msz}Mb##
#end##
#end##
#end

#**
 * AJAX Live table that displays XWiki data.
 *
 * Example of usage, in syntax 2.0:
 * <code>
 * {{velocity}}
 * #set($columns = [ "_avatar", "first_name", "last_name", "email"])
 * #set($columnsProperties = {
 *                  "first_name" : { "type" : "text" , "size" : 10, "link" : "view"},
 *                  "last_name" : { "type" : "text" , "size" : 10, "link" : "view"},
 *                  "email" : { "type" : "text" , "size" : 20, "link" : "editor"},
 *                  "_avatar" : { "type" : "none" , "size" : 20, "link" : "none", "html" : "true", "sortable":false }
 *                })
 * #set($options = {  "className":"XWiki.XWikiUsers",
 *                    "translationPrefix" : "xe.index.users.",
 *                    "tagCloud" : true,
 *                    "rowCount": 15,
 *                    "javascriptName" : "MyModule.myTable",
 *                    "description: "The description of this table here", })
 * #livetable("userstable" $columns $columnsProperties $options)
 * {{/velocity}}
 * </code>
 *
 * @param divid the id of the table div
 * @param collist the column list
 * @param colprops the columns properties
 * @param options the livetable options.
 *#
#macro(livetable $divid $collist $colprops $options)
## Do not indent:
#if($xwiki.getCurrentContentSyntaxId() != "xwiki/1.0")


{{html}}
#else {pre} #end
  ##
  ## SX deps.
  ##
  #set($ok = $xwiki.jsfx.use('js/xwiki/table/livetable.js', true))
  #set($ok = $xwiki.ssfx.use('js/xwiki/table/livetable.css', true))
  ##
  ## Options / defaults
  ##
  #if("$!options.translationPrefix" != '') #set($transprefix = $options.translationPrefix) #else #set($transprefix = '') #end
  #if("$!options.selectedColumn" != '')  #set($selectedColumn = $options.selectedColumn) #end
  #if("$!options.defaultOrder" == 'desc') #set($defaultOrder = 'desc') #else #set($defaultOrder = 'asc') #end
  #if("$!options.rowCount" != '') #set($count = $options.rowCount) #else #set($count = 15) #end
  #if("$!options.maxPages" != '') #set($maxPages = $options.maxPages) #else #set($maxPages = 10) #end
  #if("$!options.selectedColumn" != '') #set($selectedColumn = $options.selectedColumn) #end
  #if("$!options.callback" != '') #set($callback = $options.callback) #end
  #if("$!options.tagCloud" == '' || $options.tagCloud == false) #set($tagcloud=false) #else #set($tagcloud = true) #end
  #if("$!options.javascriptName" != '') #set($jsName = $options.javascriptName) #else #set($jsName = 'livetable') #end
  #if("$!options.topFilters" != '') #set($topfilters = $options.topFilters) #end
  #if("$options.pageSize" == '' || $!options.pageSize == false) #set($hasPageSize=false) #else #set($hasPageSize = true) #end
  #if("$!options.pageSizeBounds" != '') #set($pageSizeBounds = $options.pageSizeBounds) #end
  #set($classname = "$!options.className")
  #set($extraparams = "$!options.extraParams")
  ##
  ## Columns informations
  ##
  #set($collist2 = '')
  #set($classparams = '')
  #foreach($colname in $collist)
    #if("$!selectedColumn" == '' && !$colname.startsWith('_'))
      #set($selectedColumn = $colname)
    #end
    #if($colname != '_actions')
      #set($collist2 = "${collist2},${colname}")
      #set($propClassName = "$!{colprops.get($colname).get('class')}")
      #if($propClassName != '')
        #set($classparams = "${classparams}&${colname}_class=${propClassName}")
      #end
    #end
  #end
  #set($collist2 = $collist2.substring(1))
  #if("$!options.url" != '')
    #set($dataurl = $options.url)
  #elseif("$!options.resultPage" != '')
    #set($dataurl = $xwiki.getURL($options.resultPage, 'get', "outputSyntax=plain&transprefix=${transprefix}&classname=$!{classname}&collist=${collist2}&$!{extraparams}${classparams}") )
  #else
    #set($dataurl = $xwiki.getURL('XWiki.LiveTableResults', 'get', "outputSyntax=plain&transprefix=${transprefix}&classname=$!{classname}&collist=${collist2}$!{extraparams}${classparams}"))
  #end
  ##
  ## HTML Table
  ##
<div class="xwiki-livetable-container">
  #if("$!topfilters" !='') #set($hasTopFilters = true) #else #set($hasTopFilters = false) #end
  #if($tagcloud || $hasTopFilters)
  <div class="tipfilters">
  #end
  #if($hasTopFilters)
  <div id="${divid}-topfilters" class="xwiki-livetable-topfilters-tip #if($tagcloud)splitted#end">
    <div>
      <div class="xwiki-livetable-topfilters-container">
      $topfilters
      </div>
      <div class="tippointer">
        <div></div>
      </div>
    </div>
  </div>
  #end
  #if($tagcloud)
    #set($discard = $xwiki.ssx.use('XWiki.TagCloud'))
    <div id="${divid}-tagcloud" class="xwiki-livetable-tagcloud-tip hidden #if($hasTopFilters)splitted#end">
      <div>
        <div class="xwiki-livetable-tagcloud-container">
          <h2>$msg.get('xe.livetable.tags.help')
	        <span>$msg.get('xe.livetable.tags.help.cancel')</span>
          </h2>
          <div class="xwiki-livetable-tagcloud"></div>
        </div>
        <div class="tippointer">
          <div></div>
        </div>
      </div>
    </div>
  #end
  #if($tagcloud || $hasTopFilters)
  </div>
  #end
  <table id="${divid}" class="xwiki-livetable"#if("$!options.description" != '') summary="$options.description"#end>
    <tr>
      <td class="xwiki-livetable-pagination">
        <span id="${divid}-limits" class="xwiki-livetable-limits"></span>
  #if($hasPageSize)
        <span id="${divid}-pagesize" class="xwiki-livetable-pagesize">
            <span>$msg.get('xe.livetable.pagesize.label')</span>
            <span class="xwiki-livetable-pagesize-content" ></span>
        </span>
  #end
        <span id="${divid}-ajax-loader" class="xwiki-livetable-loader hidden">
          <img src="$xwiki.getSkinFile('icons/xwiki/ajax-loader-large.gif')" alt="$msg.get('xe.livetable.loading')" title="" />
        </span>
        <span class="controlPagination">
          <a title="$msg.get('xe.pagination.page.prev.title')" class="prevPagination" href="#"><span class="hidden">$msg.get('xe.pagination.page.prev.title')</span></a>
          <a title="$msg.get('xe.pagination.page.next.title')" class="nextPagination" href="#"><span class="hidden">$msg.get('xe.pagination.page.next.title')</span></a>
        </span>
        <span class="pagination">
          <span class="xwiki-livetable-pagination-text">$msg.get("xe.pagination.page")</span>
          <span class="xwiki-livetable-pagination-content" ></span>
        </span>
      </td>
    </tr>
    <tr>
      <td class="xwiki-livetable-display-container">
        <table class="xwiki-livetable-display">
          <thead class="xwiki-livetable-display-header">
            <tr>
            #set($columnCount = 0)
            #foreach($colname in $collist)
              #set($colprop = $colprops.get($colname))
              #if(("$!colprop.filterable" == '' || $colprop.filterable != false) && "$!colname" != '_actions')
                #set($isFilterable = true)
              #else
                #set($isFilterable = false)
              #end
              #if(("$!colprop.sortable" == '' || $colprop.sortable != false) && "$!colname" != '_actions')
                #set($isSortable = true)
              #else
                #set($isSortable = false)
              #end
              ## Determine the name to be displayed in the column header. Strategy is as following :
              ## - If defined the displayName passed as a column option wins
              ## - If not, and if a i18n prefix has been passed, we use the localization tool with the prefix + the column name
              ## - Finally, we fall back on the column name
              #if("$!colprop.displayName" != '')
                #set($displayName = $colprop.displayName)
              #elseif($transprefix != '')
                #set($displayName = $msg.get("${transprefix}${colname}"))
              #else
                #set($displayName = $colname)
              #end
              #if($colname != '_actions' || $hasAdmin)
              <th class="xwiki-livetable-display-header-text $!colprop.headerClass #if($!colprop.type=='hidden')hidden#end #if($isSortable)sortable #if($colname == $selectedColumn)selected $defaultOrder#else asc#end#end#if ($colname == '_avatar') avatar#end" scope="col">
                #if($isSortable)<a rel="${colname}">#end
                #if($isFilterable && ("$!colprop.type"=="text"||"$!colprop.type"=="number"))<label for="xwiki-livetable-${divid}-filter-${velocityCount}">#end
                $displayName
                #if($isFilterable && ("$!colprop.type"=="text"||"$!colprop.type"=="number"))</label>#end
                #if($isSortable)</a>#end
                #set($columnCount = $mathtool.add($columnCount, 1))
              </th>
              #end
            #end
            </tr>
            <tr class="xwiki-livetable-display-filters">
            #foreach($colname in $collist)
              #set($colprop = $colprops.get($colname))
              #if(("$!colprop.filterable" == '' || $colprop.filterable != false) && "$!colname" != '_actions')
                #set($isFilterable = true)
              #else
                #set($isFilterable = false)
              #end
              #if("$!colprop.type" == 'list' && $isFilterable)
                <td class="xwiki-livetable-display-header-filter">
                #if($colprop.get('class'))
                  #set($propClassName = $colprop.get('class'))
                #else
                  #set($propClassName = $classname)
                #end
                #set($class = $xwiki.getDocument($propClassName).getxWikiClass())
                #set($list = '')
                #set($list = $class.get($colname).getListValues())
                <select id="xwiki-livetable-${divid}-filter-${velocityCount}" name='${colname}'><option value=''>$msg.get('xe.livetable.select.all')</option>
                #set($map = $class.get($colname).getMapValues())
                #foreach($listitem in $list)
                  #set ($l10n_key = "${propClassName}_${colname}_${listitem}")
                  #set ($l10n_value = $msg.get($l10n_key))
                  #if ($l10n_value == $l10n_key)
                    #set ($l10n_value = $map.get($listitem).getValue())
                  #end
                  <option value="$listitem">$l10n_value</option>
                #end
                </select>
                </td>
              #elseif(("$!colprop.type" == 'text' || "$!colprop.type" == 'number') && $isFilterable)
                <td class="xwiki-livetable-display-header-filter"><input id="xwiki-livetable-${divid}-filter-${velocityCount}" name="${colname}" type="text" #if("!$colprop.size" != '') size="${colprop.size}" title="$msg.get('xe.livetable.filters.title', [$msg.get("${transprefix}${colname}")])"#end /></td>
              #elseif("$!colprop.type" == 'hidden')
              #elseif($colname != '_actions' || $hasAdmin)
              <td class="xwiki-livetable-display-header-filter"></td>
              #end
            #end
            </tr>
            <tr class="xwiki-livetable-initial-message">
              <td colspan="${columnCount}">
                <div class="warningmessage">$msg.get('xe.livetable.environmentCannotLoadTableMessage')</div>
              </td>
            </tr>
          </thead>
          <tbody id="${divid}-display" class="xwiki-livetable-display-body"><tr><td>&nbsp;</td></tr></tbody>
        </table>
      </td>
    </tr>
    <tr>
      <td class="xwiki-livetable-pagination">
        <span class="controlPagination">
          <a title="$msg.get('xe.pagination.page.prev.title')" class="prevPagination" href="#"><span class="hidden">$msg.get('xe.pagination.page.prev.title')</span></a>
          <a title="$msg.get('xe.pagination.page.next.title')" class="nextPagination" href="#"><span class="hidden">$msg.get('xe.pagination.page.next.title')</span></a>
        </span>
        <span class="pagination">
          <span class="xwiki-livetable-pagination-text">$msg.get('xe.pagination.page')</span>
          <span class="xwiki-livetable-pagination-content" ></span>
        </span>
      </td>
    </tr>
  </table>
  <div id="${divid}-inaccessible-docs" class="hidden">
    #info($msg.get('rightsmanager.documentrequireviewrights'))
  </div>
  <script type="text/javascript">
  //<![CDATA[
(function() {
 var startup = function() {
  if (typeof XWiki !== "undefined" && typeof XWiki.widgets !== "undefined" && typeof XWiki.widgets.LiveTable !== "undefined") {
    // Make sure the Livetable widgets exists (It does not in the WYSIWYG for example).
  #if($callback)
    $jsName = new XWiki.widgets.LiveTable("$dataurl", "${divid}", $callback ,{
                         "maxPages":$maxPages
	                    ,"limit":$count
     #if($hasTopFilters),"filterNodes" : [$("${divid}").down(".xwiki-livetable-display-filters"), $('${divid}-topfilters')]#end
     #if($hasPageSize && "$!pageSizeBounds" != ''),"pageSizeBounds" : $pageSizeBounds#end
	          });
  #else
    $jsName = new XWiki.widgets.LiveTable("$dataurl", "${divid}", #livetablecallback($divid $collist $colprops $transprefix), {
                         "maxPages":$maxPages
	                    ,"limit":$count
     #if($hasTopFilters),"filterNodes" : [$("${divid}").down(".xwiki-livetable-display-filters"), $('${divid}-topfilters')]#end
     #if($hasPageSize && "$!pageSizeBounds" != ''),"pageSizeBounds" : $pageSizeBounds#end
	          });
  #end
  #if($!hasPageSize)
    document.observe("xwiki:livetable:${divid}:loadingEntries", function() { $('${divid}-pagesize').addClassName("hidden"); } );
    document.observe("xwiki:livetable:${divid}:loadingComplete", function() { $('${divid}-pagesize').removeClassName("hidden"); } );
  #end
  }
 }
 if ((typeof(XWiki) != 'undefined') && (typeof(XWiki.widgets) != 'undefined') && (typeof(XWiki.widgets.LiveTable) != 'undefined')) {
   startup();
 } else {
   document.observe('xwiki:dom:loading', startup);
 }
})();
   //]]>
  </script>
</div> ## xwiki-livetable-container
  #if($xwiki.getCurrentContentSyntaxId() != "xwiki/1.0"){{/html}}

#else {/pre} #end
#end

#**
 * Internal macro - Used by the livetable macro to generate a JavaScript anonymous function
 * that is passed to the LiveTable object constructor. This is function is dynamically written
 * according to columns properties passed to the livetable macro.
 *
 * @param collist the list of columns
 * @param colprops the columns properties
 * @param transprefix the translation prefix
 *
 * @internal
 *#
#macro(livetablecallback $divid $collist $colprops $transprefix)
function (row, i, table) {
  // This callback method code has been generated from velocity.
  var tr = new Element("tr");
  if (row.doc_viewable) {
  #foreach($colname in $collist)
    // $colname
    #set($colprop = $colprops.get($colname))
    #if("$!colprop.type"!="hidden")
      #if($colname.indexOf("doc.")==0)
        #set($jscolname = $colname.replaceAll("doc.", "doc_"))
      #else
        #set($jscolname = $colname)
      #end
      ## Is the td element bound to a link ?
      #if("$!colprop.link" != "" && "$!colname" != "_actions")
        #set($tdClass = "${jscolname} link$!{colprop.link} type$!{colprop.type}")
        var td = new Element("td", {'class':"$tdClass"});
        var link = #if("$!colprop.link" != "editor") new Element("a"); #else new Element("span"); #end
        ## Automatic: the link url is in JSON results, with key column name + "_url"
        #if("$!colprop.link"=="auto")
          link.href = (row.${jscolname}_url=="") ? row.doc_url : row.${jscolname}_url;
        #elseif($colprop.link=="field")
          if (row.${jscolname}_url != "") {
            link.href = row.${jscolname}_url;
          }
        ## Property editor
        #elseif($colprop.link=="editor")
          #if($colprop.get("class"))
            #set($propClassName = $colprop.get("class"))
          #else
            #set($propClassName = $className)
          #end
          td.observe("click", function(event){
            var tag = event.element().down("span");
            if (!tag)
             tag = event.element();
            editProperty(row.doc_fullname, "${propClassName}", "${colname}", function(value) { tag.innerHTML = value});
          });
        ## Author
        #elseif($colprop.link == "author")
          link.href = row.doc_author_url;
        ## Space URL
        #elseif($colprop.link == "space")
          link.href = row.doc_space_url;
        ## Wiki URL
        #elseif($colprop.link == "wiki")
          link.href = row.doc_wiki_url;
        #else
          link.href = row.doc_url;
        #end
        #if($colprop.html && $colprop.html==true)
          link.innerHTML = row.${jscolname};
        #else
          link.update(row.${jscolname});
        #end
        td.appendChild(link);
        tr.appendChild(td);
      #elseif("$colname" == "_actions")
        if(row.doc_hasadmin) {
          var td = new Element("td", {'class':'actions'});
          #foreach($action in $colprop.get("actions"))
            #if($velocityCount > 1)
            td.insert(" ");
            #end
            #if($transprefix != '' && $msg.get("${transprefix}_actions.${action}") != "${transprefix}_actions.${action}")
              #set($text = $msg.get("${transprefix}_actions.${action}"))
            #elseif($msg.get("xe.livetable._actions.${action}") != "xe.livetable._actions.${action}")
              #set($text = $msg.get("xe.livetable._actions.${action}"))
            #else
              #set($text = "$action")
            #end
            var link = new Element("a", {"href": row.doc_${action}_url, "class":"action action${action}"}).update("$text");
            #if("$!colprop.ajaxActions.get($action)" == 'true')
              link.observe('click', function(event) {
                event.stop();
                new Ajax.Request(link.href, {
                  onSuccess : function() {
                    $colprop.actionCallbacks.get($action)
                  }
                });
              });
            #end
            td.insert(link);
          #end
          tr.appendChild(td);
        }
      #else
        #set($tdClass = "${jscolname} link$!{colprop.link} type$!{colprop.type}")
        var fieldel = new Element("td", {'class':"$tdClass"});
        #if($colprop.html && $colprop.html==true)
          fieldel.innerHTML = row.${jscolname};
        #else
          fieldel.update(row.${jscolname});
        #end
        tr.appendChild(fieldel);
      #end
    #end
  #end
  }
  else {
    var page = row.doc_fullname;
    var dp = page.indexOf(':');
    var p = page.indexOf('.');
    var space = (dp > 0) ? page.substring(dp + 1, p) : page.substring(0, p);
    var name = page.substring(p + 1);
    #foreach($colname in $collist)
      #if("$!colprop.type"!="hidden")
        #if($colname.indexOf("doc.")==0)
         #set($jscolname = $colname.replaceAll("doc.", "doc_"))
        #else
         #set($jscolname = $colname)
        #end
        #if($jscolname == "doc_name")
          tr.insert(new Element("td").update(name + "*"));
        #elseif($jscolname == "doc_space")
          tr.insert(new Element("td").update(space));
        #elseif($jscolname != "_actions")
          tr.insert(new Element("td").update(" "));
        #end
      #end
    #end
    $('${divid}-inaccessible-docs').removeClassName('hidden');
  }
  return tr;
}
#end
##
##
#**
 * Pagination 2.0
 *
 * Displays a generic pagination widget for browsing a collection of items.
 * The macro is responsible for displaying browsing links, and does not involve the actual display of the browsed items.
 *
 * @param parameters A map of parameters:
 * <dl>
 *   <dt>url</dt>
 *   <dd>The base url of the document displaying the collection.</dd>
 *   <dd>Default: $doc.getURL('view')</dd>
 *   <dt>totalItems</dt>
 *   <dd>The total number number of items in the collection.</dd>
 *   <dd>Default: none, this parameter is mandatory.</dd>
 *   <dt>defaultItemsPerPage</dt>
 *   <dd>The number of items per page. This value is overwritten by the request parameter "perPage", if it exists and
 *       has a valid positive integer value.</dd>
 *   <dd>Default: 20</dd>
 *   <dt>position</dt>
 *   <dd>The placement of the pagination widget. Supported values: "top", "bottom". The bottom widget only displays
 *       pages, while the top widget also provides a information about the item range on the current page.</dd>
 *   <dd>Default: top</dd>
 *   <dt>itemParamName</dt>
 *   <dd>The name of the request parameter for the index of the first displayed item.</dd>
 *   <dd>Default: firstIndex</dd>
 *   <dt>itemsPerPageParamName</dt>
 *   <dd>The name of the request parameter for the number of items displayed on a page.</dd>
 *   <dd>Default: perPage</dd>
 * </dl>
 *#
#macro(pagination $parameters)
  $xwiki.ssfx.use('uicomponents/pagination/pagination.css', true)##
  #if("$!{parameters.url}" == '')
    #set($parameters.url = $doc.getURL('view'))
  #end
  #if(!$parameters.url.contains('?'))
    #set($parameters.url = "${parameters.url}?")
  #end
  #if($util.parseInt("$!{parameters.defaultItemsPerPage}") <= 0)
    #set($parameters.defaultItemsPerPage = 20)
  #end
  #if($parameters.position != 'bottom')
    #set($parameters.position = 'top')
  #end
  #paginationPrepareParams($parameters)
  #paginationDisplay($parameters)
#end
#**
 * Pagination : request parameters preparation
 *
 * Used internally by the pagination macro. Retrieves pagination paramemer values from the request:
 * "firstIndex" = the index of the first displayed item; "perPage" = number of items per page
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationPrepareParams $parameters)
  ## Setting some defaults
  #if("$!{parameters.itemParamName}" == '')
    #set($parameters.itemParamName = 'firstIndex')
  #end
  #if("$!{parameters.itemsPerPageParamName}" == '')
    #set($parameters.itemsPerPageParamName = 'perPage')
  #end
  ## Get starting item number from request
  #set($parameters.firstItem = "$!{request.get($parameters.itemParamName)}")
  ## If the value is missing or invalid, parseInt returns 0, which is the default first item.
  #set($parameters.firstItem = $util.parseInt($parameters.firstItem))
  ## Get number of items per page from request
  #set($parameters.itemsPerPage = "$!{request.get($parameters.itemsPerPageParamName)}")
  #set($parameters.itemsPerPage = $util.parseInt($parameters.itemsPerPage))
  #if($parameters.itemsPerPage <= 0)
    #set($parameters.itemsPerPage = $parameters.defaultItemsPerPage)
  #end
#end
#**
 * Pagination : display the pagination widget after all parameters have been computed
 *
 * Used internally by the pagination macro.
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationDisplay $parameters)
  #set($parameters.pageCount = ($parameters.totalItems + $parameters.itemsPerPage - 1) / $parameters.itemsPerPage)
  #if($parameters.firstItem >= $parameters.totalItems)
    #set($parameters.firstItem = ($parameters.pageCount - 1) * $parameters.itemsPerPage)
  #elseif($parameters.firstItem < 0)
    #set($parameters.firstItem = 0)
  #end
  #set($parameters.crtPage = $parameters.firstItem / $parameters.itemsPerPage)
  ## Make firstItem a multiple of itemsPerPage
  #set($parameters.firstItem = $parameters.crtPage * $parameters.itemsPerPage)
  #set($parameters.lastPage = $parameters.pageCount - 1)
  <div class="paginationFilter">
    #if($parameters.position == 'top')
      #paginationResultsRange($parameters)
    #end
    #if($parameters.totalItems > 0)
      #paginationControl($parameters)
      #paginationPages($parameters)
    #end
  </div>
#end
#**
 * Pagination : display links for browsing pages
 *
 * Used internally by the pagination macro.
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationPages $parameters)
## $url $crtPage $itemsPerPage $lastPage $pageCount $itemParamName $itemsPerPageParamName)
  #set($contextLeft  = 4)
  #set($contextRight = 4)
  #set($contextWidth = $contextLeft + 1 + $contextRight)
  #if($parameters.pageCount <= $contextWidth)
    #set($contextFirstPage = 0)
    #set($contextLastPage = $parameters.pageCount - 1)
  #else
    #set($contextFirstPage = $parameters.crtPage - $contextLeft)
    #set($contextLastPage = $parameters.crtPage + $contextRight)
    #if($contextFirstPage < 0)
      #set($contextFirstPage = 0)
    #end
    #if($contextLastPage >= $parameters.pageCount)
      #set($contextLastPage = $parameters.pageCount - 1)
    #end
    #if($contextLastPage < $contextWidth)
      #set($contextLastPage = $contextWidth - 1)
    #end
    #if($contextFirstPage > $parameters.pageCount - $contextWidth)
      #set($contextFirstPage = $parameters.pageCount - $contextWidth)
    #end
  #end
  <span class="pagination">$msg.get('xe.pagination.page')
  #if($contextFirstPage != 0)
    #paginationPageLink(0 $parameters)
  #end
  #if($contextFirstPage > 1) ... #end
  #foreach ($i in [$contextFirstPage .. $contextLastPage])
    #paginationPageLink($i $parameters)
  #end
  #if($parameters.lastPage - $contextLastPage > 1) ... #end
  #if($contextLastPage != $parameters.lastPage)
    #paginationPageLink($parameters.lastPage $parameters)
  #end
  </span>
#end
#**
 * Pagination : display the link to a certain page (indicated by $pageNumber)
 *
 * Used internally by the pagination macro.
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationPageLink $pageNumber $parameters)
  #set($firstItem = $pageNumber * $parameters.itemsPerPage)
  #set($displayedPageNumber = $pageNumber + 1)
  #if($pageNumber == $parameters.crtPage)
  <span class="currentPage">$displayedPageNumber</span>
  #else
    <a href="${parameters.url}&amp;${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&amp;${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end" title="$msg.get('xe.pagination.page.title', [$displayedPageNumber])">$displayedPageNumber</a>
  #end
#end
#**
 * Pagination : display prev / next links
 *
 * Used internally by the pagination macro.
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationControl $parameters)
  <span class="controlPagination">
  #if($parameters.crtPage > 0)
    #set($prevPage = $parameters.crtPage - 1)
    #set($firstItem = $prevPage * $parameters.itemsPerPage)
    <a href="${parameters.url}&amp;${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&amp;${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end" title="$msg.get('xe.pagination.page.prev.title')" class="prevPagination">$msg.get('xe.pagination.page.previous')</a>
  #else
    <span class="noPrevPagination"> </span>
  #end
  #if($parameters.crtPage < $parameters.lastPage)
    #set($nextPage = $parameters.crtPage + 1)
    #set($firstItem = $nextPage * $parameters.itemsPerPage)
    <a href="${parameters.url}&amp;${parameters.itemParamName}=${firstItem}#if($parameters.itemsPerPage != $parameters.defaultItemsPerPage)&amp;${parameters.itemsPerPageParamName}=${parameters.itemsPerPage}#end" title="$msg.get('xe.pagination.page.next.title')" class="nextPagination">$msg.get('xe.pagination.page.next')</a>
  #else
    <span class="noNextPagination"> </span>
  #end
  </span>
#end
#**
 * Pagination : message informing the user which items are being displayed on the current page (Results i - j of N)
 *
 * Used internally by the pagination macro.
 *
 * @see #pagination
 * @internal
 *#
#macro(paginationResultsRange $parameters)
  #set($from = $parameters.firstItem + 1)
  #set($to =   $parameters.firstItem + $parameters.itemsPerPage)
  #if ($to > $parameters.totalItems)
    #set($to = $parameters.totalItems)
  #end
  <span class="resultsNo">
  #if($parameters.totalItems == 0)
    <span class='currentResultsNo'>$msg.get('xe.pagination.results.none')</span>
  #elseif($parameters.totalItems == 1)
    <span class='currentResultsNo'>$msg.get('xe.pagination.results.one')</span>
  #elseif($from == $parameters.totalItems)
    $msg.get('xe.pagination.results.single', [$from, $parameters.totalItems])
  #else
    $msg.get('xe.pagination.results.many', [$from, $to, $parameters.totalItems])
  #end
  </span>
#end

#**
  * Hides the element that will be replaced by the WYSIWYG editor and shows the loading animation instead.
  *
  * @param $fieldId identifies the form field that will be replaced by the WYSIWYG editor
  *#
#macro(wysiwyg_hide $fieldId)
<script type="text/javascript">
//<![CDATA[
(function() {
  var field = document.getElementById('$!{fieldId}');
  if (field) {
    // Hide the element that will be wrapped by the WYSIWYG editor.
    field.style.visibility = 'hidden';
    // Show the loading animation.
    var loading = document.createElement('span');
    loading.className = 'loading';
    loading.style.display = 'block';
    loading.style.position = 'absolute';
    loading.style.width = field.offsetWidth + 'px';
    loading.style.height = field.offsetHeight + 'px';
    field.parentNode.insertBefore(loading, field);
    // Remove the loading animation after the WYSIWYG module has been loaded.
    Wysiwyg.onModuleLoad(function() {
      loading.parentNode.removeChild(loading);
    });
  }
}).call();
//]]>
</script>
#end

#**
  * Imports the JavaScript files required by the WYSIWYG editor.
  *
  * @param $lazy {@code true} to download the WYSIWYG code only when it is needed, {@code false} to download it when the page is loaded
  *#
#macro(wysiwyg_import $lazy)
## SmartClient (used by the XWikiExplorer)
$xwiki.jsfx.use("js/smartclient/initsc.js", {"forceSkinAction": true, 'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_Core.js", {'defer': false})
## TODO: remove the following line when http://forums.smartclient.com/showthread.php?t=3097 will be fixed
$xwiki.jsfx.use("js/smartclient/overwritesc.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_Foundation.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_Containers.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_Grids.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_Forms.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/modules/ISC_DataBinding.js", {'defer': false})
$xwiki.jsfx.use("js/smartclient/skins/Enterprise/load_skin.js", {'defer': false})
## XWikiExplorer (used by the link plug-in)
$xwiki.jsfx.use("js/xwiki/xwikiexplorer/xwikiexplorer.js", {"forceSkinAction": true, 'defer': false})
## WYSIWYG
$xwiki.jsfx.use("js/xwiki/wysiwyg/xwe/XWikiWysiwyg.js", {"forceSkinAction": true, "lazy": ${lazy}, 'defer': false})
#end

#**
  * Displays the ConversionFilter error for the specified field, if any. The ConversionFilter is executed before the
  * SaveAction and converts the HTML output of all the WYSIWYG editors to the corresponding storage syntax. If the
  * ConversionFilter catches any exception during the convesion then it redirects the request back preventing the user
  * from loosing unsaved changes and allowing us to display the exception.
  *
  * @param $parameters WYSIWYG editor configuration parameter map including the id of the field for which to display the
  *                    conversion errors
  *#
#macro(wysiwyg_displayConversionError $parameters)
#set($fieldId = $parameters.hookId)
#if("$!{request.key}" != "")
#set($sessionErrors = $request.getSession().getAttribute("com.xpn.xwiki.wysiwyg.server.converter.errors"))
#if($sessionErrors && $sessionErrors.containsKey($request.key))
#set($requestErrors = $sessionErrors.get($request.key))
#if($requestErrors && $requestErrors.containsKey($fieldId))
#set($fieldError = $requestErrors.get($fieldId))
#if($fieldError)
#set($ok = $parameters.put('convertInput', false))
#error("${fieldId}: ${fieldError.message}")
#set($ok = $requestErrors.remove($fieldId))
#if($requestErrors.isEmpty())
#set($ok = $sessionErrors.remove($request.key))
#end
#end
#end
#end
#end
#end

#**
  * Creates the input hidden whose value will be used to cache the state of the WYSIWYG editor in order to preserve it
  * when the user navigates away from the edit page and restore it when the user comes back.
  *
  * @param $parameters WYSIWYG editor configuration parameter map to put the cache id in
  *#
#macro(wysiwyg_createCache $parameters)
#set($ok = $parameters.put('cacheId', "wysiwygCache$!{util.generateRandomString(4)}"))
<input type="hidden" id="$!{parameters.cacheId}" />
#end

#**
  * Writes the WYSIWYG configuration parameters to a JavaScript variable.
  *
  * @param $jsVarName the name of the JavaScript variable to write the WYSIWYG configuration parameter to
  * @param $parameters WYSIWYG editor configuration parameters
  *#
#macro(wysiwyg_writeConfig $jsVarName $parameters)
<script type="text/javascript">
//<![CDATA[
var $jsVarName = {
#set($separator = '')
#foreach($entry in $parameters.entrySet())
  ${separator}$entry.key: '$!{escapetool.javascript($entry.value)}'
#set($separator = ',')
#end
};
//]]>
</script>
#end

#**
  * Stores the WYSIWYG configuration in a map of (parameter, value) pairs.
  *
  * @param $parameters the map of parameters where the WYSIWYG configuration will be stored
  * @param $editedDocument the document being edited
  * @param $fieldId identifies the form field to be replaced by the WYSIWYG editor
  * @param $full {@code true} to use a fully-fledged editor, {@code false} to use the compact editor
  *#
#macro(wysiwyg_storeConfig $parameters $editedDocument $fieldId $full)
#if(!$parameters.containsKey('hookId'))
#set($ok = $parameters.put('hookId', $fieldId))
#end
#set($ok = $parameters.put('syntax', $editedDocument.syntax.toIdString()))
#set($ok = $parameters.put('convertInput', true))
#set($ok = $parameters.put('inputURL', $editedDocument.getExternalURL('edit', "xpage=wysiwyginput&token=${services.csrf.getToken()}")))
#if($full)
#set($ok = $parameters.put('displayTabs', 'true'))
#set($ok = $parameters.put('defaultEditor', 'wysiwyg'))
#end
#set($ok = $parameters.put('plugins', $xwiki.getXWikiPreference('wysiwyg.plugins', "submit line separator embed text color valign list indent history format font color symbol link image table macro import#if($full && $request.sync) sync#end")))
#set($ok = $parameters.put('menu', $xwiki.getXWikiPreference('wysiwyg.menu', 'link image table macro import')))
#set($ok = $parameters.put('toolbar', $xwiki.getXWikiPreference('wysiwyg.toolbar', 'fontname fontsize forecolor backcolor | bold italic underline strikethrough | subscript superscript | unorderedlist orderedlist | outdent indent | undo redo | format | hr symbol | paste')))
#set($ok = $parameters.put('wiki', $editedDocument.wiki))
#set($ok = $parameters.put('space', $editedDocument.space))
#set($ok = $parameters.put('page', $editedDocument.name))
#if("$!{oomanager.serverState}" == "Connected")
#set($ok = $parameters.put('openofficeServerConnected', 'true'))
#end
#if($full && $request.sync)
#set($ok = $parameters.put('syncPage', $editedDocument.fullName))
#if("$!{request.reset}" != "")
#set($ok = $parameters.put('syncReset', $request.reset))
#end
#end
#if("$!{request.debug}" != "")
#set($ok = $parameters.put('debug', $request.debug))
#end
#end

#**
  * Creates a new WYSIWYG editor instance using the given configuration parameters.
  *
  * @param $parameters WYSIWYG editor configuration parameters
  *#
#macro(wysiwyg_createEditor $parameters)
#set($jsVarName = "wysiwygConfig${util.generateRandomString(4)}")
#wysiwyg_writeConfig($jsVarName $parameters)
<script type="text/javascript">
//<![CDATA[
Wysiwyg.onModuleLoad(function() {
  new WysiwygEditor($jsVarName);
  $jsVarName = undefined;
});
//]]>
</script>
#end

#**
  * Loads the GWT-based WYSIWYG editor for the specified object property. The special "content" document property is
  * also supported.
  *
  * @param $editedDocument the document whose objects are being edited
  * @param $propertyIds A comma separated list of property identifiers. An example of a property identifier is "XWiki.ArticleClass_0_content".
  * @param $full {@code true} to use a fully-fledged editor, {@code false} to use a compact editor
  *#
#macro(wysiwyg_editProperty $editedDocument $propertyId $full)
#set($parameters = $util.hashMap)
#wysiwyg_storeConfig($parameters $editedDocument $propertyId $full)
#wysiwyg_editPropertyCustom($editedDocument $parameters)
#end

#**
  * Loads the GWT-based WYSIWYG editor for the specified object property, using the given configuration parameters. The
  * special "content" document property is also supported.
  *
  * @param $editedDocument the document whose objects are being edited
  * @param $parameters WYSIWYG editor configuration parameters
  *#
#macro(wysiwyg_editPropertyCustom $editedDocument $parameters)
## Hide the plain text area.
#wysiwyg_hide($parameters.hookId)
## Import required JavaScript files (lazy=false).
#wysiwyg_import(false)
## Display conversion errors, if present.
#wysiwyg_displayConversionError($parameters)
## Create the cache.
#wysiwyg_createCache($parameters)
## Create the editor UI.
#wysiwyg_createEditor($parameters)
#end

#**
  * Loads the GWT-based WYSIWYG editor for the specified object properties, using the default configuration.
  *
  * @param $editedDocument the document whose objects are being edited
  * @param $propertyIds A comma separated list of property identifiers. An example of a property identifier is "XWiki.ArticleClass_0_content".
  * @param $full {@code true} to use a fully-fledged editor, {@code false} to use a compact editor
  *#
#macro(wysiwyg_editProperties $editedDocument $propertyIds $full)
#set($parameters = $util.hashMap)
#wysiwyg_storeConfig($parameters $editedDocument '' $full)
#wysiwyg_editPropertiesCustom($editedDocument $propertyIds $parameters)
#end

#**
  * Loads the GWT-based WYSIWYG editor for the specified object properties, using the given configuration parameters.
  *
  * @param $editedDocument the document whose objects are being edited
  * @param $propertyIds A comma separated list of property identifiers. An example of a property identifier is "XWiki.ArticleClass_0_content".
  * @param $parameters WYSIWYG editor configuration parameters
  *#
#macro(wysiwyg_editPropertiesCustom $editedDocument $propertyIds $parameters)
#set($instanceParameters = $util.hashMap)
#set($ok = $instanceParameters.putAll($parameters))
#set($propertyIds = "$!propertyIds")
#foreach($propertyId in $propertyIds.split(","))
#set($ok = $instanceParameters.put('hookId', $propertyId))
#wysiwyg_editPropertyCustom($editedDocument $instanceParameters)
#end
#end
