// var divHelper = Class.create();
// divHelper.prototype = {
//   initialize: function(target, c, w) {
//     var elem = target;
//     if (typeof(target) == 'string') {
//       elem = $(target);
//     }
//     this.element = elem;
//     this.id = 'divhelper';
//     this.helper = $(this.id);
//     this.helpmarginleft = 4;
//     this.helpmarginbottom = 8;
//     if (c == undefined) c = 'balloon2';
//     if (w == undefined) w = '400px';
//     this.classname = c;
//     this.width = w;
//     if (this.helper == undefined) {
//       this.helper = document.createElement("div");
//       this.helper.id = this.id;
//       this.helper.className = this.classname;
//       if (this.width != undefined)
//         this.helper.style.width = this.width;
//       this.helper.className = this.classname;
//       document.body.appendChild(this.helper);
//     }
//   },
//   show: function(msg) {
//     this.helper.innerHTML = msg;
//     
//     var helpdim = Element.getDimensions(this.helper);
//     var elmdim = Element.getDimensions(this.element);
//     var elmpos = Position.positionedOffset(this.element);
//     
//     var helpleft = elmpos[0] + this.helpmarginleft;
//     var helptop = elmpos[1] + elmdim.height + this.helpmarginbottom;
//     this.helper.style.left = helpleft+'px';
//     this.helper.style.top  = helptop +'px';
//     Element.show(this.helper);
//   },
//   hide: function() {
//     Element.hide(this.helper);
//   }
// };


/**
 * DropDownMenu for global navi
 * Powered by hisato http://chibinowa.net/
 * http://sjam.chibinowa.net/eid/162
 */
var DropDownMenu = {
  open_sleep: 100,
  close_sleep: 500,
  timer: null,
  active_oid: null,
  open: function(target_id)
  {
    if (this.timer) {
      if (this.active_oid == target_id)
        clearTimeout(this.timer);
      else
        this._close();
    }
    this.active_oid = target_id;
    this.timer = setTimeout("DropDownMenu._open();", this.open_sleep);
    //Event.observe(document.documentElement, "click", DropDownMenu._close, true);
    $(document.documentElement).bind("click", DropDownMenu._close);
  },
  close: function()
  {
    if (this.timer)
      clearTimeout(this.timer);
    this.timer = setTimeout("DropDownMenu._close();", this.close_sleep);
  },
  _open: function()
  {
    var obj = document.getElementById(this.active_oid);
    obj.style.visibility = "visible";
  },
  _close: function()
  {
    document.getElementById(DropDownMenu.active_oid).style.visibility = "hidden";
    //Event.stopObserving(document.documentElement, "click", DropDownMenu._close, true);
    $(document.documentElement).unbind("click");
    clearTimeout(DropDownMenu.timer);
    delete DropDownMenu.timer;
  }

};


function addComment(f) {
  if(!confirm('コメントを投稿しますか？'))
    return false;
  var urlc = '/article/parts/comment';
  var article_id = f.article_id.value;
  var comment = encodeURIComponent(f.comment.value);
  var is_member = f.is_member.value;
  var name = encodeURIComponent(f.name.value);
  var title_icon = '';
  for(var i=0;i< f.title_icon.length;i++) {
    var r = f.title_icon[i];
    if (r.checked) {
      title_icon = r.value;
    }
  }
  var fdata = 'comment=' + comment  + '&article_id=' + article_id +
        '&is_member=' + is_member + '&name=' + name + '&cmt_title_icon=' + title_icon;
  var id = 'id=' + article_id + '&rand=' + Math.random();;
//  new Ajax.Request(urlc, {
//    method: 'post', 
//    parameters: fdata, 
//    onComplete: function(r) {
//      var res = r.responseText;
//      if (res ==''){
//        var objAjax = new Ajax.Updater( 'comment', urlc, {method: 'get', parameters: id, asynchronous: 1 });
//        alert('コメントありがとうございました。');
//      }else{
//        alert('コメント登録に失敗しました');
//      }
//    }
//  });
  jQuery.ajax({
    type: "POST",
    url: urlc,
    data: fdata,
    success: function(res){
      if (res ==''){
        alert('コメントありがとうございました。');
      }else{
        alert('コメント登録に失敗しました');
      }
    }
  });
  return false;
}


function getComment() {
  var url ;
  var id = '';
  var status = '';
  urls = '/article/parts/comment';
  var divcmt = document.getElementById('comment');
  if (divcmt.style.display == "block"){
    divcmt.style.display = "none";
    status = "none";
    return;
  }else{
    status = "block";
  }
  divcmt.style.display = "block";
  id = 'id=' + get_location_pathname2article_id();
  id += '&rand=' + Math.random();
  //var objAjax = new Ajax.Updater( 'comment', urls, {method: 'get', parameters: id, asynchronous: 1 });
  $("#comment").load(urls + '?' + id);
}


function getTrackback() {
  var url ;
  var id = '';
  urls = '/article/trackback';
  var divtb = document.getElementById('trackback');
  if (divtb.style.display == "block"){
    divtb.style.display = "none";
    return;
  }
  divtb.style.display = "block";
  id = 'id=' + get_location_pathname2article_id();
  //var objAjax = new Ajax.Updater( 'trackback', urls, {method: 'get', parameters: id, asynchronous: 1 });
  $("#tblist").load(urls + '?' + id);
}


// function showsum(elem, visible, sum_id) {
//   var target = elem;
//   if (typeof(elem) == 'object') {
//     target = elem.target || elem.srcElement;
//   }
//   var helper = new divHelper(target);
//   var d = document.getElementById(sum_id);
//   if (visible == 1) {
//     if (d) {
//       if (d.style.display == 'none') {
//         helper.show(d.innerHTML);
//       }
//     }
//   } else {
//     helper.hide();
//     if (d) {
//       d.style.display = 'none';
//     }
//   }
// }
function showsum(){}


function get_location_pathname2article_id(){
  var id  = '';
  var str = location.pathname;
  var url = /^\/article\/detail\/(\d+)/;
  if (str.match(url)) {
    var m = str.match(url);
    id = m[1];
  }
  url = /^\/article\/proof\/(\d+)/;
  if (str.match(url)) {
    var m = str.match(url);
    id = m[1];
  }
  url = /^\/(%|[A-Za-z0-9])*\/article\/detail\/(\d+)/;
  if (str.match(url)) {
    var m = str.match(url);
    id = m[2];
  }
  return id;
}

// set article ad element
function set_art_ad(ad_count, rel_key) {
  var re = new RegExp("p=([0-9]+)", "i");
  var p = 'p1';
  if (location.search.match(re)) {
    p = 'p'+RegExp.$1;
  }

  var art = document.getElementById('article');
  var pgelm = document.getElementById(p);
  var p_elm;
  // p1がない
  if (pgelm == null) {
    p_elm = art;
  } else {
    p_elm = pgelm;
  }
  if (p_elm.getAttribute('ref') == 'noad') return;

  var sib = null;
  // search p element
  for(var n=0;n<p_elm.childNodes.length;n++) {
    var node = p_elm.childNodes[n];
    var tagName = node['tagName'];
    if (tagName != undefined && tagName.match(/^p/i)) {
      sib = node;
      break;
    }
    if (n>=4) {break;}
  }
  // only p
  if (sib == null) return;

  var rand = Math.floor( Math.random() * ad_count );
  var aditem = fxadlist[rand];

  var div = document.createElement('div');
  div.setAttribute('class','inner_banner');
  div.setAttribute('className','inner_banner'); //ie
  div.innerHTML = aditem.html;
  
  // an element insert before p
  p_elm.insertBefore(div, sib);
}

// news load
function news_init() {
  if (typeof(fxadlist) == 'undefined') return;
  set_art_ad(fxadlist.length, 'nc');
  set_link_event('nc');
}
// article load
function art_init() {
  if (typeof(fxadlist) == 'undefined') return;
  set_art_ad(fxadlist.length, 'ac');
  set_link_event('ac');
}


function delFile(id,filename) {
  if(!confirm('ファイルを削除しますか？'))
    return false;
  var data = 'id=' + id + '&file_name=' + filename + '&mode=del';
  jQuery.ajax({
    type: "POST",
    url: '/user/author/upload',
    data: data,
    success: function(msg){
      alert('削除しました');
      location.reload();
    }
  })
}

// ホットスポット置換
function replace_hotspot(parag, hs_words) {

  var re_words = new RegExp(hs_words.join("|"), "ig");
  // 重複置換チェック用
  var save_words = [];

  parag.each( function() { 
    $(this).contents().each( function() {
      // テキストのみ置換
      if ($(this)[0].nodeName == '#text') {
        var html = $(this)[0].nodeValue;
        html = html.replace(re_words, function(keyword, subkey) {
          if (keyword in save_words) {
            return keyword;
          } else {
            save_words[keyword]=1;
            var enc_key = encodeURIComponent(keyword);
            var area_key = 'articleinner';
            var hs_link='http://search.moneyzine.jp/sponsor/?Keywords='+enc_key+'&ref='+area_key+'_'+enc_key;
            return '<a href="'+hs_link+'" title="「'+keyword+'」を検索（PR）" class="hslink" onclick="ov_click_count(location.href,\''+area_key+'\',\''+keyword+'\')">'+keyword+'</a>';
          }
        });
        
        // ノード置換のためspanタグにする
        var span = document.createElement('span'); 
        span.innerHTML = html;

        $(this).replaceWith(span);
      }
    })
  })
}

// auto hotspot pでテキストのみの箇所だけ置換
$('#article').ready(function(){
  if ($('#article').html() == null) return;

  var hs_words=['アメリカ','米ドル','ユーロ','日経','FX','セミナー','自動売買','ローン','カード','保険','キャッシング','くりっく365','クレジットカード','システムトレード','スワップ','デイトレード','証券','ビジネスローン','ファイナンシャルプランナー','ファンド','ローン','遺産相続','過払い','株式投資','外為','資金繰り','資金調達','買取','手数料比較','消費者金融','賞金','信用','生命保険','融資','査定','低金利','投資','入門','独立開業','自動車','相談','民事再生','投信','投資信託','富裕層','年収','確定申告','中国株','ギャンブル','パチンコ','競馬','先物','ノーロード','ポートフォリオ','資産運用','貴金属','負債','会計','CFD','レバレッジ'];
  
  var p_led = $('#lead>p');
  var p_art = $('#article>div>p');
  if (p_art.length==0) {
    p_art = $('#article>p');
  }
  
  replace_hotspot(p_led, hs_words);
  replace_hotspot(p_art, hs_words);
});
