/* JS Doc.
 * 
 * This script uses AJAX to post information to a php script, and receives
 * a JSON response back.
 */


$(document).ready(function() {
  
  
  function getQuerystring(key) {
    /* */
    var deflt = "";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    var keyVal = "";
    if (qs == null) {
      keyVal = deflt;
    }
    else {
      keyVal = qs[1];
      if (keyVal.length < 1) {
        keyVal = "__zz";
      }
    }
    return keyVal;
  }
  
  
  function postShowResult() {
    /* Takes a text search box value, and does an AJAX request to the HSPC
     * web service API via a PHP script. Displays an image with the results of
     * the web service query. */
    
    /* Check if user submitted a search from the Home page, not the Domains page.
     * If so, the search value is in the GET query string in the URL. */
    var $ps_domain_name = getQuerystring("ps_dom_from_home");
    if ( ($ps_domain_name.length < 1) || ($("#searchedAlready").val() == "1") ) {
      // Get Domains page form inputs instead.
      $ps_domain_name = $('input[name="ps_domain_name"]').val();
      if ($("#tld").length > 0) {
        // There is a Top Level Domain input field, so add it to the domain string.
        var $tld = $("#tld").val();
        $ps_domain_name = $ps_domain_name + "." + $tld;
      }
    }
    else {
      /* Store the fact that a search has been done at least once, so the GET string
      will no longer be used for searches. */
      $("#searchedAlready").val("1");
    }
    var $url = "/domains/register_new.php";
    var formData = {"ps_domain_name": $ps_domain_name};
    /* Call the AJAX post method. The web service should return an errors string
     * and a confirmation string.
     * Syntax: jQuery.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )
     */
    $.post($url,
          formData,
          function(data) {
            // Success function.
            var resp = $(data)[0];
            var errors = resp["errors"];
            var confirmation = resp["confirmation"];
            var picPath = "/images/";
            if (errors.length > 1) {
              var picToUse = picPath + "reg_unavailable.png";
              var textToUse = errors;
            }
            else {
              var picToUse = picPath + "reg_available.png";
              var textToUse = confirmation;
            }
            // Display the text result over an image.
            var imgHtml = '<img src = "' + picToUse + '" id = "domainCheckImg" />';
            imgHtml += '<div id = "domainCheckCaption">';
            imgHtml += textToUse + '</div>';
            $("#checkDomainResultBox").empty().append(imgHtml);

            $(document).click(function(e) {
              if ($("#domainCheckImg").length > 0) {
                // If there is a mouseclick outside the image, remove the image.
              }
            });
            
          },  // End of success function
          "json"
          );  // End of post request
  }
  
  
  $("#form").submit(function() {
    /* If the form on the Domains page is submitted by pressing Enter,
     * do an AJAX post instead of the default form submit. */ 
    postShowResult();
    return false;
  });
  
  
  $(".register").click(function() {
    /* If the form on the Domains page is submitted by pressing a button,
     * do an AJAX post instead of the default form submit. */ 
    postShowResult();
    return false;
  });
  
  
  $("#form1").submit(function(event) {
    /* If the form on the Home page is submitted,
     * do an AJAX post instead of the default form submit. */
    event.preventDefault();
    
    var $form1 = $("#form1");
    var $pdn = $("input[name='ps_domain_name']").val();
    var newForm = "<form method = 'get' action = ";
    newForm += "'/domains/index.php' id = 'newForm'>";
    newForm += "<input type = 'hidden' name = 'ps_dom_from_home' value = '" + $pdn + "' /></form>";
    $("body").append(newForm);
    $("#newForm").submit();
  });
  
  
  /* Run this check every time the index or domains pages load. If the request is a
   * bounce from the index page to domains with a GET string sent, display a bubble. */ 
  var $ps_domain_name = getQuerystring("ps_dom_from_home");
  if ($ps_domain_name.length > 0) {
    postShowResult();
  }
  
});

