## The contents of this file are subject to the Common Public Attribution
## License Version 1.0. (the "License"); you may not use this file except in
## compliance with the License. You may obtain a copy of the License at
## http://code.reddit.com/LICENSE. The License is based on the Mozilla Public
## License Version 1.1, but Sections 14 and 15 have been added to cover use of
## software over a computer network and provide for limited attribution for the
## Original Developer. In addition, Exhibit A has been modified to be
## consistent with Exhibit B.
##
## Software distributed under the License is distributed on an "AS IS" basis,
## WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
## the specific language governing rights and limitations under the License.
##
## The Original Code is reddit.
##
## The Original Developer is the Initial Developer.  The Initial Developer of
## the Original Code is reddit Inc.
##
## All portions of the code written by reddit are Copyright (c) 2006-2015
## reddit Inc. All Rights Reserved.
###############################################################################

<%!
  from r2.config import feature
  from r2.lib.media import thumbnail_url
  from r2.lib.pages import UserText
  import simplejson
  from babel.numbers import format_currency
%>

<%namespace file="utils.html" 
            import="error_field, checkbox, image_upload" />
<%namespace name="utils" file="utils.html"/>

<%def name="javascript_setup()">
<script type="text/javascript">
  r.sponsored.init();
  r.sponsored.set_form_render_fnc(r.sponsored.fill_campaign_editor);
  r.sponsored.setup(${unsafe(simplejson.dumps(thing.inventory))},
                    ${unsafe(simplejson.dumps(thing.price_dict))},
                    ${simplejson.dumps(not thing.campaigns)},
                    ${simplejson.dumps(c.user_is_sponsor)});
  r.sponsored.setup_geotargeting(${unsafe(simplejson.dumps(thing.regions))},
                                 ${unsafe(simplejson.dumps(thing.metros))});
  r.sponsored.setup_collections(${unsafe(simplejson.dumps(thing.collections))});
</script>
</%def>

## Create a datepicker for a form. min/maxDateSrc are the id of the
## element containing the min/max date - the '#' is added automatically
## here (as a workaround for babel message extraction not handling it
## properly if passed in when the function is called
<%def name="datepicker(name, value, minDateSrc = '', maxDateSrc ='', initfuncname = '', min_date_offset=0)">
  <div class="date-input">
    <input name="${name}"
           value="${value}" id="${name}" class="rounded styled-input" readonly="readonly" size="10" />
    <div id="datepicker-${name}" class="datepicker"></div>
    ${error_field("BAD_DATE", name, "div")}
    ${error_field("DATE_TOO_EARLY", name, "div")}
    ${error_field("DATE_TOO_LATE", name, "div")}
    <script type="text/javascript">
      ${initfuncname} = function() {
          attach_calendar("#${name}", "#${minDateSrc}", "#${maxDateSrc}",
                          ${caller.body()}, ${min_date_offset})
      };
    </script>
  </div>
</%def>

<%def name="title_field(link, editable=False)">
  <%utils:line_field title="${_('title')}" id="title-field" css_class="rounded title-field">
    <textarea name="title" rows="2" cols="1" 
              ${"disabled" if not editable else ""}
              wrap="hard" class="rounded">${link.title if link else ''}</textarea>
    ${error_field("NO_TEXT", "title", "div")}
    ${error_field("TOO_LONG", "title", "div")}
    <div class="help infotext rounded">
      <p>${_("A good title is important to the success of your campaign. reddit users are an intelligent, thoughtful group, and reward those who engage them.")}</p>
    </div>
  </%utils:line_field>
</%def>

<%def name="post_type_field(link_selected=True)">
  <%utils:line_field title="${_('post type')}" id="kind-selector" css_class="rounded post-type-field">
    <div class="radio-group">
      <label class="form-group">
        <input id="url_link" class="nomargin" 
               type="radio" value="link" name="kind"
               onclick="$('#text-field').hide(); $('#url-field').show()"
               ${"checked='checked'" if link_selected else ""}>
        <div class="label-group">
          <span class="label">${_("link")}</span>
          <small class="label">${_("clicks through to your URL")}</small>
        </div>
      </label>
      <label class="form-group">
        <input id="self_link" class="nomargin" 
               type="radio" value="self" name="kind"
               onclick="$('#url-field').hide(); $('#text-field').show()"
               ${"" if link_selected else "checked='checked'"}>
        <div class="label-group">
          <span class="label">${_("text")}</span>
          <small class="label">${_("clicks through to text you customize")}</small>  
        </div>
      </label>
    </div>
  </%utils:line_field>
</%def>

<%def name="url_field(link, editable=False, enable_override=False)">
  <%utils:line_field title="${_('url')}" id="url-field" css_class="rounded url-field">
    <input id="url" name="url" type="text" 
           ${"disabled" if not editable else ""}
           value="${('self' if link.is_self else link.url) if link else ""}"
           class="rounded"/>
    ${error_field("NO_URL", "url", "div")}
    ${error_field("BAD_URL", "url", "div")}
    ${error_field("DOMAIN_BANNED", "url", "div")}
    <div class="help infotext rounded">
      <p>${_("Provide the URL of your ad. No redirects please!")}</p>
    </div>

    %if enable_override:
      <label style="display:block; text-align:right" for="domain">${_("Override display domain:")}</label>
      <input id="domain" name="domain" type="text" 
             %if link and link.domain_override:
               value="${link.domain_override}" class="rounded"
             %else:
               class="gray rounded" value="optional"
             %endif
      />

      <div class="infotext rounded">
        <p>${_("Choose a different domain name to display on the site (the small grey text next to a link)")}</p>
      </div>
    %endif
  </%utils:line_field>
</%def>

<%def name="text_field(text='', visible=True)">
  <%utils:line_field title="${_('text')}" id="text-field" css_class="rounded text-field"
                     style="${('' if visible else 'display:none')}">
    ${UserText(None, text=text, textarea_class='rounded', have_form=False, creating=True)}
  </%utils:line_field>
</%def>

<%def name="image_field(link)">
  <% current_image = getattr(link, 'thumbnail_url', '') %>
  <%utils:line_field title="${_('thumbnail')}" 
                     css_class="rounded image-field ${'has-image' if current_image else ''}">
    <div class="infotext">
      ${_('images will be resized if larger than 140x140 pixels (displayed at 70x70)')}
    </div>
    <div class="delete-field">
      <%utils:image_upload post_target="/api/link_thumb" 
                           current_image="${current_image}"
                           label="${_('upload header image:')}"
                           ask_type="True">
        <input type="hidden" name="link_name" value="${link._fullname}" />

        ## overwrite the completed image function
        <script type="text/javascript">
          completedUploadImage = (function(cu) {
            return function(status, img_src, name, errors) {
              cu(status, "", "", errors);
              $.things('${link._fullname}').find(".thumbnail img")
                .attr("src", img_src + "?v=" + Math.random());
            }
          })(completedUploadImage);
        </script>

      </%utils:image_upload>
      <div class="clearleft"></div>
    </div>
  </%utils:line_field>
</%def>

<%def name="commenting_field(link)">
  <%utils:line_field title="${_('options')}" id="commenting-field" css_class="rounded commenting-field">
    <div class="checkbox-group">
      <div class="form-group">
        ${checkbox("disable_comments", _("disable comments"), link.disable_comments)}
      </div>
      
      <div class="form-group">
        ${checkbox("sendreplies", _("send comments on my ad to my inbox"), link.sendreplies)}
      </div>
    </div>

    <div class="help infotext">
      <p>${_("Comments are a great way to get feedback from customers, and the reddit community is known for being vocal in comment threads.")}</p>
    </div>
  </%utils:line_field>
</%def>

<%def name="media_field(link)">
  <%utils:line_field title="${_('media')}" id="media-field" css_class="rounded media-field">
    <div class="delete-field">
      <div class="radio-group">
        <%
          scraper_checked = link.media_url or not link.gifts_embed_url
        %>
        <label class="form-group checkbox">
          <input type="radio" id="scrape" value="scrape" name="media_url_type"
                 ${"checked='checked'" if scraper_checked else ''}>
          <span class="label">scraper</span>
        </label>
        <label class="form-group checkbox">
          <input type="radio" id="redditgifts" value="redditgifts" name="media_url_type"
                 ${"checked='checked'" if not scraper_checked else ''}>
          <span class="label">redditgifts</span>
        </label>
      </div>
      <p id="scraper_input" ${"" if scraper_checked else "style='display:none'"}>
        <label for="media_url">source URL to scrape</label>
        <input id="media_url" name="media_url" type="text" class="rounded"
               value="${link.media_url or ""}"
               ${"" if scraper_checked else "disabled"}>
        ${error_field("BAD_URL", "media_url", "div")}
        ${error_field("SCRAPER_ERROR", "media_url", "div")}
      </p>
      <p id="rg_input" ${"style='display:none'" if scraper_checked else ""}>
        <label for="gifts_embed_url">redditgifts embed URL</label>
        <input id="gifts_embed_url" name="gifts_embed_url" type="text" class="rounded"
               value="${link.gifts_embed_url or ''}"
               ${"disabled" if scraper_checked else ""}>
        ${error_field("BAD_URL", "gifts_embed_url", "div")}
      </p>
      ${checkbox("media_autoplay",
                 _("autoplay"),
                 link.media_autoplay)}
      <br>
      ${checkbox("media-override",
                 _("media override (adds an onclick to the link to generate a drop-down rather than a link out)"),
                 getattr(link, "media_override", False) or False)}
      <br>
    </div>
  </%utils:line_field>
</%def>

<%def name="managed_field(link)">
  <%utils:line_field title="" id="managed-field" css_class="rounded managed-field">
    <div class="checkbox-group">
      <div class="form-group">
        ${checkbox("is_managed", _("managed promotion"), link.managed_promo if link else False)}
      </div>
      <div class="infotext rounded">
        <p>${_("Managed promotions don't appear in the selfserve approval queues.")}</p>
      </div>
    </div>
  </%utils:line_field>
</%def>

<%def name="timing_field()">
  <%utils:line_field title="${_('timing')}" css_class="rounded timing-field">
    %if thing.min_start:
      <input type="hidden" id="date-min" value="${thing.min_start}">
    %endif
    %if thing.max_start:
      <input type="hidden" id="date-start-max" value="${thing.max_start}">
    %endif
    %if thing.max_end:
      <input type="hidden" id="date-end-max" value="${thing.max_end}">
    %endif

    <div class="group">
      <div class="form-group">
        <span class="label">${_("start")}</span>
        <div class="input-group">
          <%self:datepicker name="startdate", value="${thing.default_start}"
                            minDateSrc="date-min" maxDateSrc="date-start-max"
                            initfuncname="init_startdate">
            function(elem) {
              check_enddate(elem, $("#enddate"));
              r.sponsored.on_date_change();
            }
          </%self:datepicker>
        </div>
      </div>
      <div class="form-group">
        <span class="label">${_("end")}</span>
        <div class="input-group">
        <%self:datepicker name="enddate", value="${thing.default_end}"
                            minDateSrc="startdate" maxDateSrc="date-end-max"
                            initfuncname="init_enddate" min_date_offset="86400000">
            function(elem) { r.sponsored.on_date_change(); }
          </%self:datepicker>
        </div>
      </div>
      <div class="form-group">
        <span class="label">${_("duration")}</span>
        <div class="display-text duration"></div>
      </div>
    </div>
    <div>
      ${error_field("BAD_DATE_RANGE", "enddate", "div")}
    </div>
  </%utils:line_field>
</%def>

<%def name="priority_field()">
  <%def name="priority_field_content()">
    <div class="radio-group">
      %for value, text, description, default, override, cpm in thing.priorities:
        <label class="form-group checkbox">
          <input id="${value}" class="nomargin" 
                 type="radio"  value="${value}" name="priority"
                 onclick="r.sponsored.priority_changed()"
                 ${"checked='checked'" if default else ""}
                 data-default="${simplejson.dumps(default)}"
                 data-override="${simplejson.dumps(override)}"
                 data-cpm="${simplejson.dumps(cpm)}">
          %if description:
            <span class="label">${"%s (%s)" % (text, description)}</span>
          %else:
            <span class="label">${text}</span>
          %endif
        </label>
      %endfor
    </div>
  </%def>

  %if c.user_is_sponsor:
    <%utils:line_field title="${_('priority')}" css_class="rounded priority-field">
      ${priority_field_content()}
    </%utils:line_field>
  %else:
    <div style="display:none">
      ${priority_field_content()}
    </div>
  %endif
</%def>

<%def name="budget_field()">
  <%utils:line_field title="${_('budget')}" css_class="rounded budget-field">
    <div class="group">
      <div class="form-group">
        <span class="label">${_("total budget")}</span>
        <div class="input-group">
          $<input id="bid" name="bid" size="7" type="text"
                  class="rounded styled-input"
                  style="width:auto"
                  onchange="r.sponsored.on_bid_change()"
                  onkeyup="r.sponsored.on_bid_change()"
                  value="${'%.2f' % g.default_promote_bid}"
                  data-default_bid="${g.default_promote_bid}"
                  data-min_bid="${thing.min_bid}"
                  data-real_min_bid="${g.min_promote_bid}"
                  data-max_bid="${thing.max_bid}"/>
          <div class="minimum-spend">
            ${_('%(minimum)s minimum') % dict(minimum=format_currency(thing.min_bid, 'USD', locale=c.locale))}
          </div>
        </div>
      </div>
      <div class="form-group">
        <span class="label">${_("impressions")}</span>
        <input id="impressions" name="impressions" size="10" type="text"
               class="rounded styled-input"
               onchange="r.sponsored.on_impression_change()">
      </div>
      <div class="form-group">
        <span class="label">${_("price")}</span>
        <div class="display-text price-info"></div>
      </div>
    </div>
    <div>
      ${error_field("BAD_BID", "bid", "div")}
      ${error_field("BID_LIVE", "bid", "div")}
      <div class="budget-change-warning error">
        ${_('if you modify the budget of this paid campaign you will need to reauthorize payment by clicking the "pay" button')}
      </div>
      <div class="available-info"></div>
      ${error_field("OVERSOLD_DETAIL", "bid", "div")}
    </div>
  </%utils:line_field>
</%def>

<%def name="targeting_field(default_checked='collection')">
  <%utils:line_field title="${_('targeting')}" css_class="rounded targeting-field">
    <div class="radio-group group">
      <span class="label">target</span>
      <label class="form-group">
        <input id="collection_targeting" class="nomargin"
               type="radio" value="collection" name="targeting"
               onclick="r.sponsored.collection_targeting()"
               %if default_checked == 'collection':
                 checked="checked"
               %endif
               >
        <div class="label-group">

          <span class="label">${_("interests")}</span>
          <small class="label">${_("targets a collection of similar subreddits")}</small>
        </div>
      </label>
      <label class="form-group">
        <input id="subreddit_targeting" class="nomargin"
               type="radio" value="one" name="targeting"
               onclick="r.sponsored.subreddit_targeting()"
               %if default_checked == 'one':
                 checked="checked"
               %endif
               >
        <div class="label-group">
          <span class="label">${_("subreddits")}</span>
          <small class="label">${_("targets a subreddit and its subscribers")}</small>
        </div>
      </label>
    </div>
    <div class="target-group group">
      <div class="collection-targeting"
           %if default_checked != 'collection':
             style="display:none"
           %endif
           >
        <span class="label">${_("interest audience group")}</span>
        <div class="collection-selector uninitialized">
          <div class="widget-container">
            <div class="form-group-list">
            </div>
          </div>
        </div>
        <div class="collection-subreddit-list">
          <div class="label frontpage-label">
            ${_("subreddits included on the frontpage are based on users\' subscriptions")}
          </div>
          <div class="label collection-label" style="display:none;">
            ${_('includes these subreddits')}
            &#32;<a href="/wiki/advertising/interestaudiencegroups">${_('and more!')}</a>
          </div>
          <ul></ul>
          ${error_field("COLLECTION_NOEXIST", "collection", "div")}
        </div>
      </div>
      <div class="subreddit-targeting"
           %if default_checked != 'one':
             style="display:none"
           %endif
           >
        <span class="label">subreddit</span>
        ${error_field("OVERSOLD", "sr", "div")}
        ${thing.subreddit_selector}
      </div>
    </div>
    <div class="select-group geotargeting-group">
      <span class="label">location</span>
      <div class="geotargeting-disabled" style="display:none">
        ${_("location targeting is only available when targeting the frontpage")}
      </div>
      <div class="geotargeting-selects">
        <select class="geotarget-select" id="country" name="country"
                title=${_("country")}
                onchange="r.sponsored.country_changed()">
          %for code, name, selected in thing.countries:
          <option ${"selected='selected'" if selected else ""} value=${code}>
            ${name}
          </option>
          %endfor
        </select>
        <select class="geotarget-select" id="region" name="region"
                title=${_("region")} style="display:none"
                onchange="r.sponsored.region_changed()"></select>
        <select class="geotarget-select" id="metro" name="metro"
                title=${_("metro")} style="display:none"
                onchange="r.sponsored.metro_changed()"></select>
        ${error_field("INVALID_LOCATION", ("country", "region", "metro"), "div")}
      </div>
    </div>
  </%utils:line_field>
</%def>

<%def name="subreddit_targeting_field(subreddit_selector)">
  <%utils:line_field title="${_('subreddit targeting')}" css_class="rounded subreddit-targeting-field">
    <div class="target-group group">
      <div class="subreddit-targeting">
        <span class="label">subreddit</span>
        ${error_field("OVERSOLD", "sr", "div")}
        ${subreddit_selector}
      </div>
    </div>
  </%utils:line_field>
</%def>

<%def name="reporting_field(link_text='', owner='')">
  <%utils:line_field title="${_('report')}" css_class="rounded reporting-field">
    <label class="form-group">
      <div class="label">${_('link ids')}</div>
      <textarea name="link_text">${link_text}</textarea>
      ${error_field("BAD_LINKS", "bad_links", "div")}
    </label>
    <label class="form-group">
      <div class="label">${_('owner')}</div>
      <input type="text" name="owner" value="${owner}" />
    </label>
  </%utils:line_field>
</%def>

<%def name="admin_panel()">
  %if c.user_is_sponsor:
    <div class="spacer bidding-history">
      %if thing.bids:
        <%utils:line_field title="${_('bidding history')}" css_class="rounded">
          <table class="bid-table">
            <tr>
              <th>date</th>
              <th>user</th>
              <th>transaction id</th>
              <th>campaign id</th>
              <th>pay id</th>
              <th>bid</th>
              <th>charge</th>
              <th>status</th>
            </tr>
            %for bid in thing.bids:
              <tr class="bid-${bid.status}">
                <td>${bid.date}</td>
                <td>${bid.bidder}</td>
                <td>${bid.transaction}</td>
                <td>${bid.campaign}</td>
                <td>${bid.pay_id}</td>
                <td>${bid.amount_str}</td>
                <td>${bid.charge_str}</td>
                <td class="bid-status">${bid.status}</td>
              </tr>
            %endfor
          </table>
        </%utils:line_field>
      %endif

      <form id="promotion-history" method="post" action="/post/promote_note"
            onsubmit="post_form(this, 'promote_note'); $('#promote_note').val('');return false;">
        <%utils:line_field title="${_('promotion history')}" css_class="rounded">
          <div style="font-size:smaller; margin-bottom: 10px;">
            For correspondence, the email address of this author is&#32;
            <a href="mailto:${thing.author.email}">${thing.author.email}</a>.
          </div>

          <div style="font-size:smaller; margin-bottom: 10px;">
            To check with&#32;<a href="https://account.authorize.net/">authorize.net</a>,
            use CustomerID&#32;<b>${thing.author._fullname}</b>&#32; when searching by batch.
          </div>

          <input type="hidden" name="link" value="${thing.link._fullname}"/>
          <label for="promote_note">add note:</label>
          <input id="promote_note" name="note" value="" type="text" size="40" />
          <button type="submit">save</button>
          <div class="notes">
            %for line in thing.promotion_log:
              <p>${line}</p>
            %endfor
          </div>
        </%utils:line_field>
      </form>
    </div>
  %endif
</%def>
