// Input Tip
(function($) {
  if('placeholder' in $('<input type="text" />')[0]) {
    $.fn.makeInputTip = $.fn.fitInputTip = $.fn.showInputTip = function() { return this; };
    return;
  }
  var inputTips = $([]);
  var currentFocus = null; // Webkit: onmousedown doesn't fire blur event
  $.fn.extend({
    makeInputTip: function() {
      return this.each(function() {
        if($.data(this, 'inputTipDiv') || !this.getAttribute('placeholder')) return;
        var jelt = $(this), pos = jelt.offset(), w = jelt.outerWidth(), h = jelt.outerHeight(),
            ta = this.tagName.toLowerCase() == 'textarea',
            ph = ta ? (h - jelt.height()) / 2 : 0, pw = (w - jelt.width()) / 2,
            div = $('<div/>');
        div.css({
          position: 'absolute',
          left: pos.left+'px', top: pos.top+'px',
          width: w+'px', height: h+'px', lineHeight: ta ? jelt.css('lineHeight') : h+'px',
          background: 'transparent', color: 'gray',
          fontFamily: jelt.css('fontFamily'),
          fontWeight: jelt.css('fontWeight'),
          fontStyle: jelt.css('fontStyle'),
          fontSize: jelt.css('fontSize'),
          overflow: 'hidden', cursor: 'text',
          MozUserSelect: 'none', WebkitUserSelect: 'none', userSelect: 'none',
          cursor: 'text'
        }).bind('click mousedown', function(ev) {
          if(currentFocus == this) return;
          ev.preventDefault();
          if($.browser.msie) setTimeout(function() { jelt.focus(); }, 1);
          else jelt[0].focus();
        }).append(
          $('<div/>').css({
            verticalAlign: ta ? 'baseline' : 'middle', textAlign: 'left',
            padding: ph+'px ' + pw+'px'
          }).attr('unselectable', 'on').text(this.getAttribute('placeholder'))
        );
        if(this.value != '') div.hide();
        $(document.body).append(div);
        $.data(this, 'inputTipDiv', div);
        inputTips.push(this);
      }).focus(function() {
        var div = $.data(this, 'inputTipDiv');
        if(div) div.hide();
        if(currentFocus != this) $(currentFocus).showInputTip();
        currentFocus = this;
      }).blur(function() {
        $(this).showInputTip();
        currentFocus = null;
      });
    },
    fitInputTip: function() {
      return this.each(function() {
        var jelt = $(this), div = $.data(this, 'inputTipDiv'), pos = jelt.offset(), cpos = div.offset(),
            w = jelt.outerWidth(), h = jelt.outerHeight();
        if(pos.top != cpos.top || pos.left != cpos.left) div.offset(pos);
        if(div.width() != w) div.css('width', w+'px');
        if(div.height() != h) div.css('height', h+'px');
      });
    },
    showInputTip: function() {
      return this.each(function() {
        var div = $.data(this, 'inputTipDiv');
        if(div) div[this.value == '' ? 'show' : 'hide']();
      });
    },
    valWithoutInputTip: $.fn.val,
    val: function(value) {
      var result = this.valWithoutInputTip.apply(this, arguments);
      if(arguments.length != 0) this.showInputTip();
      return result;
    }
  });
  $(function() {
    $('input[placeholder],textarea[placeholder]').makeInputTip();
    $(window).bind('load resize scroll', function() { inputTips.fitInputTip(); });
    $('[autofocus]').focus();
  });
})(jQuery);
(function($){
  $.fn.extend({
    lookupZip: function(afterFn) {
      function element(form, name) {
        return form.find('input[name$="['+name+']"],select[name$="['+name+']"],textarea[name$="['+name+']"]');
      }
      return this.each(function() {
        var button = $(this), form = $(this.form);
        var zip_code = element(form, 'zip_code');
        if(!/^\d\d\d-?\d\d\d\d$/.test(zip_code.val())) {
          alert('郵便番号（7桁）を入力してください');
          zip_code.focus();
          return;
        }
        button.disable();
        $.ajax({
          type: "GET",
          url: '/ajax/zip_lookup.json',
          data: { code: zip_code.val() },
          success: function(data, dataType){
            if(!data.postal_code) {
              alert('郵便番号 ' + zip_code.val() + ' に該当する住所が見つかりません。');
              return;
            }
            element(form, 'prefecture').val(data.pref);
            element(form, 'city').val(data.city);
            element(form, 'street').val(data.street + (data.address || ''));
            element(form, 'address').val('');
            if(data.name) {
              var company = element('company'), curr = company.val();
              if(!company.empty() && curr != '' && curr != data.name &&
                confirm('この番号は ' + data.name + ' の事業所郵便番号です。\n会社名を変更してもよろしいですか。'))
                element(form, 'company').val(data.name);
            }
            if(afterFn) afterFn.call(form, form);
          },
          error: function() {
            alert('サーバとの通信中にエラーが発生しました。');
          },
          complete: function() {
            button.enable();
          }
        });
      });
    },
    checkSubdomain:function(status) {
      status = $(status);
      return this.each(function() {
        status.addClass('loading').text('チェック中...');
        $.ajax({
          type: "POST",
          url: '/ajax/check_subdomain.json',
          data: { subdomain: this.value },
          success: function(data) {
            status.removeClass('loading').text(data.message ? 'すでに使用されています' : '使用可能です');
          },
          error: function() {
            status.removeClass('loading').text('サーバとの通信中にエラーが発生しました。');
          }
        });
      });
    }
  });
})(jQuery);
(function($){
  $(function(){
    var mailtos = $('a[href^="mailto:"]'), dialog;
    if(mailtos.length == 0) return;
    
    function openDialog(jelt) {
      var form = dialog.find('form');
      dialog.dialog({
        autoOpen: true, modal: true, position: 'center', width: 600, resizable: false,
        title: 'メール送信',
        open: function() {
          var uri = jelt.attr('href').split('?'), query = uri[1] ? uri[1].split('&') : [];
          $.each(query, function() {
            var kv = this.split('='), store = null;
            switch(decodeURIComponent(kv[0]).toLowerCase()) {
              case 'subject': store = dialog.find('[name=subject]'); break;
              case 'body': store = dialog.find('[name=body]'); break;
            }
            if(store) store.val(decodeURIComponent(kv[1]));
          });
        },
        buttons: {
          'キャンセル': function() {
            dialog.dialog('close');
          },
          '送信': function() {
            var elements = dialog.find('input,select,textarea,button'), sending = dialog.find('.dialogSending'),
                to = form.find('[name=to]');
            if(!to.val()) {
              alert('宛先が入力されていません');
              to.focus();
              return;
            }
            $.ajax({
              type: 'POST',
              url: '/ajax/sendmail.json',
              data: form.serialize(),
              beforeSend: function() {
                var div = dialog.find('.dialog');
                elements.disable();
                sending.css({
                  top: (div.height() - sending.outerHeight()) / 2,
                  left: (div.width() - sending.outerWidth()) / 2
                }).show();
              },
              complete: function() {
                elements.enable();
                sending.hide();
              },
              success: function(data) {
                if(data.success) {
                  alert('メールを送信しました。');
                  dialog.dialog('close');
                } else {
                  alert(data.message);
                }
              },
              error: function() {
                alert('サーバとの通信中にエラーが発生しました。');
              }
            });
          }
        }
      });
    }
    
    mailtos.click(function(ev) {
      var jelt = $(this), callfn = function() { openDialog(jelt); };
      ev.preventDefault();
      if(!dialog) {
        dialog = $('<div/>').hide().appendTo(document.body).load('/ajax/mailto_dialog.html', callfn);
      } else {
        callfn();
      }
    });
  });
  $(function(){
    $('.flashClose').hover(function() {
      $(this).addClass('ui-state-hover');
    }, function() {
      $(this).removeClass('ui-state-hover');
    }).click(function(ev) {
      ev.preventDefault();
      $(this.parentNode).fadeOut();
    });
  });
})(jQuery);

