var Domain;

$(function(){
  function buildPriceOptions(type, tld, currency) {
    var options = "",
        count = tld.min_registration_period,
        price = tld.brand_tld_prices[0][type];

    while (count <= tld.max_registration_period) {
      var period_price = price * count,
          formatted_period_price = (period_price / 100).toFixed(2);

      options += "<option value='" + count + "'>";
      options += count + " ";
      options += (count == 1) ? "year" : "years";
      
      if(currency == "usd"){
        label = "$";
      } else if (currency == "eur"){
        label = "&euro;";
      } else {
        label = "&pound;";
      }

      if (period_price === 0) {
        options += " / FREE!";
      } else {
        options += " / " + label + formatted_period_price;
      }

      options += "</option>";
      count++;
    }

    return options;
  }

  function buildTlds(tlds, tlds_type) {
    $.each(tlds, function (i, tld) {
      var html = "",
          t = tld.tld,
          escaped_name = t.name.replace(/^\./, "").replace(".", "-"),
          locale = $.cookie("locale"),
          currency;

      html += "<li id='" + escaped_name + "'>";
      html += "  <div class='domain'>";
      html += "    <strong class='subdomain'></strong><span class='extension'>" + t.name + "</span>";
      html += "  </div>";
      html += "  <div class='decisions'>";
      html += "    <div class='prices'>";
      html += "      <select class='price registration'>";

      if(/US/.test(locale)){
        currency = "usd";
      } else if (/(AT|BE|BG|CY|CZ|DK|EE|FI|FR|DE|GR|HU|IE|IT|LV|LT|LU|MT|NL|PL|PT|RO|SK|SI|ES|SE)/.test(locale)){
        currency = "eur";
      } else {
        currency = "gbp";
      }

      html += buildPriceOptions(currency + "_registration_fee", t, currency);

      html += "      </select>";
      html += "      <select class='price transfer'>";

      html += buildPriceOptions(currency + "_transfer_fee", t, currency);

      html += "      </select>";
      html += "    </div>";
      html += "    <div class='availability'>";
      html += "      &nbsp;";
      html += "    </div>";
      html += "    <div class='spinner'></div>";
      html += "    <div class='clear'></div>";
      html += "  </div>";
      html += "  <div class='clear'></div>";
      html += "</li>";

      $(html).appendTo("#tlds-" + tlds_type);
    });
  }

  var tldsAvailableToRegister, 
      tldsAvailableToTransfer, 
      popularTlds       = [],
      spinner           = "<img alt='Loading' height='16' src='images/spinner.gif' width='16' />",
      available_partial = "<a href='#' class='registration'>Register Now</a>",
      taken_partial     = "<a href='#' class='transfer'>Transfer</a>",
      disabled_partial  = "<a href='#' class='disabled'>Not Available - Why?</a>",
      added_partial     = "<a href='#' class='added'>Added</a>";

  $.ajax({
    async: false,
    url: "http://core.hostroute.com/setup_domain_tool.json?callback=?",
    type: "GET",
    dataType: "jsonp",
    success: function (data) {      
      tldsAvailableToRegister = data.available_to_register;
      tldsAvailableToTransfer = data.available_to_transfer;

      popularTlds = [];

      $.each(data.popular_tlds, function (i, tld) {
        popularTlds.push(tld.tld.name);
      });
            
      buildTlds(data.popular_tlds, "popular");
      buildTlds(data.other_tlds, "other");
    }
  });

  // Fix for IE's handling of indexOf
  if (!Array.indexOf) {
    Array.prototype.indexOf = function (obj) {
      for (var i = 0; i < this.length; i++) {
        if (this[i] == obj) {
          return i;
        }
      }

      return -1;
    };
  }

  Domain = {
    ajaxRequests: [],
    basketCount: function(){
      var cookie = $.cookie("unauthed_domain_basket") || "[]",
          arr = JSON.parse(cookie);
          
      return arr.length;
    },
    clearBasket: function(){
      $.cookie("unauthed_domain_basket", "[]");
      $("#domain-lookup-tool-utility-bar p").html("Domains to configure: <b>0</b>");
      $("#domain-lookup-tool-utility-bar").hide();
    },
    addDomainToBasket: function(name, tld, period, action){
      var data = $.cookie("unauthed_domain_basket") || "[]", str, cookie;

      cookie = JSON.parse(data);
      cookie.push({ n: name, t: tld, p: period, a: action });
      str = JSON.stringify(cookie);
            
      if(str.length > 4000) { throw("Cannot add domain to cookie; too long (over 4,000 characters)"); }

      $.cookie("unauthed_domain_basket", str, { domain: ".hostroute.com", path: "/" });
            
      return $.cookie("unauthed_domain_basket");
    },
    stopAllAjaxRequests: function () {
      $.each(Domain.ajaxRequests, function () {
        this.abort();
      });

      Domain.ajaxRequests = [];
    },
    containerFor: function (tld) {
      tld = tld.replace(/^\./, "");
      tld = tld.replace(/\./, "-");

      return $("#" + tld);
    },
    checkDomain: function (subdomain, tld) {
      var el = Domain.containerFor(tld);

      Domain.ajaxRequests.push($.ajax({
        type: "GET",
        url: "http://core.hostroute.com/lookup.json?callback=?",
        data: {
          query: subdomain + tld
        },
        dataType: "jsonp",
        beforeSend: function () {
          $(el).find("div.spinner").html(spinner).show();
        },
        complete: function () {
          $(el).find("div.spinner").empty().hide();
        },
        success: function (response) {
          var r = response.domain_lookup,
              domain = r.query,
              prices = $(el).find("div.prices"),
              availability = $(el).find("div.availability");

          $(prices).find("select").hide();

          if (r.available === true) {
            if (tldsAvailableToRegister.indexOf(r.tld.name) == -1) {
              $(el).addClass("disabled");

              $(availability).html(disabled_partial).addClass("disabled").css("visibility", "visible");
              $(prices).css("visibility", "hidden");
            } else {
              $(el).addClass("available");

              $(availability).html(available_partial).addClass("available").css("visibility", "visible");
              $(prices).css("visibility", "visible");
              $(prices).find("select.registration").show();
            }
          } else {
            if (tldsAvailableToTransfer.indexOf(r.tld.name) == -1) {
              $(el).addClass("disabled");

              $(availability).html(disabled_partial).addClass("disabled").css("visibility", "visible");
              $(prices).css("visibility", "hidden");
            } else {
              $(el).addClass("taken");

              $(availability).html(taken_partial).addClass("taken").css("visibility", "visible");
              $(prices).css("visibility", "visible");
              $(prices).find("select.transfer").show();
            }
          }
        }
      }));
    },
    clearSearch: function () {
      $("#domain-lookup-tool-empty").show();
      $("#domain-lookup-tool-results").hide();
      $("#domain-lookup-tool-search-box input[type='text']").val("").attr("placeholder", "Enter phrase to start search");
    },
    alphabeticalSort: function (a, b) {
      var aB = $(a).text().toLowerCase(),
          bA = $(b).text().toLowerCase();

      if (aB > bA) {
        return 1;
      } else if (aB < bA) {
        return -1;
      } else {
        return 0;
      }
    },
    performLookup: function (tlds) {
      var subdomain = $("#domain-lookup-tool-search-box input[type='text']").val();

      $(tlds).each(function () {
        Domain.checkDomain(subdomain, this);
      });
    },
    registrationRequest: function (button) {
      var parent = $(button).parent().parent().parent(),
          name   = $.trim($(parent).find("div.domain strong.subdomain").text()),
          tld    = $.trim($(parent).find("div.domain span.extension").text()),
          period = $(parent).find("select.price").val(),
          count  = Domain.basketCount();

      Domain.addDomainToBasket(name, tld, period, "registration");
      
      $(parent).find("div.prices").css("visibility", "hidden");
      $(button).replaceWith(added_partial);
      $("#domain-lookup-tool-utility-bar").show();
      $("#domain-lookup-tool-utility-bar p b").html(count + 1).effect("highlight");
    },
    transferRequest: function (button) {
      var parent = $(button).parent().parent().parent(),
          name   = $.trim($(parent).find("div.domain strong.subdomain").text()),
          tld    = $.trim($(parent).find("div.domain span.extension").text()),
          period = $(parent).find("select.price").val(),
          count  = Domain.basketCount();

      Domain.addDomainToBasket(name, tld, period, "transfer");
      
      $(parent).find("div.prices").css("visibility", "hidden");
      $(button).replaceWith(added_partial);
      $("#domain-lookup-tool-utility-bar").show();
      $("#domain-lookup-tool-utility-bar p b").html(count + 1).effect("highlight");
    }
  };

  var tld_column = $("#domain-lookup-tool-results"),
      empty_column = $("#domain-lookup-tool-empty"),
      tlds = $("ul.tlds"),
      query = $("#domain-lookup-tool-search-box input[type='text']"),
      filters = $("#domain-lookup-tool-rules"),
      error_message = $("#domain-lookup-tool-error"),
      count = Domain.basketCount();

  $().ajaxStart(function () {
    $("a").blur();
    $(query).blur().attr("disabled", true).addClass("disabled");
  });

  $().ajaxStop(function () {
    $(query).focus();
    $(query).attr("disabled", false).removeClass("disabled");
  });

  // Unload all AJAX requests when unloading the window
  $(window).bind("unload", function () {
    Domain.stopAllRequests();
  });
    
  if(count > 0){
    $("#domain-lookup-tool-utility-bar p b").html(count);
    $("#domain-lookup-tool-utility-bar").show();    
  } else {
    $("#domain-lookup-tool-utility-bar").hide();
  }

  $("div.spinner").ajaxStop(function () {
    $(this).hide();
  });

  $("a.transfer").live("click", function () {
    Domain.transferRequest(this);
    return false;
  });

  $("a.registration").live("click", function () {
    Domain.registrationRequest(this);
    return false;
  });
  
  $("a.added").live("click", function () {
    return false;
  });

  $("#domain-lookup-tool-results ul").selectable({
    filter: "li",
    cancel: ":input, option, a",
    stop: function () {
      var subdomain = $(query).val();

      $(".ui-selected", this).each(function () {
        var tld = $(this).find("span.extension").text();

        Domain.checkDomain(subdomain, tld);
      });
    }
  });

  $(query).keyup(function (e) {
    var value = $(this).val();

    // Remove all classes
    $(tld_column).find("li").removeClass();
    $(tld_column).find("div.availability").html("&nbsp;");
    $(tld_column).find("div.prices").css("visibility", "hidden");

    // Do some validation
    if (!value.match(/^[A-Za-z0-9]{1}[A-Za-z0\-]{1,61}[A-Za-z0-9]{1}$/)) {
      $(tld_column).hide();
      $(empty_column).show();

      if (value.length > 3) {
        $(filters).hide();
        $(error_message).show();
        $(query).addClass("error");
      }
    } else {
      $(tld_column).show();
      $(empty_column).hide();
      $(filters).show();
      $(error_message).hide();
      $(query).removeClass("error");
    }

    // Set all the TLDs in the search column
    $.each($(tlds).find("li"), function () {
      $(this).find("strong.subdomain").text(value);
    });

    // If a carriage return (or "Enter key") is pressed,
    // then we'll automatically start a search for popular TLDs
    if (e.keyCode == 13) {
      Domain.performLookup(popularTlds);
    }
  });
  
  $("#domain-lookup-tool-clear-bucket").live("click", function(){
    Domain.clearBasket();
    Domain.clearSearch();
    
    return false;
  });
});
