














function FTPAccessUI(top, options) {
  this.topElement = top;
  this.options = options;
}


FTPAccessUI.prototype = {
  



  withTitle: function(t, a) {
    if(!this.options.noTitle) {
      a=[_mkel("h2", [t]), _mkel("div", {className: "bbox"}, a)];
    }
    return a;
  },
  





  infoPopup: function(extra_options) {
    var options = this.options;
    if(extra_options)
      for(var k in extra_options) options[k] = extra_options[k];

    return hide_block_popup("Why do I have to do this?", [
      _mkel("p", ["FTP is locked on all accounts as standard. This is to help prevent your site being attacked. You can unlock FTP for a set period of time; we recommend that you do this only for short periods. We would advise that you prepare any changes to your website and then, when you are ready to upload it, unlock FTP for one hour. If you need longer, then please select the relevant option below. However, we would advise you to only unlock FTP for short periods."]),
      _mkel("p", ["We require this because of the many PC viruses circulating that steal passwords stored within FTP clients. We recommend that you do not store your passwords inside your FTP software for this reason. Instead, you should manually re-enter passwords each time you wish to use FTP."])
    ], options)[0];
  },
  



  lockStatusNode: function(is_locked, other_content) {
    var c = [];
    if(is_locked) {
      c.push(_mkel("img", {src: "/images/icon_locked.png", alt: "Locked"}));
    } else {
      c.push(_mkel("img", {src: "/images/icon_unlocked.png", alt: "Unlocked"}));
    }
    c = c.concat(other_content);
    return _mkel("p", {className: "ftp-access-info"}, c);
  },
  




  ttlChoice: function(value, caption) {
    var t = this;
    return _mkel("div", [
      _mkel('input', {
        type: 'radio', 
        name: 'ttl', 
        'value': value,
        'id': 'ttl'+value+this.username
      }, function() {
        
        this.onclick = function() {
          this.checked = true; 
          t.ttl_chosen = this.value;
        }
        this.onchange = function() {
          if(this.checked) t.ttl_chosen = this.value;
        }
        if(this.value=='1') {
          this.checked=true;
          this.onclick();
        }
      }),
      " ",
      _mkel("label", {htmlFor: 'ttl'+value+t.username}, [caption])
    ]);
  },
  



  ttlChoices: function(choice_array) {
    return _mkel("div", {}, choice_array);
  },
  



  ttlChoiceList: function() {
    return this.ttlChoices([
      this.ttlChoice('1', "1 hour (recommended)"),
      this.ttlChoice('4', "4 hours"),
      this.ttlChoice('24', "1 day"),
      this.ttlChoice('168', "7 days (not recommended)"),
      this.ttlChoice('672', "28 days (not recommended)")
    ]);
  },
  



  ttlUnlockButton: function(e) {
    var t = this;
    e.onclick = function() {
      t.ajaxWithArgs({ttl: t.ttl_chosen||1});
      return false
    }
    return e;
  },
  




  ipUnlockButton: function(ip_address_input, e) {
    var t = this;
    e.onclick = function() {
      var acl = ip_address_input.value;
      var acl_parts = acl.split(/\s*,\s*/);
      for(var i=0; i<acl_parts.length; i++) {
        if(acl_parts[i].match(/^(192\.168|10)\./)) {
          alert("You have entered an internal IP address that is only accessible on your own network. Please enter your external network IP address");
          return false;
        } else if(!acl_parts[i].match(/^(\d+\.){3}\d+$/) ) {
          alert("You have entered an invalid IP address. Please try again.");
          return false;
        }
      }
      t.ajaxWithArgs({'ip-address': acl});
      return false
    }
    return e;
  },
  



  formContent: function() {
    var ip_address_input;
    return [
      _mkel("p", {className: "ftp-access-question"}, ["How long you would like to unlock FTP for:"]),
      this.ttlChoiceList(),
      _mkel("p", [ this.ttlUnlockButton(
        _mkel("input", {type: "submit", value: "Unlock by Time"})
      ) ]),
      _mkel("p", ["Or you can set an IP address to always have access. To set multiple addresses, separate them with a comma."]),
      _mkel("p", {style: {fontWeight: "bold"}}, ["Please enter it below."]),
      _mkel("p", [
        
        ip_address_input = _mkel("input", {type: "text", value: ip_address}),
        this.ipUnlockButton(ip_address_input, 
          _mkel("input", {type: "submit", value: "Unlock by IP"})
        )
      ])
    ];
  },
  



  lockFTPButton: function() {
    var t = this;
    return _mkel('input', {
      type: 'submit', 
      value: "Lock FTP now", 
      onclick: function() {
        t.ajaxWithArgs({ttl: '0'});
        return false;
      }
    })
  },
  





  showUI: function() {
    var reload_interval;
    var first_run = true;
    this.username = this.topElement.title;
    this.topElement.title = "";

    var opts = this.options;
    var te = this.topElement;

    var t = this;
    









    function ajax_with_args(args) {
      args = args || {};
      args.r = Math.random();
      args.v = "1.3";
      args.mode = opts.mode || "full";
      args.username = t.username;
      xmlhttp_simple_full("/ftp-access.cgi", args, undefined, reload_page);
    }

    this.ajaxWithArgs = ajax_with_args;

    





    function nice_time(ts) {
      var times = [
        {c: "day", s: 86400},
        {c: "hour", s: 3600},
        {c: "minute", s: 60}
      ];
      var now_local = (new Date()) / 1000;
      var seconds = ts - now_local;
      if(seconds<60) {
        ajax_with_args();
        if(reload_interval) {
          clearTimeout(reload_interval);
          reload_interval = undefined;
        }
        return "";
      }
      var components = [];
      for(var i=0; i<times.length; i++)
        if(seconds > times[i].s) {
          var remainder = seconds % times[i].s;
          var count = ((seconds-remainder) / times[i].s).toFixed(0);
          seconds = remainder;
          unit = times[i].c;
          if(count != 1) unit += "s";
          components.push(count + " " + unit);
        }
      return components.join(", ");
    } 
    




    function hide_block(hide_caption, block_content) {
      var link =  _mkel("div", {
          style: {
            width: "100%",
            textAlign: "center",
            paddingBottom: "5px"
          }
        }, [
          _mkel("img", {
            src: "/images/icon_info.png", 
            style: {
              padding: "0px 10px 0px 0px",
              marginBottom: "-3px"
            },
            alt: "Information"
          }),
          _mkel("a", {
            href: '#',
            onclick: function() {
              _add_nodes(this.parentNode.parentNode, block_content);
              this.parentNode.parentNode.removeChild(this.parentNode);
              return false;
              }
            }, [hide_caption])
          ]
        );
      return [ link ];
    }
    







    function reload_page(e) {
      var ftp_el = e.getElementsByTagName("ftp").item(0);
      var ntop = te.cloneNode(false);
      te.parentNode.replaceChild(ntop, te);
      te = ntop;
      var now_unix = e.getAttribute("now");
      var now_local = (new Date()) / 1000;
      if(ftp_el) {
        if( ftp_el.getAttribute("allowed-from") ) {
          _add_nodes(ntop, ip_acl(ftp_el.getAttribute("allowed-from")));
        } else if( ftp_el.getAttribute("expires") > now_unix ) {
          _add_nodes(ntop, expires(ftp_el.getAttribute("expires") - now_unix + now_local));
        } else if(opts.startHidden && first_run) {
          _add_nodes(ntop, hide_block("Unlock", choices(), true));
        } else {
          _add_nodes(ntop, choices());
        }
      } else {
        _add_nodes(ntop, coming_soon());
      }
      first_run = false;
    }
    





    function choices(override_info, no_click) {
      if(no_click)
        return t.withTitle("Unlock FTP",
          [
          _mkel("p", ["Unable to get FTP lock status. Please reload the page and try again."])
          ]
        );

      var content = [
        override_info || t.lockStatusNode(true, [
          "FTP is ", _mkel("strong", ["currently locked."])
        ])
      ];
      if(!opts.skipBodyInfoPopup)
        content.push( _mkel("div", [t.infoPopup()]) );

      content = content.concat( t.formContent() );
      return t.withTitle("Unlock FTP", content);
    }
    





    function expires(expires_ts) {
      return t.withTitle("Lock FTP", [
        t.lockStatusNode(false, [
          "FTP is ",
          _mkel("strong", "currently unlocked"),
          " and will be automatically locked in ",
          _mkel("span",
            [nice_time(expires_ts)],
            function() {
              var t = this;
              function reload() {
                t.firstChild.data = nice_time(expires_ts);
              }
              reload_interval = setInterval(reload, 15000);
            }
          ),
          "."
        ]),
        t.lockFTPButton()
      ]);
    }
    



    function coming_soon() {
      return choices(
        t.lockStatusNode(false, [
          "FTP is ",
          _mkel("strong", ["currently unlocked."])
        ]),
        true
      );
    }
    




    function ip_acl(ip_addresses) {
      return t.withTitle("Lock FTP", [
        t.lockStatusNode(false, [
          "FTP is ", _mkel("strong", "currently unlocked"),
          " for the IP address(es): ",
          ip_addresses
        ]),
        t.lockFTPButton()
      ]);
    }
    if(
      (typeof(small_screen) == 'undefined' || !small_screen) ||
      this.options.onSmallScreen
    ) ajax_with_args();
  }
}






function ftp_access_ui(options) {
  options = options || {};
  var es = _u_prototype.call(document, "getElementsByClassName", "ftp-access-box");
  for(var i=0; i<es.length; i++) new FTPAccessUI(es[i], options).showUI();
}

