## 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-2012
## reddit Inc. All Rights Reserved.
###############################################################################

<%!
  from r2.lib.utils import to36
  from r2.lib.media import thumbnail_url
  from r2.lib.template_helpers import static
  from r2.lib import promote
  from r2.lib.strings import strings
  from r2.models import Account
  from r2.lib import js
  import simplejson
%>
<%namespace file="utils.html" 
            import="error_field, checkbox, image_upload, reddit_selector" />
<%namespace name="utils" file="utils.html"/>

${unsafe(js.use('sponsored'))}
<script type="text/javascript">
  $(function() { update_bid("*[name=bid]"); }); 
</script>


## 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>
    <script type="text/javascript">
      ${initfuncname} = function() {
          attach_calendar("#${name}", "#${minDateSrc}", "#${maxDateSrc}",
                          ${caller.body()}, ${min_date_offset})
      };
    </script>
  </div>
</%def>


<div class="create-promotion">

<%
   title = _("create a promotion") if not thing.link else _("edit promotion")
 %>
<h1>${title}</h1>

%if thing.link:
  ${thing.listing}
%endif

<div class="create-promo">

%if thing.link:
<div class="pretty-form">
  <%utils:line_field title="${_('campaign dashboard')}" id="campaign-field" css_class="rounded">

   <div class="help">
      <div class="infotext rounded" id="campaign-help">
        <p>This dashboard allows you to easily place ads on reddit.
        You can target a specific community or simply run on the main
        page.
        </p></div>
      <div class="clear"></div>
   </div>
    <div id="campaign" style="${'display:none' if thing.link.campaigns else ''}"
         class="campaign infotext rounded" method="post" action="/api/add_campaign">


    <input type="hidden" name="link_id" value="${to36(thing.link._id)}"/>
    <%
       start_title = "Date when your sponsored link will start running.  We start new campaigns at midnight UTC+5"
       end_title = "Date when your sponsored link will end (at midnight UTC+5)"
       targeting_title = "name of the community that you are targeting. A blank entry here means that the ad is untargeted and will run site-wise "
       newcamp_title = "click to create a new campaign.  To edit an existing campaing in the table below, click the 'edit' button."
     %>
    <table class="preftable">
      <tr>
        <th>duration</th>
        <td class="prefright">
		  <% 
			mindate = thing.startdate
			if c.user_is_sponsor:
				mindate = thing.promote_date_today.strftime('%m/%d/%Y')
	      %>
          <input type="hidden" id="date-min" name="date-min" value="${mindate}" />
          <%self:datepicker name="startdate", value="${thing.startdate}"
                            minDateSrc="date-min" initfuncname="init_startdate">
          function(elem) {
            var other = $("#enddate");
            if(dateFromInput("#startdate") >= dateFromInput("#enddate")) {
               var newd = new Date();
               newd.setTime($(elem).datepicker('getDate').getTime() + 86400*1000);
               $("#enddate").val((newd.getMonth()+1) + "/" + 
                                 newd.getDate() + "/" + newd.getFullYear());
            }
            $("#datepicker-enddate").datepicker("destroy");
            update_bid(elem);
          }
          </%self:datepicker>
          -
          <%self:datepicker name="enddate", value="${thing.enddate}"
                            minDateSrc="startdate" initfuncname="init_enddate" min_date_offset="86400000">
            function(elem) { update_bid(elem); }
          </%self:datepicker>
          
          ${error_field("BAD_DATE", "startdate", "div")}
          ${error_field("BAD_FUTURE_DATE", "startdate", "div")}
          ${error_field("BAD_DATE", "enddate", "div")}
          ${error_field("BAD_FUTURE_DATE", "enddate", "div")}
          ${error_field("BAD_DATE_RANGE", "enddate", "div")}
       </td>
       </tr>
      <tr>
        <th>total bid</th>
        <td class="prefright">
          ${error_field("BAD_BID", "bid", "div")}
          $<input id="bid" name="bid" size="7" type="text" class="rounded styled-input"
                  style="width:auto"
                  onchange="update_bid(this)"
                  onkeyup="update_bid(this)"
                  title="Minimum is $${'%.2f' % g.min_promote_bid} per day, or $${'%.2f' % (g.min_promote_bid * 1.5)} per day targeted"
                  value="${'%.2f' % (g.min_promote_bid * 5)}"
                  />
          <span class="bid-info gray"></span>
        </td>
      </tr>
       <tr>
         <th>
           targeting
         </th>
         <td class="prefright">
           <input id="no_targeting" class="nomargin" 
                  type="radio"  value="none" name="targeting"
                  onclick="return targeting_off(this)"
                  checked="checked" /> 
           <label for="no_targeting">no targeting (displays site-wide)</label>
           <p id="no_targeting_minimum" class="minimum-spend">minimum $20 / day</p>
           <input id="targeting" class="nomargin" 
                  type="radio"  value="one" name="targeting"
                  onclick="return targeting_on(this)" /> 
           <label for="targeting">
             enable targeting (runs on a specific reddit)
           </label>
           <p id="targeted_minimum" class="minimum-spend">minimum $30 / day</p>
           <script type="text/javascript">
             $(function() 
                { 
                  var c =  $(".campaign input[name=targeting]:checked");
                  if (c.val() == 'one') {
                      targeting_on(c);
                  } else {
                      targeting_off(c);
                  }
                })
           </script>
         </td>
       </tr>
     </table>
     <script type="text/javascript">
       $(function() {
          init_startdate();
          init_enddate();
          $("#campaign").find("button[name=create]").show().end()
               .find("button[name=edit]").hide().end();
          update_bid("*[name=bid]");
       })
     </script>
     <div class="targeting" style="display:none">
       <ul>
         <li>By targeting, your ad will only appear in front of users who subscribe to the reddit that you specify.</li>
         <li>Your ad will also appear at the top of the hot listing for that reddit</li>
         <li>You can only target one reddit per campaign.  If you would like to submit to more than one reddit, add a new campaign (its easy, you just fill this form out again).</li>
       </ul>
       ${error_field("OVERSOLD", "sr", "div")}
       ${reddit_selector(thing.default_sr, thing.sr_searches, thing.subreddits)}
     </div>
     <div class="buttons">
       <input type="hidden" name="indx" value="" />
       <span class="status error"></span>
       <button name="cancel"
          onclick="return cancel_edit()" class="fancybutton">
         cancel
       </button>
       <button name="edit"
          onclick="return post_pseudo_form('.campaign', 'edit_campaign')" class="fancybutton">
         edit
       </button>
       <button name="create"
          onclick="return post_pseudo_form('.campaign', 'edit_campaign')" class="fancybutton">
         create
       </button>
     </div>
     <div class="clear"></div>
    </div>
   <div class="existing-campaigns infotext rounded">
      <table style="${'display:none' if not thing.link.campaigns else ''}">
        <tr>
          <th title="${start_title}">start</th>
          <th title="${end_title}">end</th>
          <th>duration</th>
          <th>bid</th>
          <th title="${targeting_title}">targeting</th>
          <th style="align:right">
            <button class="new-campaign fancybutton" 
                    title="${newcamp_title}"
                    onclick="return create_campaign(this)">+ add new</button>
          </th>
        </tr>
      </table>
      <script type="text/javascript">
        $(function() {
           %for campaign in sorted(thing.link.campaigns.values(), \
                                   key = lambda x: x.start_date):
            $.new_campaign(${unsafe(','.join(simplejson.dumps(x) for x in campaign))});
           %endfor
           $.set_up_campaigns();
          });
      </script>
      <p class="error" 
         style="${'display:none' if thing.link.campaigns else ''}">
        You don't have any campaigns for this link yet.  You should add one.
      </p>
   </div>
  </%utils:line_field>
</div>
%endif

<div class="pretty-form" id="promo-form">

  %if thing.link:
    <input type="hidden" name="link_id" value="${to36(thing.link._id)}"/>
  %endif
<%
   trusted = c.user_is_sponsor or c.user.trusted_sponsor
 %>
<%utils:line_field title="${_('title')}" id="title-field" css_class="rounded">
    <textarea name="title" rows="2" cols="1" 
           ${"disabled" if (promote.is_promoted(thing.link) and
                            not trusted)  else ""}
              wrap="hard" class="rounded">${thing.link.title if thing.link else ''}</textarea>
    ${error_field("NO_TEXT", "title", "div")}
    ${error_field("TOO_LONG", "title", "div")}
    <div class="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>

<%utils:line_field title="${_('url')}" id="url-field" css_class="rounded">
  <input name="kind" value="link" type="hidden"/>
  <input id="url" name="url" type="text" 
           ${"disabled" if (promote.is_promoted(thing.link) and
                            not trusted)  else ""}
            value="${('self' if thing.link.is_self else thing.link.url) if thing.link else ""}" class="rounded"/>
  ${error_field("NO_URL", "url", "div")}
  ${error_field("BAD_URL", "url", "div")}
  ${error_field("ALREADY_SUB", "url", "div")}
  <div class="infotext rounded">
      <p>Provide the URL of your ad.&#32;<em>No redirects please!</em></p>
  </div>
  %if c.user_is_sponsor:
  <label style="display:block; text-align:right" for="domain">Override display domain:</label>
  <input id="domain" name="domain" type="text" 
         %if getattr(link, "domain_override", False):
           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>

%if thing.link and (trusted or not promote.is_promoted(thing.link)):
  <%utils:line_field title="${_('look and feel')}"
                     description="images will be resized if larger than 70 x 70 pixels" css_class="rounded">
    <div class="delete-field">
      <%utils:image_upload post_target="/api/link_thumb" 
                           current_image="${thumb}"
                           label="${_('upload header image:')}">
       <input type="hidden" name="link_id" value="${thing.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('${thing.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>
    <%utils:line_field title="${_('options')}" id="commenting-field" css_class="rounded">
      <div class="delete-field">
          <% 
             clicks = views = 0
             disable_comments = False
             if thing.link:
                disable_comments = getattr(thing.link, "disable_comments",
                                           False)
                clicks = getattr(thing.link, "maximum_clicks", 0) or 0
                views  = getattr(thing.link, "maximum_views", 0) or 0
           %>
        ${checkbox("disable_comments",
                 _("disable comments"), disable_comments)} <br />
        %if c.user_is_sponsor:
          ${checkbox("set_maximum_clicks",
                   unsafe("maximum clicks:&#32; " +
                          "<input type='text' style='width:auto' " + 
                                  "onfocus='update_box(this)' " +
                                  "name='maximum_clicks' size='7' " +
                                  "value='%s' />" % clicks),
                   clicks)} <br />
          ${checkbox("set_maximum_views",
                   unsafe("maximum views:&#32;" +
                          "<input type='text' style='width:auto' " + 
                                  "onfocus='update_box(this)' " +
                                  "name='maximum_views' size='7' " +
                                  "value='%s' />" % views),
                   views)} <br />
        %endif
      </div>
      <div class="infotext rounded">
          <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>
    %if c.user_is_sponsor or c.user.trusted_sponsor:
    <%utils:line_field title="${_('media')}" id="commenting-field" css_class="rounded">
      <div class="delete-field">
        <label for="width">Dimensions:</label>&#32;
        <input name="media-width" type='text' size='5' maxsize='5' 
               id="width"
               style="width:auto"
                 %if thing.link.media_object:
                   value='${thing.link.media_object.get("width", 0)}'
                 %else:
                   placeholder="${_('width')}"
                 %endif
               />
        x <input name="media-height" type='text' size='5' maxsize='5'
                 style="width:auto"
                 %if thing.link.media_object:
                   value='${thing.link.media_object.get("height", 0)}'
                 %else:
                   placeholder="${_('height')}"
                 %endif
                 />
        <p>
          <label for="media-embed">Embed Code</label>
          <textarea id="media-embed" name="media-embed" rows="7" cols="1">
            %if thing.link.media_object:
              ${thing.link.media_object.get('content','')}
            %endif
          </textarea>
        </p>
          ${checkbox("media-override", "media override (adds an onclick to the link to generate a drop-down rather than a link out)", getattr(thing.link, "media_override", False) or False)}<br />
      </div>
    </%utils:line_field>
    %endif
%else:
     <div class="rules">
       By clicking "next" you agree to the&#32;<a href="http://www.reddit.com/help/selfservicepromotion">Self Serve Advertising Rules.</a>
   </div>
%endif


<div class="save-button">
  <%
      if thing.link:
          name = "edit"
          text = _("save options")
      else:
          name = "create"
          text = _("next")
  %>
  ${error_field("RATELIMIT", "ratelimit")}
  &#32;
  <span class="status error"></span>
  ${error_field("RATELIMIT", "ratelimit")}
  <button name="${name}" class="btn fancybutton" type="button"
          onclick="return post_pseudo_form('#promo-form', 'edit_promo')"
          >${text}</button>

</div>
</div>
</div>

%if thing.link and not c.user_is_sponsor:
  <div class="bidding-history" style="padding-top: 0px;">
    <%utils:line_field title="${_('promotion history')}" css_class="rounded">
    <% 
       import datetime 
       pc_max = max(thing.promo_counter.values() or [1])
       %>
      <p style="font-size:smaller; margin: 5px;">
        Here is a summary of the data presented on the&#32;<a href="/promoted/graph">graph page</a>.
        Remember: best to pick days with less competition. </p>
    <table class="bidding-history">
      <tr>
        <th>date</th>
        <th>CPM</th>
        <th>CPC</th>
        <th>count</th>
        <th></th>
      </tr>
      %for i in xrange(0, 28):
      <%
         is_today = (i == 14)
         the_future = (i >= 14)
         day = (thing.now + datetime.timedelta(i-14))
         CPC = CPM = imp_traffic = cli_traffic = "---"
         if thing.promo_traffic.has_key(day):
            imp_traffic, cli_traffic = thing.promo_traffic[day]
            if thing.market.has_key(i) and not the_future:
               CPM = "$%.2f" % (thing.market[i] * 1000./max(imp_traffic, 1))
               CPC = "$%.2f" % (thing.market[i] * 1./max(cli_traffic, 1))
       %>
      <tr>
        <th>
          ${unsafe("&raquo;" if is_today else '')}
          ${day.strftime("%m/%d/%Y")}</th>
        <td>${CPM}</td>
        <td>${CPC}</td>
        <td>${thing.promo_counter.get(i, 0)}</td>
        <td><div class="graph" style="width:${int(50. * thing.promo_counter.get(i, 0) / pc_max)}px"
      </tr>
      %endfor
    </table>
</%utils:line_field>
  </div>
%endif

%if thing.link and c.user_is_sponsor:
  <div class="spacer bidding-history">
   %if thing.bids:
    <%utils:line_field title="${_('bidding history')}" css_class="rounded">
    <% 
       from r2.models import Account, bidding
       accounts = Account._byID(set(x.account_id for x in thing.bids), True)
     %>
      <table class="bid-table">
        <tr>
          <th>date</th>
          <th>user</th>
          <th>transaction id</th>
          <th>campaign id</th>
          <th>pay id</th>
          <th>amount</th>
          <th>status</th>
        </tr>
        %for bid in thing.bids:
         <%
            status = bidding.Bid.STATUS.name[bid.status].lower()
          %>
        <tr class="bid-${status}">
          <td>${bid.date}</td>
          <td>${accounts[bid.account_id].name}</td>
          <td>${bid.transaction}</td>
          <td>${bid.campaign}</td>
          <td>${bid.pay_id}</td>
          <td>$${"%.2f" % bid.bid}</td>
          <td class="bid-status">${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 getattr(thing.link, "promotion_log", []):
          <p>${line}</p>
        %endfor
      </div>
     </%utils:line_field>
   </form>

  </div>
%endif
</div>
