/*
 * jQuery Disable On Submit Plugin
 * http://www.evanbot.com/article/jquery-disable-on-submit-plugin/13
 *
 * Copyright (c) 2009 Evan Byrne (http://www.evanbot.com)
 */
$.fn.disableOnSubmit = function(disableList){
  if(disableList == null){var $list = 'input[type=submit],input[type=button],input[type=reset],button';}
  else{var $list = disableList;}

  // Makes sure button is enabled at start
  $(this).find($list).removeAttr('disabled');

  $(this).submit(function(){$(this).find($list).attr('disabled','disabled');});
  return this;
};

/**
 * FeBe x Facebook
 */
febe = {};
febe.facebook = {
  init: function() {
    // Facebook Connect の status を調べる
    FB.getLoginStatus(function(response){
      $('.facebook-loading').hide();
      if (response['status'] && response['status'] == 'connected') {
        $('.facebook-connected').show();
        // FeBe ユーザーで且つ Facebook Connected であるユーザーの場合は Fan かどうかを調べる
        $('.authenticated').ready(function() {
          var query = FB.Data.query('SELECT created_time FROM page_fan WHERE uid = me() AND page_id = 200635109967253');
          query.wait(function(rows) {
            if (rows.length && rows[0]['created_time']) {
              $('.facebook-liked').show();
            }
          });
        });
      } else {
        $('.facebook-offline').show();
      }
    });
  }
};

/**
 * febe.js
 *
 * @author ksato
 */
(function($){$(function(){

  var mouse_x, mouse_y;

  /**
   * ヘッダー部マウスオーバー時の動作
   */
  $('#genre_nav > li').hover(function(){
    var elem = $(this);
    elem.addClass('hover');
    $('.ua-ie-7 .social-plugins').hide();
    var offset = elem.offset();
    var position = elem.position();
    var w_width = $(window).width();
    if (position.left + 400 > 980 + ((w_width - 980) / 2)) {
      offset.left = 576 + ((w_width - 980) / 2);
    }
    elem.children('.genre_' + elem.attr('data-large_genre_id'))
      .css({
        position: 'absolute',
        top: offset.top + 60,
        left: offset.left + 1
      })
      .show();
  }, function(){
    var elem = $(this);
    elem.removeClass('hover');
    $('.ua-ie-7 .social-plugins').show();
    elem.children('.genre_' + elem.attr('data-large_genre_id')).hide();
  });

  /**
   * form の二重送信を防止する
   */
  $("form:not(#resign)").disableOnSubmit();

  /**
   * class=instant 内の select が変更されたときに submit する
   */
  $('.instant select').change(function(){
    $(this).parents('form').submit();
  });

  /**
   * class=async を持つ form は，非同期に submit する
   */
  var async_action = function(){
    var form = $(this);
    $.ajax({
      url: form.attr('data-async_action'),
      type: form.attr('method'),
      data: form.serialize(),
      dataType: 'json',
      success: function(data){
        if (data['status'] == 0) {
          form.find('input,button').attr('disabled', 'disabled');
        }
        if (data['class']) {
          form.addClass(data['class']);
        }
        if (data['message']) {
          var tooltip = $('<div class="tooltip"><p class="close">x</p><p class="message">'+data.message+'</p></div>');
          tooltip.children('.close').click(function(){
            tooltip.fadeOut('fast');
          });
          setTimeout(function(){
            tooltip.fadeOut('fast');
          }, 7000);
          form.after(tooltip);
        }
      }
    });

    return false;
  };

  $('form.async').submit(async_action);

  /**
   * name=__febe_allcheck の checkbox がチェックされたときにその form が持つ checkbox を全て変更する
   */
  $('input[type=checkbox][name=__febe_allcheck][value]').change(function(){
    var all_check = $(this);
    all_check.parents('form').find('input[type=checkbox][name!=__febe_allcheck]').attr('checked', all_check.attr('checked'));
  });

  /**
   * ページ内移動をアニメーションする
   */
  $('a[href^=#]').click(function(){
    $('html,body').animate({
      scrollTop: $($(this.hash)).offset().top
    }, 'normal');

    return false;
  });

  /**
   * カート内数量を表示する
   */
  var cart_info = $('.cart-info');
  if (cart_info.length > 0) {
    $.ajax({
      url: '/cart/ajxOrderProductCnt',
      dataType: 'json',
      success: function(data) {
        cart_info.text('カート内: ' + data['count'] + '冊');
      }
    });
  }

  /**
   * 割引率を取得する
   */
  var product_ids = [];
  $('.product[data-product_id]').each(function(){
    product_ids[product_ids.length] = $(this).data('product_id');
  });
  $.ajax({
    url: '/api.php/product?ids='+product_ids.join(','),
    dataType: 'jsonp',
    success: function(response) {
      if (response['products']) {
        for (var i=0, len=response.products.length; i<len; i++) {
          var product = response.products[i];
          var html = product.discount_rate > 0 ? '<span class="original-price">'+product.original_price+'円 → </span><span class="sale-price">'+product.sale_price+'円</span><wbr /><br /><span class="discount-rate">（'+product.discount_rate+'％ OFF）</span>' : product.sale_price+'円';
          $('.product[data-product_id='+product.product_id+'] .price.changeable').html(html);
          $('div[data-product_id='+product.product_id+']').data('sale_price', product.sale_price);
        }
      }
    }
  });

  /**
   * Product Popup View
   */
  if (!jQuery.browser.msie) {
    var _product_popup_ = $('<div class="product-popup"></div>').appendTo('body');
    $('div[data-product_popup=1] img').hover(function() {
      // mouseover
      var that = $(this).parents('div[data-product_popup=1]');
      var offset = that.offset();
      var product_id = that.data('product_id'),
          title = that.data('title'),
          description = that.data('description'),
          image = that.data('image'),
          author = that.data('author'),
          ticket_usable = that.data('ticket_usable'),
          sale_price = that.data('sale_price');
      _product_popup_.html(
        '<p class="title"><a href="#">'+title+'</a></p>'
        + (author ? '<p class="author">著者: '+author+'</p>' : '')
        + (sale_price ?'<p class="price">'+sale_price+'円</p>' : '')
        + (ticket_usable ? '<p class="ticket"><img src="/images/product/ticket_usable_mini.jpg" /></p>' : '')
        + '<p class="description">'+description+'</p>'
      ).css({
        top: offset.top,
        left: offset.left
      }).show();
    }, function() {
      // mouseout
      _product_popup_.hide();
    });

    document.onmousemove = function(e) {
      try {
        mouse_x = (e ? e.pageX : document.body.scrollLeft + event.x);
        mouse_y = (e ? e.pageY : document.body.scrollTop + event.y);
        if (mouse_x > 650) {
          _product_popup_.css({left: mouse_x - 300, top: mouse_y + 10});
        } else {
          _product_popup_.css({left: mouse_x + 10, top: mouse_y - 100});
        }
      } catch (e) {}
    };
  }

});})(jQuery);

YMPParams = { displaystate: 3 }

