var SetsuyakuFaveAction = function() {
}

SetsuyakuFaveAction.prototype.getTypeAndPostid = function(url) {
  var options = url.split('/');
  var postid = options[options.length - 2];
  var type = options[options.length - 1];
  type = type.split('?');
  return [type[0], postid];
}

SetsuyakuFaveAction.prototype.addFaveAction = function(target) {
  var my = this;
  var obj = $(target);
  var page = obj.attr('href');
  var options = my.getTypeAndPostid(page);
  var type = options[0];
  var postid = options[1];
	$.ajax({
		url: page,
		success: function(data) {
			var counter = '.' + type + 'Counter' + postid;
      if (data.match(/^false/)) {
        alert('★すでにクリックを頂戴し、カウントいたしました★');
      } else {
        $value = parseInt(data);
        if (!isNaN($value)) {
          if ($value > 0) {
            $(counter).text($value);
          }
        }
      }
		},
    error: function(data) {
      alert('クリックを正常にカウントできませんでした。お手数ですが、時間をおいて再度お試しくださいませ。');
    }
	});
}

function linkToWindowAddCloseButton() {
  var target = '.toWindow';
  $(target).prepend(
    '<p id="toWindowCancel"><a href="#" class="simplemodal-close"><img src="/images/window-close.gif" alt="閉じる" /></a></p>'
  );
  $('.simplemodal-close').click(function() {
    $.modal.close();
    return false;
  });
}

function linkToWindowFormSubmit() {
  $('.toWindow form').submit( function() {
    $('#toWindowContainer').load(
      $('.toWindow form').attr('action') + ' .toWindow',
      $('.toWindow form :input').serializeArray(),
      function() {
        linkToWindowAddCloseButton();
        linkToWindowFormSubmit();
        $value = $('.toWindow .mailKeepValue').text();
        $post_id = $('.toWindow .mailKeepPostId').text();
        if ($post_id != '' && $value != '') {
          $('.MailKeepCounter' + $post_id).text($value);
        }
      }
    );
    return false;
  });
}

$(document).ready(function() {
  var faveAction = new SetsuyakuFaveAction();
  $('.faveAction').click(function() {
    faveAction.addFaveAction(this);
    return false;
  });

  $('.openWindow').click(function() {
    $.get(this, function(data) {
      $(data).contents().find('#toWindowOverlay').modal({
        position: ["30%", "30%"],
        overlayId: 'toWindowOverlay',
        containerId: 'toWindowContainer',
        overlayCss: {backgroundColor: "#666"},
        containerCss: {backgroundColor: "#FFF"},
        close: false
      });
      linkToWindowAddCloseButton();
      linkToWindowFormSubmit();
    });
    return false;
  });
});
