$(function() {
  var limitString   = 140;

  $("#stringCount").text(limitString);

  $("#editProfile")
    .val("")
    .attr("disabled", "disabled");

  $("#dl")
    .attr("disabled", "disabled")
    .click(function() {
      if ($(this).attr("disabled") == "disabled") {
        return false;
      }
      $("#generator").attr("action", "./create_pdf.php");
  });

  $("#od")
    .attr("disabled", "disabled")
    .click(function() {
      if ($(this).attr("disabled") != "") {
        return false;
      }
      $("#generator").attr("action", "./pre_order.php");
  });

  $("#userId").keyup(function() {
    if (window.event.keyCode == 13) {
      return false;
    }
  });

  $(".btn_ok").click(function() {
    generateImage();
  });

  $("#image_list > li > img").click(function() {
    $("#baseImg").attr("value", $(this).attr("alt"));
    generateImage();
  });

  $("input[name='layoutPattern']").click(function() {
    generateImage();
  });

  $("input[name='fontIndex']").click(function () {
    generateImage();
  });

  $("#editProfile").keyup(function() {
    countChars($(this).val().length);
  });

  /**
   * AJAXレスポンスデータを各コンポーネントにセット
   *
   * @param  object
   * @return void
   */
  function setComponents(jsonObject)
  {
    var fileName = "./preview/" + jsonObject.fileName + "?" + new Date().getTime();

    if (jsonObject.error == undefined) {
      $("#tmp_description").attr("value", jsonObject.description);
      $("#tmp_location").attr("value", jsonObject.location);
      $("#tmp_name").attr("value", jsonObject.name);
      $("#tmp_profile_image_url").attr("value", jsonObject.profile_image_url);
      $("#tmp_qr_code").attr("value", jsonObject.qr_code);
      $("#tmp_screen_name").attr("value", jsonObject.screen_name);
      $("#tmp_url").attr("value", jsonObject.url);

      $("#currentUser").attr("value", $("#userId").attr("value"));
      $("#editProfile").attr("disabled", "").val(jsonObject.description);
      $("#dl, #od").attr("disabled", "");
      countChars($("#editProfile").val().length);
    }

    $("#cardImage").html('<img src="' + fileName + '" alt="' + jsonObject.fileName + '" width="362" height="218" />');
  }

  /**
   * AJAXリクエストでJSONデータを取得
   *
   * @param  void
   * @return void
   */
  function generateImage()
  {
    var baseUrl       = "http://twimeishi.jp/show_image.php";
    var userId        = $("#userId").attr("value");
    var baseImg       = $("#baseImg").attr("value");
    var fontIndex     = $("input[name='fontIndex']:checked").val();
    var editProfile   = $("#editProfile").val();
    var currentUser   = $("#currentUser").attr("value");

    var tmpDescription = $("#tmp_description").attr("value");
    var tmpLocation    = $("#tmp_location").attr("value");
    var tmpName        = $("#tmp_name").attr("value");
    var tmpProfileUrl  = $("#tmp_profile_image_url").attr("value");
    var tmpScreenName  = $("#tmp_screen_name").attr("value");
    var tmpUrl         = $("#tmp_url").attr("value");

    if (userId == "") {
      return false;
    }

    postData  = "userId=" + encodeURI(userId);
    postData += "&baseImg=" + encodeURI(baseImg);
    postData += "&fontIndex=" + encodeURI(fontIndex);
    postData += "&editProfile=" + encodeURI(editProfile);
    postData += "&currentUser=" + encodeURI(currentUser);
    postData += "&tmp_description=" + encodeURI(tmpDescription);
    postData += "&tmp_location=" + encodeURI(tmpLocation);
    postData += "&tmp_name=" + encodeURI(tmpName);
    postData += "&tmp_profile_image_url=" + encodeURI(tmpProfileUrl);
    postData += "&tmp_screen_name=" + encodeURI(tmpScreenName);
    postData += "&tmp_url=" + encodeURI(tmpUrl);

    $.ajax({
      cache: false,
      data: postData,
      dataType: "json",
      type: "POST",
      url: baseUrl,
      beforeSend: function(XMLHttpRequest) {
        $("#cardImage")
          .css("background-image", "none")
          .html('<img src="./images/loading.gif" alt="Now loading"/>');
      },
      error: function(XMLHttpRequest, statusText, errorObject) {
        setComponents(null);
      },
      success: function(data, dataType) {
        setComponents(data);
      }
    });
  }

  /**
   * プロフィールの文字数制限制御
   *
   * @param  integer
   * @return void
   */
  function countChars(charCount)
  {
    var targetObj = $("#stringCount");
    var chars     = limitString - charCount;
    
    targetObj.text(chars);
    if (chars < 0) {
      targetObj.addClass("char_minus");
    } else {
      targetObj.removeClass("char_minus");
    }
  }
});

