$(document).ready(function () {
  ct = new wv();

  ct.param = {
    category_id : null
  };

  ct.init = function () {
    var i = 0, l, h;
    wv.prototype.mode = "category";
    $("h3.firstCategory").bind( "click", ct.getChildCategories ).bind( "click", ct.changeCategory );
    //第2下位層まで取り込む
    $( "h3.firstCategory" ).each( function() {
                                    ct.param.category_id = this.id;
                                    ct.getXML();
                                  });
  };

  ct.getChildCategories = function ( event ) {
    ct.param.category_id = event.target.id;
    var i,
        tag = event.target.tagName,
        tag_num = tag.substr( 1 );

    //開いているものをクリックしたとき
    if ( $(event.target).hasClass("open") ) {
      $(event.target).removeClass("open");
      
      $(event.target).siblings().find( ".categoryTitle" ).siblings().hide();
      for ( i = tag_num; i < 8; i++ ) {
        $( "h" + i + ".categoryTitle.open" ).removeClass("open");
      }

      $(event.target).siblings().hide();
      $( tag + ".categoryTitle").parent().show(); //

    //閉じているものをクリックしたとき
    } else {
      for ( i = tag_num; i < 4; i++ ) {
        $( "h" + i + ".categoryHeader.open" ).siblings().hide();
        $( "h" + i + ".categoryHeader.open" ).removeClass("open");
        $( "h" + i + ".categoryHeader").parent().show();
      }

      for ( i = tag_num; i < 8; i++ ) {
        $( "h" + i + ".categoryTitle.open" ).siblings().hide();
        $( "h" + i + ".categoryTitle.open" ).removeClass("open");
        $( "h" + i + ".categoryTitle").parent().show();
      }

      $( tag + ".categoryTitle" ).parent().hide(); //第3階層以下のみ対象
      $(event.target).parent().show();
      $(event.target).addClass("open");

      //既に子カテゴリを取得しているかどうか
      if ( $(event.target).siblings().length != 0 ) {
        $(event.target).siblings().show();
      } else {
        // APIリクエスト(GETメソッド)
        ct.getXML();
      }
    }
  };

  ct.getXML = function () {
    var myObj = this;
    $.ajax({
      url      : '../fn/getCategory.php',
      data     : 'cat=' + myObj.param.category_id,
      dataType : 'xml',
      cache    : false,
      success  : function ( obj ) {
                   myObj.createDom( obj );
                 }
    });
  };

  ct.createDom = function ( result ) {
    var w = wv.prototype,
        current_arr = result.getElementsByTagName("Current"),
        currentId = w.getTextContents( result.getElementsByTagName("Id")[0] ),
        children_arr = result.getElementsByTagName("Child"),
        children_num = 0, i, d = document, ul, li, h, head = "",
        depth = result.getElementsByTagName("Category").length;
    
    // 下位カテゴリ数を計算
    children_num = children_arr.length;
   
    //とりあえずわかりやすくするため
    /*
    for ( i = 2; i < depth; i++ ) {
      head += "-";
    }
    */

    if ( children_num != 0 ) {
      ul = d.createElement("ul");
      for (i = 0; i < children_num; i++) {
        li = d.createElement("li");
        h = d.createElement("h" + (depth + 1));
        $(h).text( head + w.getTextContents( children_arr[i].lastChild.firstChild ) );
        $(h).addClass("categoryTitle");
        h.id = w.getTextContents( children_arr[i].firstChild );
        $(h).bind("click", ct.getChildCategories).bind("click", ct.changeCategory);
        $(li).append(h);
        $(ul).append(li);
      }
      if ( depth == 3 ) $(ul).css("display", "none");
      $("#" + currentId).parent().append(ul);
    }
  };

  ct.changeCategory = function (event) {
    var id = event.target.id;
    //id を検索オブジェクトのparamに入れ直し検索実行
    wv.prototype.category_id = ct.createCategoryId( id );

    if ( wv.prototype.mode == "similar" ) {
      is.doSearch( is.param.query, "category" );
    } else {
      cs.doSearch( cs.param.query, "category" );
    }
  };

  ct.createCategoryId = function (id) {
    var ret = "13457";
    $(".open").each(function () {
                        ret += "%09" + this.id;
                    });
    if ( ret == "13457" ) {
      ret = "";
    }
    return ret;
  }

  ct.selectCategoryFromTag = function ( tag ) {
    var tag_arr = tag.replace( /0\t/g, "" ).split( "\n" ), tgt;
    var i, id, h, num = 3;

    if ( tag_arr[0] == 13457 ) {
      //カテゴリを13457に初期化する
      wv.prototype.category_id = "13457";
      tag_arr.shift(); //13457を取り除く
    } else {
      return;
    }

    //一度初期状態に戻す
    $( "h3.categoryHeader.open" ).siblings().hide();
    $( "h3.categoryHeader.open" ).removeClass("open");
    $( "h3.categoryHeader").parent().show();

    for ( i = 4; i < 8; i++ ) {
      $( "h" + i + ".categoryTitle.open" ).siblings().hide();
      $( "h" + i + ".categoryTitle.open" ).removeClass("open");
      $( "h" + i + ".categoryTitle").parent().show();
    }

    for ( i = 0; i < 8; i++) { //最大5階層まで
      id = tag_arr[i];
      ct.param.category_id = id;
      if ( id == 0 ) break; //最後の0を番兵として利用
      if ( $("#" + id).length != 0 ) {
        //既にある
        wv.prototype.category_id += "%09" + id;
        tgt = $("#" + id);
        h = tgt[0].tagName;

        // openしている箇所を1か所にするため
        if ( num > h.substr( 1 ) ) {
          break;
        } else {
          num++;
        }
        $( h + ".categoryTitle").parent().hide();
        tgt.parent().show();
        tgt.addClass( "open" );

        //既に子カテゴリを取得しているかどうか
        if ( $("#" + id).siblings().length != 0 ) {
          tgt.siblings().show();
        } else {
          // APIリクエスト(GETメソッド)
          ct.getXML();
        }
      } else {
        break;
      }
    }
    is.setHash();
  };

  ct.init();
});

