<%def name="formatting()">
    <div class="formatting">
        ${h.help_link(_("formatting hints"), 'formatting')|n}
    </div>
</%def>

<%def name="freetext(name, placeholder=None)">
    <textarea name="${name}"
    %if placeholder:
        placeholder="${placeholder}"
    %endif
    ></textarea>
    ${formatting()}
</%def>

<%def name="headline()">

</%def>


<%def name="admin_controls()">
<div class="admin_controls">
    ${caller.body()}
</div>
</%def>


<%def name="build_infobox()">
<div class="info_box to_hide">
    <a class="close_button only-js" href="#">close</a>
    ${caller.body()}
</div>
</%def>


<%def name="flashmessages()">
<% messages = h.sorted_flash_messages() %>
%if messages:
    %for message in messages:
    <div class="alert alert-${message.category}" role="${'alert' if message.category == 'error' else 'status'}">
        <a class="close only-js" data-dismiss="alert" href="#">x</a>
        ${message.message|n}
    </div>
    %endfor
%endif
</%def>


<%def name="savebox(cancel_url, save_text=None, save_value='save')">
    <%
    save_text = save_text if save_text is not None else _("Save")
    %>
    <div class="savebox">
        <button type="submit" class="button"
                value="${save_value}">
            ${save_text}
        </button>
        %if cancel_url is not None:
            <span class="cancel">
                ${_("or")}
                <a href="${cancel_url}"
                   target="_self"
                >${_("cancel")}</a>
            </span>
        %endif
    </div>
</%def>


<%def name="form_watch(entity, checked=False)">
    %if can.watch.create():
    <%
        if entity:
            checked = checked or (h.find_watch(entity) is not None)
        %>
        <label for="watch">
        <input class="watch" type="checkbox" ${'checked="checked"' if checked else '' | n} name="watch" id="watch" />
        ${_("Notify me of updates.")}
        </label>
    %endif
</%def>


<%def name="watch(entity, id=None, show_skip=True)">
    ## FIXME: turn into an ajax call
    %if c.user:
    <%
    if isinstance(entity, model.Page):
        follow_text = _("Follow Norm")
    elif isinstance(entity, model.Instance):
        follow_text = _("Follow Instance")
    elif isinstance(entity, model.Proposal):
        follow_text = _("Follow Proposal")
    elif isinstance(entity, model.Milestone):
        follow_text = _("Follow Milestone")
    elif isinstance(entity, model.User):
        follow_text = _("Follow User")
    elif isinstance(entity, model.Comment):
        follow_text = _("Follow Comment")
    elif isinstance(entity, model.Tag):
        follow_text = _("Follow Tag")
    else:
        log.error('Unknown entity for watch button: %s' % entity)
    if id is None:
        id_attr = ''
    else:
        id_attr = 'id=%s'%id

    skip = False
    watch = h.find_watch(entity)

    if watch and can.watch.delete(watch):
        css_cls = "active"
        text = _('Following')
        hover_text = _('Unfollow')
        tooltip = _('Disable email notifications.')
        href = h.base_url('/watch/delete?%s' % h.url_token(),
                          query_params={'watch': str(watch.id)})
    elif not watch and can.watch.create():
        css_cls = ""
        text = hover_text = follow_text
        tooltip = _('Receive email notifications if changes occur.')
        href = h.base_url('/watch/create?%s' % h.url_token(),
                          query_params={'ref': str(h.make_watch(entity))})
    else:
        skip = True
    %>
    %if skip:
    %if show_skip:
    <div class="skip_follow">
        <%doc>
        placeholder div to fill the space if we cannot render a widget.
        FIXME: What if a user is authenticated, but is not allowed
        to watch/unwatch
        </%doc>
    </div>
    %endif
    %else:
    <a ${id_attr} class="follow_paper ${css_cls}" href="${href}"
       data-text="${text}" data-hover-text="${hover_text}"
       title="${tooltip}">${text}</a>
    %endif

    %else:
    ## (not c.user)
    <div class="skip_follow">
        <%doc>
        FIXME: render a replacement with auth instructions. Problem:
        FIXME: How to determinate if login and join the instance is enough?
        </%doc>
    </div>
    %endif
</%def>


<%def name="message_button(entity)">
    <%
    if isinstance(entity, model.Instance):  # not yet implemented
        text = _("Message to Members")
    elif isinstance(entity, model.Proposal):
        text = _("Message")
    elif isinstance(entity, model.User):
        text = _("Message")
    else:
        log.error('Unknown entity for message button: %s' % entity)

    if isinstance(entity, model.User):
        permission = can.user.message(entity)
    elif isinstance(entity, model.Proposal):
        permission = can.proposal.message(entity)
    else:
        permission = can.instance.message(c.instance)

    href = h.entity_url(entity, member='message/new')
    %>

    %if permission:
    <a class="message_button" href="${href}">${text}</a>
    %endif
</%def>


<%def name="vertical_tabs(items, css_class, current_variant=None)">
<nav>
    <div id="sidebar_nav" class="${css_class}"><div>
        <ul>
            %for item in items:
            <li>
                <a href="${item['href']}"
                   data-bind="click: function() {loadVariant('${item['variant']}', '${item['href']}')},
                              css: {current: variants.current.variant() === '${item['variant']}'}"
                   class="${'current' if current_variant == item['variant'] else ''}">
                    <span class="truncate">${item['title']}</span>
                    <span class="count">${item['rendered_score']}</span>
                </a>
            </li>
            %endfor
        </ul>
    </div></div>
</nav>
</%def>


<%def name="social_share_buttons(title)">
%if h.config.get_bool('adhocracy.show_social_buttons'):
<%
h.need.socialshareprivacy
base_url = h.get_socialshareprivacy_url()
text = "%s - %s: %s" % (h.site.name(), c.instance.label, title)
%>
<div id="socialshareprivacy"></div>
<script type="text/javascript">
$(document).ready(function () {
    adhocracy.helpers.createSocialButtons('#socialshareprivacy', '${text}',
    '${base_url}', '.${h.site.domain()}');
});
</script>
%endif
</%def>


<%def name="head(title_def=None)">
  <meta charset="utf-8" />
    <%
    if title_def is None:
        local_title = ''
    else:
        local_title = capture(title_def)
    full_title = '%s%s%s' % (
        local_title + ' - ' if local_title else '',
        c.instance.label + ' - ' if c.instance else '',
        h.site.name())
    %>
    <title>${full_title}</title>

    <meta http-equiv="X-XRDS-Location"
          content="${h.base_url('/openid/xrds', absolute=True)}" />

    %for key, value in c.html_meta.items():
    <meta name="${key}" content="${value}" />
    %endfor

    <!-- template -->

    <%
    h.instance.need_stylesheet(c.instance)
    h.need.modernizr
    h.need.jquery
    h.need.jquerytools
    h.need.elastic
    h.need.adhocracy
    h.need_js_i18n('moment')
    %>

  <!--[if lte IE 7]>
  <link href="/stylesheets/patches/patch.css" rel="stylesheet" type="text/css" />
  ##FIXME: convert to a fanstatic call
  <![endif]-->

  <link rel="icon" href="${h.base_url('/favicon.ico', None)}" type="image/png" />

  <!-- HTML5 elements for IE -->
  <script>
    document.createElement('abbr');
    document.createElement('article');
    document.createElement('aside');
    document.createElement('audio');
    document.createElement('canvas');
    document.createElement('details');
    document.createElement('figcaption');
    document.createElement('figure');
    document.createElement('footer');
    document.createElement('header');
    document.createElement('hgroup');
    document.createElement('mark');
    document.createElement('menu');
    document.createElement('meter');
    document.createElement('nav');
    document.createElement('output');
    document.createElement('progress');
    document.createElement('section');
    document.createElement('summary');
    document.createElement('time');
    document.createElement('video');
  </script>

    <!-- /template -->

    %if c.instance and c.instance.css:
        <link  rel="stylesheet" type="text/css"
            href="${h.base_url('/instance/%s/style' % c.instance.key)}"/>
    %endif

    %for link in c.html_head_links:
    <link rel="${link['rel']}" type="${link['type']}"
          title="${link['title']}" href="${link['href']}" />
    %endfor

    %if c.user and c.user.no_help:
    <style type="text/css">
        .help {display: none;}
    </style>
    %endif

    ${tiles.badge.badge_styles(c.instance)}
</%def>


<%def name="tutorial()">

%if h.tutorial.show(c.tutorial, c.user):

<% h.need.joyride %>

${caller.body()}

<script type="text/javascript">
    adhocracy.helpers.initializeTutorial("${c.tutorial}");
</script>

%endif

</%def>

<%def name="feedback()">
    <div id="feedback">
      <div id="feedback_form">
        <form name="create_feedback" method="POST" action="${h.feedback.get_proposal_url()}">
          ${h.field_token()|n}
          <fieldset>
            <legend>${_(u'Send us your feedback')}</legend>
            %if h.feedback.get_categories():
                <label>${_(u'Category')}</label>
                <select name="category">
                %for category in h.feedback.get_categories():
                <option value="${category.id}">${category.title}</option>
                %endfor
                </select>
            %endif
            <label>${_(u'Title')}</label>
            <input type="text" placeholder="${_(u'One line summary')}" name="label" />
            <label>${_(u'Description')}</label>
            <textarea rows="8" placeholder="${_('Please enter your feedback in here and help us to improve our website')}" name="text"></textarea>
            <button type="submit" class="button">${_(u'Submit')}</button>
          </fieldset>
          <a href="${h.feedback.get_proposal_url()}">${_(u'List existing feedback')}</a>
        </form>
      </div>
      <a href="#" id="feedback_button">${_(u'Feedback')}</a>
    </div>
</%def>

<%def name="category_select(id, toplevel_question, categories, selected=None)">
    <% h.need.select_hierarchy %>
    <fieldset>
      <legend>${_('Proposal Category')}</legend>
      %if selected:
      <% (cat_id, key) = selected %>
      <input type="hidden" name="category" value="${cat_id}" />
      <select disabled="disabled">
        <option value="${cat_id}">${key}</option>
      </select>
      %else:
      %if toplevel_question is not None:
      <div class="select_header">${toplevel_question}</div>
      %endif
      <div class="input_wrapper">
        <select class="drilldown" id="${id}" name="category">
          <option value="">${_("No Category")}</option>
          %for (cat_id, key, child_desc) in categories:
          <option value="${cat_id}" data-header="${child_desc|n}">${key}</option>
          %endfor
        </select>
      </div>
      <script type="text/javascript">
        $('#${id}').selectHierarchy({placeholder: '${_("Others")}'});
      </script>
      %endif
    </fieldset>
</%def>

<%def name="proposal_sort_order(name, sorting_orders, include_empty=True, default=None)">
<label>${_(u'Default proposal sort order')}</label>
<select name="${name}">
    %if include_empty:
    <option value=""></option>
    %endif
    %for group in sorting_orders.groups:
      <optgroup label="${group}">
      %for sorting_order in sorting_orders.by_group[group]:
        <option value="${sorting_order.value}"${' selected="selected"' if default == sorting_order.value else ''}>${sorting_order.label}</option>
      %endfor
      </optgroup>
    %endfor
</select>

</%def>

## Makes sure the rebindCameFrom javascript function is only called if the patched target wouldn't also lead to a 403.
## If the rebindCameFrom function isn't called, we usually (in these cases) redirect to the page we came from.
<%def name="add_patch_camefrom_class()">${u'' if c.instance and c.instance.requires_valid_email() else u'patch_camefrom'}</%def>


<%def name="attention_getter()">
<% show_attention_getter = (
    not h.config.get_bool(u'adhocracy.readonly')
    and c.instance is not None
    and (c.user is None
        or can.instance.join(c.instance)
        or (c.instance.requires_valid_email()
            and c.user
            and not c.user.is_email_activated()
            and not c.hide_activate_attention_getter)
        or (h.config.get('adhocracy.propose_optional_attributes')
            and c.user.optional_attributes is None))) %>

%if show_attention_getter:
<div id="flash_message">
    <div class="page_wrapper">
        <div class="message">
            %if c.user is None:
            <div class="register">
                %if h.allow_user_registration():
                <a href="${h.register_redirect_url()}"
                    ## rel="#overlay-url" FIXME: reactivate when ready.
                    class="button">${_('Register')}</a>
                ${_("or")}
                %endif
                <a href="${h.login_redirect_url()}"
                    ## rel="#overlay-url" FIXME: reactivate.
                    class="more_uppercase">${_('Login')}</a>
            </div>
            <p class="register_msg">
                %if h.allow_user_registration():
                    ${_('Get an account to participate in the discussion.')}
                %else:
                    ${_('Log in to participate in the discussion.')}
                %endif
            </p>
            %elif can.instance.join(c.instance):
            <div class="register">
                <a class="button" href="${h.entity_url(c.instance, member='join')}?${h.url_token()}">${_("join")}</a>
            </div>
            <p>
                ${_('Join this instance to start contributing.')}
            </p>
            %elif c.instance.require_valid_email and c.user and not c.user.is_email_activated():
            %if c.user.email is None:
            <div class="register">
                <a class="button" href="${h.entity_url(c.user, instance=c.instance, member='edit')}">${_("Edit profile")}</a>
            </div>
            <p>
                ${_('You need to set an email in your profile in order to contribute to this instance.')}
            </p>
            %else:
            <div class="register">
                <a class="button large" href="${h.base_url('/user/%s/resend?%s' % (c.user.user_name, h.url_token()))}" title="${_('Resend validation email to %s')%c.user.email}">${_('Send activation link')}</a>
                ${_("or")}
                <a class="more_uppercase" href="${h.entity_url(c.user, instance=c.instance, member='edit')}">${_("Edit profile")}</a>
            </div>
            <p>
            ${_('Please validate your email address in order to contribute to this instance.')}<br />
            ${_('Your registered email address is:')} <em>${c.user.email}</em>
            </p>
            %endif
            %else:  # h.config.get('adhocracy.propose_optional_attributes') and c.user.optional_attributes is None)):
            <div class="register">
                <a class="button" href="${h.entity_url(c.user, instance=c.instance, member='settings/optional')}">${_("Provide information")}</a>
            </div>
            <p>
                ${_(u'Please provide statistical information to help scientific evaluation!')}
            </p>
            %endif
        </div>
    </div>
</div>
%endif
</%def>

<%def name="hidden_badge_table(tables, badge_type, badge_label)">
    <% badge_id = '%s_badge_tables' % badge_type %>
    <div class="more only-js">
        <a href="#" class="showhide_button content"
           data-target="#${badge_id}"
           aria-controls="${badge_id}"
           data-toggle-class="less"
           data-target-speed="fast"
           data-toggle-text="${_(u'Hide %s') % badge_label}">
        ${_(u'Show %s') % badge_label}</a>
    </div>
    <div id="${badge_id}" style="display:none">
        ${tables}
    </div>
</%def>


<%def name="category_link(category)">
    %if category.instance is not None and category.instance.display_category_pages:
    <a href="${h.entity_url(category)}">${category}</a>
    %else:
    ${category}
    %endif
</%def>
