/**
 *  Moshimo common script definition.
 *    js/lib/Xenon.js
 * 
 *  Copyright (c) Moshimo Co.,Ltd.
 *    All rights reserved
 * 
 *  @auther     T.Mori
 *  @date       2007.06.15
 */
// {{{ Global constant definition.
var LF = '\n';
var CR = '\r';
var CRLF = '\r\n';
var TAB = '\t';
var EN_SPACE = ' ';
var EM_SPACE = '　';
var F_SLASH = '/';
var B_SLASH = '\\';
var HYPHEN = '-';
var DOT = '.';
var D_QUOT = '\"';
var S_QUOT = '\'';
var PIPE = '|';
// }}}

// {{{ Xenon constant definition.
var XENON_PROTOCOL = location.protocol;
var XENON_HOSTNAME = location.hostname;
var XENON_BASE_DIR = '/';
var XENON_BASE_URL = XENON_PROTOCOL + '//' + XENON_HOSTNAME + XENON_BASE_DIR;
var XENON_BASE_SSL_URL = 'https://' + XENON_HOSTNAME + XENON_BASE_DIR;
var XENON_BASE_NONSSL_URL = 'http://' + XENON_HOSTNAME + XENON_BASE_DIR;

var XENON_JS_DIRECTORY = 'js/lib/';
var XENON_JS_EXTENSION = '.js';

if (!MDS_HTML_FORM_ELEMENTS_FOCUS_BORDER_STYLE) {
  var MDS_HTML_FORM_ELEMENTS_FOCUS_BORDER_STYLE = 'solid 1px #2040ff';
}
if (!MDS_HTML_FORM_ELEMENTS_BLUR_BORDER_STYLE) {
  var MDS_HTML_FORM_ELEMENTS_BLUR_BORDER_STYLE = 'solid 1px #60a0ff';
}
if (!MDS_HTML_FORM_ELEMENTS_FOCUS_BACKGROUND_COLOR_STYLE) {
  var MDS_HTML_FORM_ELEMENTS_FOCUS_BACKGROUND_COLOR_STYLE = '#f0f8ff';
}
if (!MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE) {
  var MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE = '#ffffff';
}

if (!MDS_HTML_FORM_IGNORE_COLORING_TYPE) {
  var MDS_HTML_FORM_IGNORE_COLORING_TYPE = $A(['hidden', 'image', 'button', 'submit', 'reset', 'radio', 'checkbox']);
}

if (!MDS_HTML_FORM_ENABLE_COLORING_ELEMENT) {
  var MDS_HTML_FORM_ENABLE_COLORING_ELEMENT = $A(['input', 'select', 'textarea']);
}

var XENON_HTML_TOOLTIP_IMAGE_URL = XENON_PROTOCOL + '//' + XENON_HOSTNAME + XENON_BASE_DIR + 'images/tooltip/';

var XENON_DISABLE_FORM_COLORING = false;
var XENON_DISABLE_HEIGHT_ASSORT = false;
// }}}

// {{{ function $T
/**
 *  HTML 要素を取得する
 * 
 *  @param      String        __tag_name        取得する要素名
 *  @param      Integer       [__index]         取得するインデックス
 *                                              指定すると単体のオブジェクトを返す
 *  @access     public
 *  @return     mixed         Array: インデックス無指定, Element: インデックス指定
 */
function $T(__tag_name, __index) {
  if (__index || __index === 0) {
    return document.getElementsByTagName(__tag_name)[__index];
  }
  return $A(document.getElementsByTagName(__tag_name));
};
// }}}

// {{{ function $E
function $E(__form_name, __element_name) {
  var _form = document.forms[__form_name];
  var _return = null;
  if (__element_name && __element_name.indexOf("*") >= 0) {
    var _return = new Array;
    var _pattern = new RegExp(__element_name.gsub(/\[/, "\\[").gsub(/\]/, "\\]").gsub(/\*/, ".*"), 'g');
    for (var _i = 0; _i < _form.elements.length; _i++) {
      if (_form.elements[_i].name.match(_pattern)) {
        _return.push($(_form.elements[_i]));
      }
    }
    return $A(_return);
  } else if (__element_name) {
    return $(_form.elements[__element_name]);
  }
  return $(_form);
}
// }}}

// {{{ function window.getPageSizeX
window.getPageSizeX = function() {
  if (window.innerWidth) {
    return window.innerWidth;
  } else if (document.documentElement && document.documentElement.clientWidth != 0) {
    return document.documentElement.clientWidth;
  } else if (document.body) {
    return document.body.clientWidth;
  }
  return 0;
};
// }}}

// {{{ function window.getPageSizeY
window.getPageSizeY = function() {
  if (window.innerHeight) {
    return window.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight != 0) {
    return document.documentElement.clientHeight;
  } else if (document.body) {
    return document.body.clientHeight;
  }
  return 0;
};
// }}}

// {{{ function Xenon_formColoring
function Xenon_formColoring() {
  if (XENON_DISABLE_FORM_COLORING) {
    return;
  }
  var elements = $A($$(MDS_HTML_FORM_ENABLE_COLORING_ELEMENT.flatten()));
  elements.each(function(element) {
    if (MDS_HTML_FORM_IGNORE_COLORING_TYPE.indexOf(element.type) >= 0) {
      return;
    }
    if (!element.style.border) {
      element.style.border = MDS_HTML_FORM_ELEMENTS_BLUR_BORDER_STYLE;
    }
    if (!element.style.backgroundColor) {
      element.style.backgroundColor = MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE;
    }
    //if (element.type == "select-one" && element.offsetWidth) {
    //  element.style.width = (element.offsetWidth + 5) + (!Prototype.Browser.IE ? 'px' : '');
    //}
    if (element.type == "password") {
      element.value = "";
    }
    element.focused = false;
    Event.observe(element, 'mouseover', (function() {
      this.style.border = MDS_HTML_FORM_ELEMENTS_FOCUS_BORDER_STYLE;
      if (!this.focused) {
        this.style.backgroundColor = MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE;
      }
    }).bind(element), false);
    Event.observe(element, 'mouseout', (function() {
      this.style.border = MDS_HTML_FORM_ELEMENTS_BLUR_BORDER_STYLE;
      if (!this.focused) {
        this.style.backgroundColor = MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE;
      }
    }).bind(element), false);
    Event.observe(element, 'focus', (function() {
      this.style.border = MDS_HTML_FORM_ELEMENTS_FOCUS_BORDER_STYLE;
      this.style.backgroundColor = MDS_HTML_FORM_ELEMENTS_FOCUS_BACKGROUND_COLOR_STYLE;
      if (this.type == "select-one") {
        this.select();
      }
      this.focused = true;
    }).bind(element), false);
    Event.observe(element, 'blur', (function() {
      this.style.border = MDS_HTML_FORM_ELEMENTS_BLUR_BORDER_STYLE;
      this.style.backgroundColor = MDS_HTML_FORM_ELEMENTS_BLUR_BACKGROUND_COLOR_STYLE;
      this.focused = false;
    }).bind(element), false);
  });
}
// }}}

// {{{ function Xenon_anchorBlank
function Xenon_anchorBlank() {
  var anchors = $A($$('a._blank'));
  anchors.each(function(element) {
    element.target = "_blank";
  });
}
// }}}

// {{{ function Xenon_imageSwap
function Xenon_imageSwap() {
  var images = $A($$('img._swap'));
  images.each(function(element) {
    Event.observe(element, 'mouseover', (function() {
      this.src = this.src.gsub(/([a-zA-Z0-9\/._-]+)(\.[a-z]{3,4})/, "#{1}_over#{2}");
    }).bind(element), false);
    Event.observe(element, 'mouseout', (function() {
      this.src = this.src.gsub(/([a-zA-Z0-9\/._-]+)_over(\.[a-z]{3,4})/, "#{1}#{2}");
    }).bind(element), false);
  });
}
// }}}

// {{{ function Xenon_heightAssort
function Xenon_heightAssort() {
  if (XENON_DISABLE_HEIGHT_ASSORT) {
    return;
  }
  var className = "_assort";
  var parentClassName = "_assort_p";
  var reg = new RegExp(className + "_g_([a-zA-Z0-9-_]+)", "i");
  var objCN = new Array();
  var objAll = document.getElementsByTagName ? document.getElementsByTagName("*") : document.all;
  for (var i = 0; i < objAll.length; i++) {
    var eltClass = objAll[i].className.split(/\s+/);
    for (var j = 0; j < eltClass.length; j++) {
      if (eltClass[j] == className) {
        if (!objCN["main_CN"]) {
          objCN["main_CN"] = new Array();
        }
        objCN["main_CN"].push(objAll[i]);
        break;
      } else if (eltClass[j] == parentClassName) {
        if (!objCN["parent_CN"]) {
          objCN["parent_CN"] = new Array();
        }
        objCN["parent_CN"].push(objAll[i]);
        break;
      } else if (eltClass[j].match(reg)) {
        var OCN = eltClass[j].match(reg);
        if (!objCN[OCN]) {
          objCN[OCN]=new Array();
        }
        objCN[OCN].push(objAll[i]);
        break;
      }
    }
  }

  var e = document.createElement("div");
  var s = document.createTextNode("S");
  e.appendChild(s);
  e.style.visibility = "hidden";
  e.style.position = "absolute";
  e.style.top = "0";
  document.body.appendChild(e);
  var defHeight = e.offsetHeight;

  changeBoxSize = function(){
    for (var key in objCN){
      if (objCN.hasOwnProperty(key)) {
        if (key == "parent_CN"){
          for (var i = 0; i < objCN[key].length; i++){
            var max_height=0;
            var CCN = objCN[key][i].childNodes;
            for (var j = 0; j < CCN.length; j++) {
              if (CCN[j] && CCN[j].nodeType == 1) {
                CCN[j].style.height="auto";
                max_height = max_height > CCN[j].offsetHeight ? max_height : CCN[j].offsetHeight;
              }
            }
            for (var j = 0; j < CCN.length; j++) {
              if (CCN[j].style) {
                CCN[j].style.height = max_height + (!Prototype.Browser.IE ? 'px' : '');
              }
            }
          }
        } else {
          var max_height=0;
          for (var i = 0; i < objCN[key].length; i++) {
            objCN[key][i].style.height="auto";
            max_height = max_height > objCN[key][i].offsetHeight ? max_height : objCN[key][i].offsetHeight;
          }
          for (var i = 0; i < objCN[key].length; i++){
            objCN[key][i].style.height = max_height + (!Prototype.Browser.IE ? 'px' : '');
          }
        }
      }
    }
  };

  checkBoxSize = function() {
    if (defHeight != e.offsetHeight) {
      changeBoxSize();
      defHeight= e.offsetHeight;
    }
  };
  changeBoxSize();
  setInterval(checkBoxSize, 1000);
  
}
// }}}

// {{{ function Xenon_setTooltip
function Xenon_setTooltip(__id, __data) {
  var div = document.createElement('div');
  (function() {
    this.id = 'tooltip';
    this.style.position = 'absolute';
    this.style.display = 'none';
    this.innerHTML =
      '<table style="border-collapse: collapse;">'
      + '<thead>'
      + '<tr>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_lt.gif\'); background-repeat: no-repeat; background-position: right; width: 6px; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_ct.gif\'); background-repeat: repeat-x; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_rt.gif\'); background-repeat: no-repeat; width: 6px; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '</tr>'
      + '</thead>'
      + '<tbody>'
      + '<tr>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_lm.gif\'); background-repeat: repeat-y; background-position: right; width: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_cm.gif\'); background-repeat: repeat; text-align: left;" nowrap>'
      + __data
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_rm.gif\'); background-repeat: repeat-y; width: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '</tr>'
      + '</tbody>'
      + '<tfoot>'
      + '<tr>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_lb.gif\'); background-repeat: no-repeat; background-position: right; width: 6px; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_cb.gif\'); background-repeat: repeat-x; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '<td style="background-image: url(\'' + XENON_HTML_TOOLTIP_IMAGE_URL + 'tooltip_rb.gif\'); background-repeat: no-repeat; width: 6px; height: 6px; font-size: 1px; line-height: 1px;">'
      + '</td>'
      + '</tr>'
      + '</tfoot>'
      + '</table>';
    $T('body', 0).style.position = 'relative';
    $T('body', 0).appendChild(this);
    Event.observe(__id, 'mouseover', (function(__event) {
      this.style.display = 'block';
      this.style.position = 'absolute';
      if (Event.pointerX(__event) + this.offsetWidth > window.getPageSizeX() - 20) {
        this.style.left = (Event.pointerX(__event) - this.offsetWidth - 5) + (!Prototype.Browser.IE ? 'px' : '');
      } else {
        this.style.left = (Event.pointerX(__event) + 5) + (!Prototype.Browser.IE ? 'px' : '');
      }
      if (Event.pointerY(__event) + this.offsetHeight > window.getPageSizeY() - 20) {
        this.style.top = (Event.pointerY(__event) - this.offsetHeight - 5) + (!Prototype.Browser.IE ? 'px' : '');
      } else {
        this.style.top = (Event.pointerY(__event) + 5) + (!Prototype.Browser.IE ? 'px' : '');
      }
      this.style.zIndex = '999';
      this.alt = '';
    }).bind(this), false);
    Event.observe(__id, 'mousemove', (function(__event) {
      this.style.display = 'block';
      this.style.position = 'absolute';
      if (Event.pointerX(__event) + this.offsetWidth > window.getPageSizeX() - 20) {
        this.style.left = (Event.pointerX(__event) - this.offsetWidth - 5) + (!Prototype.Browser.IE ? 'px' : '');
      } else {
        this.style.left = (Event.pointerX(__event) + 5) + (!Prototype.Browser.IE ? 'px' : '');
      }
      if (Event.pointerY(__event) + this.offsetHeight > window.getPageSizeY() - 20) {
        this.style.top = (Event.pointerY(__event) - this.offsetHeight - 5) + (!Prototype.Browser.IE ? 'px' : '');
      } else {
        this.style.top = (Event.pointerY(__event) + 5) + (!Prototype.Browser.IE ? 'px' : '');
      }
      this.style.zIndex = '999';
      this.alt = '';
    }).bind(this), false);
    Event.observe(__id, 'mouseout', (function() {
      this.style.display = 'none';
    }).bind(this), false);
  }).bind(div)();
}
// }}}

// {{{ function Xenon_autoFocus
function Xenon_autoFocus() {
  if (!$E(0)) {
    return;
  }
  var element = $E(0).getElementsByClassName('_focus');
  if (typeof element == "object" && typeof element[0] != "undefined") {
    element[0].focus();
  }
}
// }}}

// {{{ function Xenon_commify
function Xenon_commify(price) {
  price = Math.floor(price);
  price = "" + price;
  var len = price.length;
  var price_new = "";
  var s = "";
  if (len >= 4) {
    for (var i = 0; i < len; i++){
      s = price.substring(i,i+1);
      if (i > 0 && (len - i) % 3 == 0){
        price_new = price_new + "," + s;
      } else {
        price_new = price_new + s;
      }
    }
  } else {
    price_new = price;
  }
  return price_new;
}

window.commify = Xenon_commify;
// }}}

// {{{ Onload functions definition.
Event.observe(window, 'load', Xenon_formColoring, false);
Event.observe(window, 'load', Xenon_anchorBlank, false);
Event.observe(window, 'load', Xenon_imageSwap, false);
Event.observe(window, 'load', Xenon_autoFocus, false);
// }}}

// {{{ Global variables definition.
var __related_articles = new Array;
// }}}

/**
 * スクリプトの実行速度をベンチするためのクラス
 *
 * @author T.Mori <t.mori@moshimo.co.jp>
 * @package Mds
 * @access public
 */
var Xenon_Timer = Class.create(
  {

    // {{{ begin
    /**
     * 開始時のミリ秒を記録
     *
     * @param String _name 名称
     * @param String _memo メモ
     */
    begin: function(_name, _memo) {
      var _date = new Date;
      var _begin = 0;
      if (Prototype.Browser.IE) {
        _begin = _date.getTime() + _date.getMilliseconds();
      } else {
        _begin = _date.getTime();
      }
      this.times.push({
        name: _name,
        begin: _begin,
        finish: 0,
        level: ++this.level,
        memo: _memo
      });
    },
    // }}}

    // {{{ finish
    /**
     * 終了時のミリ秒を記録
     *
     * @param String _name 名称
     */
    finish: function(_name) {
      var _date = new Date;
      var _finish = 0;
      if (Prototype.Browser.IE) {
        _finish = _date.getTime() + _date.getMilliseconds();
      } else {
        _finish = _date.getTime();
      }
      var _time = this.times.pop();
      _time.finish = _finish;
      this.stack.unshift(_time);
      this.level--;
    },
    // }}}

    // {{{ finalize
    /**
     * 終了処理
     */
    finalize: function() {
      this.text = "";
      this.stack.reverse();
      this.stack.each(
        function(_time) {
          var _process_time = _time.finish - _time.begin;
          if (_process_time < 0) {
            _process_time = 1000 + _process_time;
          }
          var _text = _time.name + (_time.memo ? " (" + _time.memo + ")" : "") + ": " + _process_time + "ms";
          if (Prototype.Browser.IE) {
            this.text += "&gt;".times(_time.level) + "&nbsp;" + _text + "<br />\n";
          } else {
            console.info(">".times(_time.level) + " " + _text);
          }
        },
        this
      );
      if (Prototype.Browser.IE) {
        var _p = new Element('p');
        _p.setStyle(
          {
            textAlign: "left",
            fontFamily: "monospace",
            position: "absolute",
            top: 0,
            left: 0,
            width: "400px",
            backgroundColor: "#aaaaaa",
            color: "#000000",
            filter: "alpha(opacity=60)"
          }
        );
        _p.update(this.text);
        $$('body')[0].insert({bottom: _p});
      }
    },
    // }}}

    // {{{ initialize
    /**
     * コンストラクタ
     */
    initialize: function() {
      this.stack = new Array;
      this.times = new Array;
      this.level = 0;
    }
    // }}}

  }
);
var x_timer = new Xenon_Timer;

var Xenon_Progress = Class.create(
  {

    // {{{ finish
    /**
     * 終了処理
     */
    finish: function() {
      $('x-progress-iframe').remove();
      $('x-progress-div').remove();
      $('x-progress-main').remove();
    },
    // }}}

    // {{{ start
    /**
     * 処理を開始する
     */
    start: function() {
      var _iframe = new Element(
        'iframe',
        {
          id: "x-progress-iframe",
          src: "/images/spacer.gif",
          frameborder: "0"
        }
      );
      var _div = new Element(
        'div',
        {
          id: "x-progress-div"
        }
      );
      var _div_main = new Element(
        'div',
        {
          id: "x-progress-main"
        }
      );
      var _p = new Element(
        'p',
        {
          id: "x-progress-bar"
        }
      );
      var _text = new Element(
        'p',
        {
          id: "x-progress-text"
        }
      );
      var _img = new Element(
        'img',
        {
          src: '/images/logo_moshimo.gif',
          width: '137',
          height: '47'
        }
      );
      var _top = document.viewport.getScrollOffsets().top + "px";
      var _left = document.viewport.getScrollOffsets().left + "px";
      var _width = document.viewport.getWidth() + "px";
      var _height = document.viewport.getHeight() + "px";
      var _main_top = ((document.viewport.getHeight() / 2) - 50) + "px";
      var _main_left = ((document.viewport.getWidth() / 2) - 150) + "px";
      _top = "0";
      _left = "0";
      // {{{ iframe style
      _iframe.setStyle(
        {
          width: "100%",
          height: "100%",
          border: "none",
          position: "absolute",
          zIndex: 10,
          backgroundColor: "transparent",
          opacity: 0,
          "-moz-opacity": 0,
          filter: "alpha(opacity=0)",
          top: _top,
          left: _left
        }
      );
      // }}}
      // {{{ div style
      _div.setStyle(
        {
          width: "100%",
          height: _height,
          position: "absolute",
          backgroundColor: "#000000",
          opacity: 0.5,
          "-moz-opacity": 0.5,
          filter: "alpha(opacity=50)",
          zIndex: 20,
          top: _top,
          left: _left
        }
      );
      // }}}
      // {{{ main div style
      _div_main.setStyle(
        {
          position: "absolute",
          zIndex: 30,
          width: (this.size ? this.size : 300) + "px",
          height: "120px",
          verticalAlign: "middle",
          textAlign: "center",
          border: "solid 1px #000000",
          backgroundColor: "#ffffff",
          top: _main_top,
          left: _main_left
        }
      );
      // }}}
      // {{{ progress bar
      _p.setStyle(
        {
          width: (this.size ? this.size : 300) + "px",
          height: "70px",
          lineHeight: "16px",
          fontSize: "12px",
          verticalAlign: "middle",
          textAlign: "center",
          backgroundColor: "#ffffff"
        }
      );
      _img.setStyle(
        {
          margin: "10px auto 10px 0"
        }
      );
      _text.setStyle(
        {
          height: '50px',
          textAlign: "center",
          color: "#0000ff",
          margin: "0 auto 10px 0"
        }
      );
      // }}}

      _p.insert({bottom: _img});
      _text.update("ただいまページ読み込み中です。<br />数秒お待ち下さい。");
      _div_main.insert({bottom: _p});
      _div_main.insert({bottom: _text});
      $$('body')[0].insert({top: _div})
      $$('body')[0].insert({top: _iframe})
      $$('body')[0].insert({top: _div_main})
    },
    // }}}

    // {{{ progress
    /**
     * 進捗させる
     *
     * @param Boolean _force_max 強制 100% フラグ
     */
    progress: function(_force_max) {
      if (this.index >= this.count) {
        return;
      }
      this.index++;
      var _size = this.size || 200;
      if (_force_max) {
        this.index = this.count;
      }
      var _width = Math.floor(200 * (this.index / this.count));
      if ($('x-progress-bar')) {
        $('x-progress-bar').setStyle({width: _width + "px"});
      }
    },
    // }}}

    // {{{ initialize
    /**
     * コンストラクタ
     */
    initialize: function() {
      this.index = 0;
    }
    // }}}

  }
);

var x_progress = new Xenon_Progress();

