﻿var arteWhoisSearcher = Class.create({
//   blackList : [0,16,17,18,37,38,39,40,106,107,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,144,145,186,187,188,189,190,191,192,219,220,221,222],
  blackList : [145,Event.KEY_ESC, Event.KEY_LEFT, Event.KEY_UP, Event.KEY_RIGHT, Event.KEY_DOWN, Event.KEY_DELETE, Event.KEY_HOME, Event.KEY_END, Event.KEY_PAGEUP, Event.KEY_PAGEDOWN],
  loadingMsg : 'Buscando...',
  availableMsg : '¡Está disponible!',
  notAvailableMsg : '¡No disponible. ¿Es tuyo?!',
  registerText : 'Regístralo',
  transferText : 'Trasládalo',

  initialize: function(field) {
    this.field = $(field);
    this.field.focus();
    this.form = this.field.up('form');
    this.form.observe('submit', function(e) { e.stop(); });

    this.field.observe('keyup', this.showDomains.bindAsEventListener(this));
    this.field.observe('keyup', this.timeout.bindAsEventListener(this));
    this.field.observe('keydown', this.spaceHacking.bindAsEventListener(this));
    this.timer = null;
    this.request = null;

    $('registerAvailables').observe("click", function(){
      //Only .es because technical restrictions
      if ($('ajaxDomainListEsCheckbox').checked == true && $('ajaxDomainListEs').domainFree == true) {
        $('registerAvailables').href = 'dom_com_reg.aspx?domain='+$('searchTextfield').value+'.es';
        $('registerAvailables').click();
      } else {
        var go = false;
        var form = new Element('form', {method: 'get', action: 'registro-de-dominios.aspx'});
        if ($('ajaxDomainListComCheckbox').checked == true && $('ajaxDomainListCom').domainFree == true) {
          form.insert(new Element('input', {name: 'chedomains', value: $('searchTextfield').value+'.com', type: 'hidden'}));
          go = true;
        }
        if ($('ajaxDomainListNetCheckbox').checked == true && $('ajaxDomainListNet').domainFree == true) {
          form.insert(new Element('input', {name: 'chedomains', value: $('searchTextfield').value+'.net', type: 'hidden'}));
          go = true;
        }
        if (go == true) {
          form.insert(new Element('input', {name: 'whoisdomain', value: 'true', type: 'hidden'}));
          form.insert(new Element('input', {name: 'domain', value: $('searchTextfield').value, type: 'hidden'}));
          $(document.body).insert(form);
          form.submit();
        }
      }
    });

    $('showMoreResults').observe("click", this.showMoreResults);
    $('findDomains').observe("click", this.showMoreResults);

    $('ajaxDomainListEsCheckbox').observe("click", function(){
      $('ajaxDomainListComCheckbox').checked = false;
      $('ajaxDomainListNetCheckbox').checked = false;
    });

    $('ajaxDomainListComCheckbox').observe("click", function(){
      $('ajaxDomainListEsCheckbox').checked = false;
    });

    $('ajaxDomainListNetCheckbox').observe("click", function(){
      $('ajaxDomainListEsCheckbox').checked = false;
    });
  },

  spaceHacking : function(event)  {
    if (event.keyCode == '32') {
//        console.log($('searchTextfield').value);

//        console.log($('searchTextfield').value);
    }
  },

  showMoreResults : function(){
    //Only .es because technical restrictions
    if ($('searchTextfield').value && $('searchTextfield').value.length > 2) {
      var form = new Element('form', {method: 'post', action: 'registro-de-dominios.aspx'});
      form.insert(new Element('input', {name: 'defaultdomain', value: $('searchTextfield').value, type: 'hidden'}));
      $(document.body).insert(form);
      //console.log("AASDASD");
      form.submit();
    }
  },

  showDomains : function(event)
  {
    for(var x=0; x < this.blackList.length;x++) {
      if (event.keyCode == this.blackList[x]) {
          return;
      }
    }
    $('searchTextfield').value = $('searchTextfield').value.replace(/ +/g,"-");
    $('searchTextfield').value = $('searchTextfield').value.replace(/ñ+/g,"n");
    $('searchTextfield').value = $('searchTextfield').value.toLowerCase();
    if (event.keyCode == Event.KEY_RETURN) {
      this.showMoreResults();
      return;
    }
//     console.log(event.keyCode);
    var value = this.cleanDomain($('searchTextfield').value);

    $('ajaxDomainListCom').removeClassName('no');
    $('ajaxDomainListCom').removeClassName('si si2');
    $('ajaxDomainListCom').addClassName('cargando');
    $('ajaxDomainListComLoadImage').show();
    $('ajaxDomainListComCheckbox').hide();
    $('ajaxDomainListComName').innerHTML = "<strong>"+value+'</strong><span class="ajaxDomainListTld">.com</span>';
    $('ajaxDomainListComMsg').innerHTML = this.loadingMsg;

    $('ajaxDomainListNet').removeClassName('no');
    $('ajaxDomainListNet').removeClassName('si si2');
    $('ajaxDomainListNet').addClassName('cargando');
    $('ajaxDomainListNetLoadImage').show();
    $('ajaxDomainListNetCheckbox').hide();
    $('ajaxDomainListNetName').innerHTML = "<strong>"+value+'</strong><span class="ajaxDomainListTld">.net</span>';
    $('ajaxDomainListNetMsg').innerHTML = this.loadingMsg;

    $('ajaxDomainListEs').removeClassName('no');
    $('ajaxDomainListEs').removeClassName('si si2');
    $('ajaxDomainListEs').addClassName('cargando');
    $('ajaxDomainListEsLoadImage').show();
    $('ajaxDomainListEsCheckbox').hide();
    $('ajaxDomainListEsName').innerHTML = "<strong>"+value+'</strong><span class="ajaxDomainListTld">.es</span>';
    $('ajaxDomainListEsMsg').innerHTML = this.loadingMsg;

    if (value.length > 2) {
      $('ajaxDomainList').appear();
    } else {
      $('ajaxDomainList').hide();
    }
  },

  timeout : function(event)
  {
    for(var x=0; x < this.blackList.length;x++) {
      if (event.keyCode == this.blackList[x]) {
          return;
      }
    }
    if (event.keyCode == Event.KEY_RETURN) {
      return;
    }
    if (this.timer != null) {
      this.timer.stop();
      this.timer = null;
    }

    if ($('searchTextfield').value.length < 3) {
      return;
    }
    $('registerAvailables').hide();
    this.timer = new PeriodicalExecuter(this.doWhois.bind(this),0.5);
  },

  doWhois : function() {
    if ($('searchTextfield').value.length < 3) {
      return;
    }

    if (this.request != null) {
      this.request.transport.onreadystatechange = Prototype.emptyFunction;
      this.request.transport.abort();
      Ajax.activeRequestCount --;
    }

    this.timer.stop();
    this.timer = null;

    var toSearch = this.cleanDomain(this.field.getValue());

    this.request = new Ajax.Request('apiwhois.aspx?',
    {
      method:'get',
      parameters : {domainName : toSearch},
      onSuccess: this.createBoxes.bind(this),
      onFailure: function(){ }
    });
  },

  cleanDomain : function(domain)
  {
    domain = domain.replace(/ +/g,"-");

    if (domain.substr(0,7) == "http://") {
      domain = domain.substr(7,domain.length)
    }

    if (domain.substr(0,6) == "http:/") {
      domain = domain.substr(6,domain.length)
    }

    if (domain.substr(0,5) == "http:") {
      domain = domain.substr(5,domain.length)
    }

    if (domain.substr(0,4) == "www.") {
      domain = domain.substr(4,domain.length)
    }

    var patt1=/\./gi;

    var matches = domain.match(patt1);

    if (!matches) {
      numOfDots = 0;
    } else {
      numOfDots = matches.length;
    }

    if (numOfDots != 0) {
      //We check if it's not in the final, .com .es etc
      if (numOfDots == 1) {
        var pos = domain.indexOf('.');
        pos = pos + 1;
        domain = domain.substr(0,pos-1);
      }

      if (numOfDots == 2) {
        var pos = domain.indexOf('.');
        var pos2 = domain.lastIndexOf('.');

        var result = pos2 - pos;
        if (result == 3 || result == 4) {
          domain = domain.substr(0,pos);
        }
      }
    }
    return domain;
  },

  createBoxes : function(transport) {
    var json = transport.responseText.evalJSON();
    var free = 0;
    for (var x = 0; x < json.length; x++) {
      var item = json[x];
      var ext = item.domain[0].toUpperCase();
      ext = ext+item.domain.substr(1,item.domain.length);
      var baseName = 'ajaxDomainList'+ext

      if (item.error && item.error == true) {
        $(baseName).hide();
        $(baseName+'Checkbox').checked = false;
      } else {
        $(baseName).show();
        if (item.free == true) {
          $(baseName).removeClassName('no');
          $(baseName).removeClassName('cargando');
          $(baseName).addClassName('si si2');
          $(baseName+'LoadImage').hide();
          $(baseName+'Msg').innerHTML = this.availableMsg+' <a href="dom_com_reg.aspx?domain='+$('searchTextfield').value+'.'+item.domain+'&product=7">Regístralo</a>';
          $(baseName+'Checkbox').show();
          $(baseName+'Checkbox').checked = true;
          $(baseName).domainFree = true;// Smal hack to evade another loop, TODO: fix that with a better json
          free++;
        } else {
          $(baseName).removeClassName('si si');
          $(baseName).removeClassName('cargando');
          $(baseName).addClassName('no');
          $(baseName+'LoadImage').hide();
          $(baseName+'Checkbox').hide();
          $(baseName+'Checkbox').checked = false; //Just to be sure, we don't want that in anyway
          $(baseName+'Msg').innerHTML = this.notAvailableMsg+' <a href="dom_com_reg.aspx?domain='+$('searchTextfield').value+'.'+item.domain+'&product=79">Trasládalo</a>';
          $(baseName).domainFree = false;
        }
      }
    }

    //If .es is free
    if ($('ajaxDomainListCom').domainFree == true || $('ajaxDomainListNet').domainFree == true) {
      $('ajaxDomainListEsCheckbox').checked = false;
    }

    //Is a crap have to do a bucle again, but is needed because of the json design, we'll improve it later
    if (free == 0) {
      $('registerAvailables').hide();
    } else {
      $('registerAvailables').show();
    }
  }
});

var magicSlide = Class.create({
  counter : 0,
  maxCounter : 0,
  images : '',
  initialize: function() {
    this.slideContainer = $('magicSlideContainer');
    this.images = this.slideContainer.select('div').toArray();
    this.maxCounter = this.images.length-1;

    $('backButton').observe('click', this.backSlide.bindAsEventListener(this));
    $('nextButton').observe('click', this.nextSlide.bindAsEventListener(this));
  },

  nextSlide : function()  {
    var oldCounder = this.counter;
    this.counter++;
    if (this.counter > this.maxCounter) {
      this.counter = 0;
    }

    var oldSlide = this.images[oldCounder];
    var newSlide = this.images[this.counter];

    (new Effect.DropOut(oldSlide,{duration : 0.5, queue: 'end' }));
    (new Effect.Appear(newSlide,{duration : 0.1, queue: 'end'}));
  },

  backSlide : function() {
    var oldCounder = this.counter;
    this.counter--;
    if (this.counter < 0) {
      this.counter = this.maxCounter;
    }

    var oldSlide = this.images[oldCounder];
    var newSlide = this.images[this.counter];

    (new Effect.DropOut(oldSlide,{duration : 0.5, queue: 'end' }));
    (new Effect.Appear(newSlide,{duration : 0.1, queue: 'end'}));
  }
});
