﻿/**
 * (c) 2009, Nobis Ltd.
 */

function byId(id) {
  return document.getElementById(id);
}

function addHandler(el, event, handler) {
  if (typeof handler == "string") { handler = new Function(handler); }
  if (el.addEventListener) { el.addEventListener(event, handler, false); }
  else if (el.attachEvent) { el.attachEvent("on" + event, handler); }
}


CheckDomain = {

  msg: {
    invalidName: 'Неправильное имя домена &laquo;<strong>%s</strong>&raquo;'+
          '<div class="comment">Доменное имя может состоять только из букв латинского алфавита, ' +
          'цифр и знака &laquo;&minus;&raquo;, и должно оканчиваться на ' +
          '<strong>.ru</strong>, <strong>.com</strong> или другой домен верхнего уровня '+
          'из перечисленных выше. Длина имени должна составлять не менее двух символов.</div>',
    serverError: 'Ошибка при получении данных',
    domainAvailable: 'Домен <strong>%s</strong> доступен для регистрации!' +
          '<div class="comment">Спешите! Каждый месяц только в домене .RU региструется '+
          'более&nbsp;50&nbsp;тысяч новых имен!</div>',
    domainNotAvailable: 'Доменное имя <strong>%s</strong> уже занято'
  },

  url: "http://" + window.location.host + '/whois?domain=',
  slideTimeout: 10, // ms per pixel of height, see this.slide
  slideStep: 3,
  input: null,

  init: function() {
    this.input = byId("check-domain-input");
    addHandler(this.input, "focus", "CheckDomain.onFocus()");
    addHandler(this.input, "blur",  "CheckDomain.onBlur()");
    addHandler(byId("check-domain-submit"), "click",  "CheckDomain.onSubmit()");
    addHandler(byId("check-domain-form"),   "submit", "CheckDomain.onSubmit()");
  },

  onFocus: function() {
    var i = this.input;
    if (i.className == "empty") { // remove the prompt
      i.title = i.value;
      i.value = "";
      i.className = "";
    }
  },

  onBlur: function() {
    var i = this.input;
    if (i.value == "") {
      i.className = "empty";
      i.value = i.title;
    }
  },

  onSubmit: function() {
    var name = this.input.value, xhr;
    if (!name) { return; }
    if (!this.isValidName(name)) { return this.onError(this.msg.invalidName); }

    // var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    try { xhr = new XMLHttpRequest(); } catch(e) { // Mozilla, IE7
    try { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {
    try { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} } }
    if (!xhr) { return this.onError(); }

    xhr.open("GET", this.url + name, true);
    xhr.onreadystatechange = function() { CheckDomain.processResponse(xhr); }
    xhr.send(null);
  },

  processResponse: function(xhr) {
    if (xhr.readyState == 4) {
      switch (xhr.responseText) { // no need to check status==200
        case 'AVAIL': return this.onAvailable();
        case 'NA':    return this.onNotAvailable();
        // all other responses are treated as error
        default:      return this.onError();
      }
    }
  },

  onError: function(msg) {
    if (!msg) { msg = this.msg.serverError; }
    this.showResult("error", msg);
  },

  onAvailable: function() {
    this.showResult("ok", this.msg.domainAvailable);
  },

  onNotAvailable: function() {
    this.showResult("na", this.msg.domainNotAvailable);
  },

  showResult: function(className, message) {
    byId("check-domain").className = className;
    var r = byId("check-domain-result");
    r.innerHTML = message.replace("%s", this.input.value);
    this.slide(byId("check-domain-result-wrapper"), r, this.slideTimeout, this.slideStep);
  },

  slide: function(outer, inner, time, step) {
    var delta = outer.clientHeight - (document.all ? inner.scrollHeight : inner.clientHeight);
    if (delta != 0) {
      var dir = (delta > 0 ? -1 : 1),
          delta = Math.abs(delta),
          x = dir * (step > delta ? delta : step);
      outer.style.height = (outer.clientHeight + x) + "px";
      window.setTimeout(function() { CheckDomain.slide(outer, inner, time, step); }, time);
    }
  },

  isValidName: function(n) {
    return (n.charAt(0) != "-" && n.search(/^[a-zа-я\d\-]{1,62}[a-zа-я\d]\.(?:ru|su|рф|com|biz|org|net|info)$/i) != -1)
  }

}

addHandler(window, "load", "CheckDomain.init()");

