## 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.filters import keep_space
  from r2.lib.template_helpers import add_sr, static
  from r2.lib.media import s3_direct_url
  import os

%>
<%namespace file="utils.html" import="error_field, image_upload"/>
<%namespace file="printablebuttons.html" import="ynbutton, toggle_button"/>

<div class="stylesheet-customize-container">
  <form
     onsubmit="return post_form(this, 'subreddit_stylesheet')"
     name="subreddit_stylesheet" id="subreddit_stylesheet"
     class="pretty-form sr-form"
     action="/post/subreddit_stylesheet" method="post" >
    
  <input type="hidden" name="r"  value="${thing.site.name}" />
  <input type="hidden" name="op"  value="" />

  <h2>${_("stylesheet")}</h2>
  <div class="sheets">
    <div style="width: 100%" class="col">
      <div>
        <textarea
           rows="20"
           cols="20"
           id="stylesheet_contents"
           name="stylesheet_contents"
           >
          ${keep_space(thing.stylesheet_contents) or ''}
        </textarea>
      </div>
    </div>
    <div style="display:none" class="col">
      <div>
        <textarea
           rows="20"
           cols="20"
           id="default_stylesheet"
           name="default_stylesheet"
           readonly="readonly"
           >
        </textarea>
      </div>
    </div>
    <div class="clearleft"></div>
    <div class="buttons"><span class="btn right">
       ${toggle_button("default-css", 
                       _("show the default stylesheet"), 
                       _("hide the default stylesheet"),
                       "showDefaultStylesheet",
                       "hideDefaultStylesheet")}
      </span>
      <button class="btn" name="save" type="submit" 
             onclick="this.form.op.value='save'; return true;">
        ${_('save')}
      </button>
      <button class="btn" name="preview" type="submit" 
             onclick="this.form.op.value='preview'; return true;">
        ${_('preview')}
      </button>
      <span class="status error"></span>
    </div>
  </div>
  <div class="errors" style="display:none">
    <h2>${_("errors")}</h2>
    <ul><li></li>
      <!-- populated from AJAX requests to /api/subreddit_stylesheet -->
    </ul>
  </div>
  
  </form>

  <div id="preview-table" style="display:none">
    <h2><a name="preview">${_("preview")}</a></h2>
    <table>
      <tr>
        <th>${_("normal link")}</th>
        <td id="preview_link_normal"></td>
      </tr>
      <tr>
        <th>${_("compressed link")}</th>
        <td id="preview_link_compressed"></td>
      </tr>
      <tr>
        <th>${_("link with thumbnail")}</th>
        <td id="preview_link_media"></td>
      </tr>
      <tr>
        <th>${_("comment")}</th>
        <td id="preview_comment"></td>
      </tr>
    </table>
  </div>

  <div id="images">
    <h2><a name="images">${_("images")}</a></h2>

  <%call expr="image_upload('/api/upload_sr_img', '', 
                              onchange='return file_changed(this)',
                              label = _('image file'), ask_type=True)">
    
    <br/>
    <label for="img-name">${_("new image name:")}</label>
    <input id="img-name" name="name" value="" type="text"/>
    ${error_field("BAD_CSS_NAME", "name")}
    <br/>
    <span class="little gray">
      ${_("(image names should consist of alphanumeric characters and '-' only)")}
    </span>
  </%call>
<p class="error">
  ${_("Note: any changes to images here will be reflected immediately on reload and cannot be undone.")}
</p>
    <script type="text/javascript">
      /* <![CDATA[ */
        function create_new_image(name) {
              var list = $(".image-list:first");
              var new_li = list.children("li:first")
                  .clone(true).attr("id", "")
                  .find(".img-name").html(name).end()
                  .find(".img-url").html("url(%%" + name + "%%)").end()
                  .find("form input[name=img_name]").val(name).end()
                  .find("img").attr("id", "img-preview-" + name).end();
              
              list.append(new_li);
              img = new_li.find("img");
              
              $("#old-names").append("<option>" + name + "</option>");
              return img;           
        }

        function on_image_success(img) {
           $(img).parents("li:first").fadeIn();
           $(img).parent("a").attr("href", $(img).attr("src"));
        }


        function too_big() {
            $(".IMAGE_ERROR").innerHTML = "image too big: there is a 500k cap";
            $(".img-status").innerHTML = "";
        }
        function showDefaultStylesheet(btn) {
            var default_stylesheet = $('#default_stylesheet');
            /* make sure to load the default stylesheet contents from the local domain so it doesn't get caught by cross-domain rules. */
            var stylesheet_url = '${add_sr(os.path.join(c.site.static_path, g.static_names.get("reddit.css", "reddit.css")), nocname=True, sr_path=False)}';

            if (!default_stylesheet.data('loaded')) {
              default_stylesheet.text('loading...');
              $.get(stylesheet_url, function(css) {
                default_stylesheet.val(css);
                default_stylesheet.data('loaded', true);
              })
            }

            $("#stylesheet_contents").parents(".col")
                .animate( { width: "50%" }, function() { 
                        default_stylesheet.parents(".col")
                            .css("width", "50%")
                            .fadeIn();
                    });
        }
        function hideDefaultStylesheet(btn) {
            $("#default_stylesheet").parents(".col")
                .fadeOut(function() {
                        $(this).css("width", "50%");
                        $("#stylesheet_contents").parents(".col")
                            .animate( { width: "100%" });
                    });
        }

        function paste_url(source) {
            var txt = $(source).siblings("pre:first").html();
            $("#stylesheet_contents").insertAtCursor(txt);
            return false; 
        }
        function delete_img(button) {
            $(button).parents("li:first").fadeOut(function() {
                $(this).remove();
            })
        }
        function file_changed(file_input) {
            $("#submit-header-img").show();
            $(".img-status").html("");
            if(file_input.value) {
                if(! $('#img-name').val()) {
                   var f = file_input.value
                        .replace(/.*[\/\\]/, "").split('.')[0]
                        .replace(/[ _]/g, "-");
                    $('#img-name').val(f);
                }
            }
        }
        function check_name(form) {
           var name = form.name.value;
           var r = new RegExp(/[^a-zA-Z0-9\-]/);
           if (name == "" || name.match(r)) { 
              $(".img-status").html("").hide();
              $(".BAD_CSS_NAME").show().html("${_('bad image name')}");
              return false; 
           }
           else if(form.srfile.value) {
              $(".BAD_CSS_NAME").html("").hide();
              $(".IMAGE_ERROR").html("").hide();
              return true;
           } else {
              $(".img-status").html("").hide();
              $(".IMAGE_ERROR").show().html("${_('please select an image')}");
              return false; 
           }
        }
    /* ]]> */
    </script>
    <ul id="image-preview-list" class="image-list">
      <%def name="make_li(name='', img=None, prototype=False)">
        <li ${"style='display:none'" if img is None else ""}>
          <% 
             if img is not None:
                 if isinstance(img, int):
                    bucket = g.s3_old_thumb_bucket
                    baseurl = "http://%s" % (bucket)
                    if g.s3_media_direct:
                        baseurl = "http://%s/%s" % (s3_direct_url, bucket)
                        
                    img = "%s/%s_%d.png" % \
                    (baseurl, c.site._fullname, img)
             else:
                 img = static('kill.png')
             %>
          <a href="${img}" class="preview">
            <img id="img-preview-${name}" src="${img}" 
                 alt="Image ${name}" title="click to preview"/>
          </a>
          <div class="description">
            <b class="img-name">
              ${name}
            </b>
            <br/>
            <span>link:</span>
            <pre class="img-url">url(%%${name}%%)</pre>
            <br/>
            <a href="javascript:void(0)" onclick="return paste_url(this)">
              ${_("paste into stylesheet")}
            </a>
            <br/>
            ${ynbutton(_("delete this image"), _("deleted"),
                       "delete_sr_img", callback = "delete_img",
                        hidden_data = dict(img_name = name))}
          </div>
        </li>
        </%def>
      ${make_li(prototype=True)}
      %for name, img_num in c.site.get_images():
         ${make_li(name=name, img=img_num)}
      %endfor
    </ul>

    <iframe src="about:blank" width="600" height="200" style="display: none;"
            name="upload-iframe" id="upload-iframe"></iframe>
    
  </div>

</div>

