/**
 * js/shop/common.js
 *
 * @author T.Mori
 * @package Mds
 * @version $Id$
 */

XENON_DISABLE_FORM_COLORING = true;

/**
 * ショップオーナーページのライブラリ
 *
 * @author T.Mori
 * @package Mds
 */
var Mds_Shop = {

  /**
   * グローバルナビゲーション用クラス
   *
   * @author T.Mori
   * @package Mds_Shop
   */
  HeaderNavi: Class.create(
    {

      /** @var Number 開く・閉じる処理時間 */
      default_duration: 0.2,

      /** @var Number 遅延隠しをする際の秒数 */
      default_hide_delay: 1.0,

      /**
       * メニューを表示する
       */
      show: function() {
        if (!Object.isUndefined(this.timer)) {
          clearTimeout(this.timer);
          this.timer = undefined;
        }
        if (this.visible || this.during) {
          return;
        }
        this.during = true;
        var effects = [];
        effects.push(
          Effect.BlindDown(
            this.e_sub_menu,
            {
              duration: this.default_duration,
              afterFinishInternal: function() {
                this.during = false;
                this.visible = true;
              }.bind(this)
            }
          )
        );
        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          effects.push(
            Effect.BlindDown(
              this.e_iframe,
              {
                duration: this.default_duration
              }
            )
          );
        }
        // }}}
        new Effect.Parallel(effects, {delay: 0, sync: true});
      },

      /**
       * メニューを隠す
       */
      hide: function() {
        if (!this.visible || this.during) {
          return;
        }
        this.during = true;
        var effects = [];
        effects.push(
          Effect.BlindUp(
            this.e_sub_menu,
            {
              duration: this.default_duration,
              afterFinishInternal: function() {
                if (!Object.isUndefined(this.timer)) {
                  clearTimeout(this.timer);
                  this.timer = undefined;
                }
                this.e_sub_menu.hide();
                this.during = false;
                this.visible = false;
              }.bind(this)
            }
          )
        );
        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          effects.push(
            Effect.BlindUp(
              this.e_iframe,
              {
                duration: this.default_duration,
                afterFinishInternal: function() {
                  this.e_iframe.hide();
                }.bind(this)
              }
            )
          );
        }
        // }}}
        new Effect.Parallel(effects, {delay: 0, sync: true});
      },

      /**
       * 遅延させつつメニューを隠す
       */
      hideDelay: function() {
        this.timer = setTimeout(this.hide.bind(this), Math.round(this.default_hide_delay * 1000, 1));
      },

      /**
       * メニュー表示をトグルさせる
       */
      toggle: function() {
        if (this.visible) {
          this.hide();
        } else {
          this.show();
        }
      },

      /**
       * コンストラクタ
       */
      initialize: function(index) {
        this.visible = false;
        this.timer = undefined;
        this.$element = $('header-navi-' + index);
        this.$element.observe('mouseout', this.hideDelay.bind(this));
        this.e_sub_menu = $('header-navi-sub-' + index);
        this.e_sub_menu.observe('mouseover', this.show.bind(this));
        //this.$element.observe('mouseover', this.show.bind(this));
        $('header-navi-trigger-' + index).observe('click', this.toggle.bind(this));
        $('header-navi-sub-footer-' + index).observe('click', this.hide.bind(this));

        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          this.e_iframe = new Element('iframe', {frameborder: 0, src: 'javascript: false;'});
          var e_dummy = this.e_sub_menu.cloneNode(true);
          e_dummy.setStyle({position: 'absolute', top: 0, left: 0});
          e_dummy.setOpacity(0);
          this.$element.insert({bottom: e_dummy});
          width = e_dummy.getWidth();
          height = e_dummy.getHeight();
          e_dummy.remove();
          this.e_iframe.setStyle(
            {
              width     : '190px',
              height    : height + 'px',
              position  : 'absolute',
              color     : '#ffffff',
              top       : '31px',
              left      : 0,
              zIndex    : 100,
              padding   : 0,
              margin    : 0,
              border    : 'none'
            }
          );
          this.e_iframe.hide();
          this.$element.insert({bottom: this.e_iframe});
        }
        // }}}
      }

    }
  ),

  /**
   * 左ナビ特集バナー関連クラス
   *
   * @author T.Mori
   * @package Mds_Shop
   */
  LeftNaviFeature: Class.create(
    {

      /**
       * 一つ分のバナー要素を最上部に追加して全体を一つ分スライドさせる
       */
      slide: function() {
        this.current_index++;
        if (this.current_index >= this.list.length) {
          this.current_index = 0;
        }
        var p = this._create(this.list[this.current_index]);
        p.setStyle({top: "-90px"});
        this.$element.insert({top: p});
        var effect_list = [];
        this.$element.select('p').each(
          function(e_p) {
            effect_list.push(new Effect.Move(e_p, {sync: true, y: 90, mode: 'relative'}));
          }.bind(this)
        );
        new Effect.Parallel(
          effect_list,
          {
            duration: 1.0,
            afterFinish: function() {
              this.$element.down('p', this.$element.select('p').length - 1).remove();
            }.bind(this)
          }
        );
      },

      /**
       * くるくるを開始する
       */
      start: function() {
        if (!this.timer) {
          this.timer = setInterval(this.slide.bind(this), 3000);
        }
      },

      /**
       * くるくるを止める
       */
      stop: function() {
        if (this.timer) {
          clearInterval(this.timer);
          this.timer = undefined;
        }
      },

      /**
       * 一つ分のバナー要素 p > a > img を構築
       *
       * @param Object data 構築用データ
       * @return Element 構築した p タグ
       */
      _create: function(data) {
        var p, a, img;
        p = new Element('p');
        a = new Element('a', {href: data.uri});
        img = new Element('img', {src: data.image, width: 192, height: 80});
        a.insert({bottom: img});
        p.insert({bottom: a});
        return p;
      },

      /**
       * コンストラクタ
       */
      initialize: function() {
        if (!$('left-navi-feature')) {
          return;
        }
        this.list = _variables.left_navi_feature;
        this.$element = $('left-navi-feature');
        this.current_index = 0;
        for (var i = 0; i < 4; i++) {
          this.current_index = i;
          var p = this._create(this.list[this.current_index]);
          p.setStyle({top: (90 * (3 - i)) + 'px'});
          this.$element.insert({top: p});
        }
        this.start();
        this.$element.observe('mouseover', this.stop.bind(this));
        this.$element.observe('mouseout', this.start.bind(this));
      }

    }
  ),

  /**
   * 詳細検索用クラス
   *
   * @author T.Mori
   * @package Mds_Shop
   */
  DetailSearch: Class.create(
    {

      /** @var Number 開く・閉じる処理時間 */
      default_duration: 0.2,

      /**
       * 詳細検索窓を表示する
       */
      show: function() {
        if (this.during) {
          return;
        }
        this.during = true;
        var effects = [];
        effects.push(
          Effect.BlindDown(
            this.$element,
            {
              duration: this.default_duration,
              afterFinishInternal: function() {
                this.during = false;
                this.visible = true;
              }.bind(this)
            }
          )
        );
        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          effects.push(
            Effect.BlindDown(
              this.e_iframe,
              {
                duration: this.default_duration
              }
            )
          );
        }
        // }}}
        new Effect.Parallel(effects, {delay: 0, sync: true});
      },

      /**
       * 詳細検索窓を隠す
       */
      hide: function() {
        if (this.during) {
          return;
        }
        this.during = true;
        var effects = [];
        effects.push(
          Effect.BlindUp(
            this.$element,
            {
              duration: this.default_duration,
              afterFinishInternal: function() {
                this.$element.hide();
                this.during = false;
                this.visible = false;
              }.bind(this)
            }
          )
        );
        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          effects.push(
            Effect.BlindUp(
              this.e_iframe,
              {
                duration: this.default_duration,
                afterFinishInternal: function() {
                  this.e_iframe.hide();
                }.bind(this)
              }
            )
          );
        }
        // }}}
        new Effect.Parallel(effects, {delay: 0, sync: true});
      },

      /**
       * 詳細検索窓の表示をトグルする
       */
      toggle: function() {
        if (this.during) {
          return;
        }
        if (this.visible) {
          this.hide.bind(this)();
        } else {
          this.show.bind(this)();
        }
      },

      /**
       * 送信する
       */
      submit: function(event) {
        this.$element.up('form').submit();
      },

      /**
       * フォームの内容を初期化する
       */
      clear: function() {
        var e_form = this.$element.up('form');
        if (e_form.down('input[name="tags"]')) {
          e_form.down('input[name="tags"]').clear();
        }
        if (e_form.down('p.tags')) {
          e_form.down('p.tags').update('');
        }
        e_form.down('input[name="except_words"]').clear();
        e_form.down('input[name="date_from"]').clear();
        e_form.down('input[name="date_to"]').clear();
        e_form.down('input[name="default_profit_sum_from"]').clear();
        e_form.down('input[name="default_profit_sum_to"]').clear();
        e_form.down('input[name="default_sales_sum_from"]').clear();
        e_form.down('input[name="default_sales_sum_to"]').clear();
        e_form.down('input[name="minimum_sum_from"]').clear();
        e_form.down('input[name="minimum_sum_to"]').clear();
        e_form.down('input[name="stock_status"]').clear();
        e_form.down('input[name="stock_status"]').setValue('');
        e_form.select('input[name^="options"]').each(Form.Element.clear);
        e_form.down('select[name="article_category_code"]').setValue('');
        e_form.down('select[name="target"]').setValue('');
        e_form.down('select[name="field"]').setValue('full');
        e_form.down('select[name="order"]').setValue('word');
        e_form.down('select[name="limit"]').setValue('10');
      },

      /**
       * コンストラクタ
       *
       * @param Element $element 詳細検索要素
       */
      initialize: function($element) {
        this.visible = false;
        this.during = false;
        this.$element = $($element);
        if (!this.$element) {
          return;
        }
        if ($(this.$element.identify() + '-trigger')) {
          $(this.$element.identify() + '-trigger').observe('click', this.toggle.bind(this));
        }
        if (this.$element.down('p.close a')) {
          this.$element.down('p.close a').observe('click', this.hide.bind(this));
        }
        //this.$element.down('p.search-button a').observe('click', this.submit.bindAsEventListener(this));
        this.$element.down('p.clear-button a').observe('click', this.clear.bind(this));

        // {{{ IE 対応
        if (Prototype.Browser.IE) {
          this.e_iframe = new Element('iframe', {frameborder: 0, src: 'javascript: false;'});
          this.$element.setStyle({zIndex: 91});
          var e_dummy = this.$element.cloneNode(true);
          e_dummy.setStyle({position: 'absolute', top: 0, left: 0});
          e_dummy.setOpacity(0);
          this.$element.insert({after: e_dummy});
          width = e_dummy.getWidth();
          height = e_dummy.getHeight();
          e_dummy.remove();
          this.e_iframe.setStyle(
            {
              width     : '433px',
              height    : (height - 11) + 'px',
              position  : 'absolute',
              color     : '#ffffff',
              top       : '41px',
              right     : '15px',
              zIndex    : 90,
              padding   : 0,
              margin    : 0,
              border    : 'none'
            }
          );
          this.e_iframe.hide();
          this.$element.insert({after: this.e_iframe});
        }
        // }}}
      }

    }
  ),

  /**
   * ご意見投稿用クラス
   *
   * @author T.Mori
   * @package Mds_Shop
   */
  Opinion: Class.create(
    {

      /**
       * 送信する
       */
      submit: function() {
        var result = this.check();
        if (result) {
          this.e_form.down('div.mds-button div.mds-button-content').update('送信中');
          mds.form.request(
            this.e_form,
            function (response) {
              var result = response.responseJSON;
              if (!result) {
                this.addError('エラーが発生しました');
                this.addError('時間を置いて再度お試し下さい');
                this.e_form.down('div.mds-button div.mds-button-content').update('送信する');
                this.e_form.down('div.mds-button').mds_button.enable();
              } else {
                this.complete();
              }
            }.bind(this)
          );
        } else {
          this.e_form.down('div.mds-button').mds_button.enable();
        }
      },

      /**
       * JavaScript 側で簡易なバリデーションを行う
       *
       * @return Boolean バリデーション結果
       */
      check: function() {
        var result = true;
        this.resetError();
        if (!this.opinion.gsub(/ |　|\r|\n/, '')) {
          this.addError('ご意見を入力して下さい');
          result = false;
        }
        return result;
      },

      /**
       * 処理が終了したことを表示する
       */
      complete: function() {
        this.e_form.select('.opinion-bg .form-area *').each(Element.remove);
        var e_div = new Element('div');
        var e_p = undefined;
        e_div.addClassName('complete');
        e_p = new Element('p');
        e_p.addClassName('red');
        e_p.update('ご意見を確かに承りました。');
        e_div.insert({bottom: e_p});
        e_p = new Element('p');
        e_p.addClassName('red');
        e_p.update('誠にありがとうございました。');
        e_div.insert({bottom: e_p});
        e_p = new Element('p');
        e_p.addClassName('red');
        e_p.update('個々のご意見にはお返事できませんが何卒ご了承下さい。');
        e_div.insert({bottom: e_p});
        this.e_form.down('.opinion-bg .form-area').insert({bottom: e_div});
      },

      /**
       * エラーメッセージを初期化する
       */
      resetError: function() {
        this.e_form.down('.error').select('p').each(Element.remove);
      },

      /**
       * エラーを一件表示する
       *
       * @param String message エラーメッセージ
       */
      addError: function(message) {
        var e_p = new Element('p');
        e_p.addClassName('red');
        e_p.addClassName('bold');
        e_p.update(message);
        this.e_form.down('.error').insert({bottom: e_p});
      },

      /**
       * コンストラクタ
       */
      initialize: function() {
        this.e_form = $('opinion');
        this.opinion = (new String(this.e_form.down('textarea').getValue()));
      }

    }
  ),

  /**
   * フッタの位置を再調整する
   * (IE 専用)
   */
  FooterReposition: function() {
    if (Prototype.Browser.IE && $('footer')) {
      $('footer').setStyle(
        {
          position: 'absolute',
          bottom: '1px'
        }
      );
      $('footer').setStyle(
        {
          position: 'absolute',
          bottom: 0
        }
      );
    }
  },

  /**
   * 検索窓のグレーメッセージを変更する
   *
   * @param Element e_element セレクトボックス要素
   * @param Element element 入力フィールド要素
   */
  ChangeInduce: function(e_select, element) {
    e_select = $(e_select);
    var article_category_code = e_select.getValue();
    var article_category_name = e_select.down('[value="' + article_category_code + '"]').innerHTML;
    var induce_message = '';
    if (article_category_code) {
      induce_message = article_category_name + 'カテゴリから検索';
    } else {
      induce_message = '検索キーワードを入力してください';
    }
    if (!$(element).getValue() || $(element).getValue() == $(element).mds_induce.induce_message) {
      $(element).setValue(induce_message);
    }
    if ($(element).mds_induce) {
      $(element).mds_induce.induce_message = induce_message;
    }
  }

};

Event.observe(
  window,
  'load',
  function() {
    new Mds_Shop.HeaderNavi(2);
    new Mds_Shop.HeaderNavi(3);
    new Mds_Shop.HeaderNavi(4);
    new Mds_Shop.HeaderNavi(5);
    new Mds_Shop.DetailSearch('detail-search');
    new Mds_Shop.LeftNaviFeature();
  }
);

/**
 * サイトURL登録
 * 
 * @param String $form_name フォーム要素名
 * @access public
 * @return void
 */
function siteEntry(form_name) {
  $(form_name).down('div[id=message]').update("");
  var shop_id = $E(form_name, 'shop_id').value;
  var site_urls = $E(form_name, 'site_urls').value;
  if (shop_id && site_urls) {
    new Ajax.Request(
      '/shop/support/complianceshop/siteEntry'
      , {
        method: 'get'
        , onSuccess: function (response) {
          var result = response.responseJSON;
          if (result.result == "failure") {
            var error_message = '';
            var error_count = 0;
            result.errors.each(
              function(error) {
                error_count++;
                if (error_count > 1) {
                  error_message = error_message + "<br >";
                }
                error_message = error_message + error;
              }
            );
            $(form_name).down('div[id=message]').update("<p>" + error_message + "</p>");
          } else if (result.result == "success") {
            $E(form_name, 'site_urls').value = "";
            $(form_name).down('div[id=message]').update("<p>修正対応のご連絡ありがとうございました。修正内容を確認させていただきます。</p>");
          }
        }
        , parameters: {
          shop_id: shop_id,
          site_urls: site_urls
        }
      }
    );
  } else {
    return;
  }
}

