<%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}">
        <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):  # not yet implemented
        text = _("Message to Supporters")
    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)
    else:
        permission = can.message.create(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 -->

    <%
    instance_stylesheets = h.config.get('adhocracy.instance_stylesheets')
    if instance_stylesheets and c.instance is not None and c.instance.key in instance_stylesheets:
        h.need.load_dynamic('instance_stylesheet', c.instance.key)
    else:
        h.need.stylesheets
    h.need.modernizr
    h.need.jquery
    h.need.jquerytools
    h.need.elastic
    h.need.adhocracy
    %>

  <!--[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>
