var defaultSearch = 'キーワードを入力';
var defaultComment = 'コメントを入力してください';
// 円グラフ Flash
var loadTime = 0; //[ms]
var waitTime = 200; //[ms]
var genreArray = new Array();
genreArray[ 'new' ] = 'news_and_society';
genreArray[ 'pol' ] = 'politics_and_economy';
genreArray[ 'ent' ] = 'entertainment';
genreArray[ 'eco' ] = 'ecology';

$(function(){

	$( '> li:first', 'ul, ol' ).addClass( 'first' );
	$( '> li:last', 'ul, ol' ).addClass( 'last' );
	$( '#top-feature dd:first' ).addClass( 'first' );
	$( 'dl.content-list dd ol li:odd' ).addClass( 'odd' );
	$( 'dl.content-list dd ol li:even' ).addClass( 'even' );
	$( '#list li:odd' ).addClass( 'odd' );
	$( '#list li:even' ).addClass( 'even' );
	$( 'div.mypage-list-box ol li:odd' ).addClass( 'odd' );
	$( 'div.mypage-list-box ol li:even' ).addClass( 'even' );
	$( 'ul.prof-rank-g li:odd , ul.prof-rank-e li:odd , ul.prof-rank-a li:odd , ul.prof-rank-w li:odd' ).addClass( 'odd' );
	$( 'ul.prof-rank-g li:even , ul.prof-rank-e li:even , ul.prof-rank-a li:even , ul.prof-rank-w li:even' ).addClass( 'even' );
	$( '#topic-hot #list li:last-child dl' ).addClass( 'last' );
	$( '#topic-hot #list li dl dd:last-child' ).addClass( 'last' );
	$( '#rank-list li dl dd:last-child' ).addClass( 'last' );
	$( '#side-faq dd:last-child' ).addClass( 'last' );
	$( 'div.formbox01 form dl dd:last-child' ).addClass( 'last' );
	$( 'div.formbox01-c dl dd:last-child' ).addClass( 'last' );
	$( 'div.formbox05 dd:last-child' ).addClass( 'last' );
	$( 'dd#genre-ranking dl dd:last-child' ).addClass( 'last' );
	$( '#setting input[type="text"] , #setting input[type="password"] , #setting textarea' ).addClass( 'ipt-off' );
	$( '*:disabled' ).css( 'cursor' , 'default' );
	$( '#feature #top-feature , div.top-topic-img , p.top-topic-txt , #topic-img , #topic-txt , #side-ranking dd ol li , #error-box , div#unvote , #voted-yes , #voted-no , div.nomore-cmt , div.nomore-made , #prof-box , #prof-box dl , #topic-hot #list , #topic-hot #list li dl , #rank-list , #rank-user-order li, div.nocmt p , dl#side-hot , dd#genre-ranking , dl#side-recent , dl#side-recent dd ' ).corner( '5px' );


	// FLASH のバージョンチェック
	$( 'object' ).each( function(){
		var installVer = deconcept.SWFObjectUtil.getPlayerVersion();
		if( !installVer['major'] ){
			afterFlash()
		}
	});

	//検索フォーム
	if ($( 'input#search' ).val() == '') {
		$( 'input#search' ).val( defaultSearch );
	}
	$( 'input#search' ).focus( function() {
		$( this ).toggleClass( 'ipt-on' );
		$( '#container > ul' ).hide();
		if( $( this ).val() == defaultSearch ) {
			$( this ).val( '' );
		}
	}).blur( function() {
		if( $( this ).val() == '' ) {
			$( this ).val( defaultSearch ).toggleClass( 'ipt-on' );
		}
	});

	$( '#to-search' ).click( function(){
		$( '#search' ).focus();
	});

	// outline 非表示
	$( 'a', 'h1, #side-use' ).focus( function(){
		$( this ).blur();
	});

	//フォーム全般
	$( 'input[@type="text"] , input[@type="password"] , textarea' ).focus( function() {
		$( this ).addClass( 'ipt-on' );
	}).blur( function() {
		$( this ).removeClass( 'ipt-on' );
	});

	var birthFlag = 1;
	$( '#RequiredBirth' ).hover( function(){
		if ( birthFlag ) {
			$( '#RequiredBirth' ).val( '1960' );
			birthFlag = 0;
		}
	},function(){});

	//コメント入力フォーム
	if ($( 'form#comment textarea' ).val() == '' || $( 'form#comment textarea' ).val() == defaultComment ) {
		$( 'form#comment textarea' ).val( defaultComment );
	}
	$( 'form#comment textarea[@disabled]' ).text( '' ).addClass( 'dis-comment' );
	$( 'form#comment textarea' ).focus( function() {
		$( this ).toggleClass( 'ipt-on' );
		if( $( this ).val() == defaultComment ) {
			$( this ).val( '' );
		}
	}).blur( function() {
		$( this ).toggleClass( 'ipt-on' );
		if( $( this ).val() == '' ) {
			$( this ).val( defaultComment );
		}
	});
	$( 'form#comment' ).submit( function() {
		if ($( 'form#comment textarea' ).val() == '' || $( 'form#comment textarea' ).val() == defaultComment ) {
			alert( defaultComment );
			$( 'textarea', this ).focus();
			return false;
		}
	});

	//トピック一覧ロールオーバー
	$( 'dl.content-list dd ol li > a , #list li > a , #mypage-other div.mypage-list-box ol li > a , #mypage-other-makelist div.mypage-list-box ol li > a' ).hover( function() {
		$( this ).parent().addClass( 'sel' );
	}, function() {
		$( this ).parent().removeClass( 'sel' );
	});
	$( '#list li dl dt a' ).hover( function() {
		$( this ).parents( 'ol#list li' ).addClass( 'sel' );
	}, function() {
		$( this ).parents( 'ol#list li' ).removeClass( 'sel' );
	});
	$( '#rank-user-order li > a' ).hover( function() {
		$( this ).parents( '#rank-user-order li' ).addClass( 'on' );
	}, function() {
		$( this ).parents( '#rank-user-order li' ).removeClass( 'on' );
	});
	$( '#tit-topic-list ul li > a , #side-faq dd > a , #side-use dd > a' ).hover( function() {
		$( this ).parent().addClass( 'on' );
	}, function() {
		$( this ).parent().removeClass( 'on' );
	});

	//バーチャルナビのセンタリング
	var naviWidth = $( '.hit li:first' ).width() * 1.25 * $( '.hit:first li' ).size();
	var baseWidth = $( '.ins-navi:first' ).width();
	naviWidth = Math.floor( ( baseWidth - naviWidth ) / 2 )
	$( '.hit' ).css( 'left', naviWidth + 'px' );

	//カテゴリリストの改行
	var catTopicMax = $( '.cat-list' ).width() * 1;
	var catTopicWidth = 0;
	$( '.cat-list li' ).each( function(){
		catTopicWidth += $( this ).width();
		if ( catTopicWidth > catTopicMax ) {
			catTopicWidth = $( this ).width();
			$( this ).prev().append( '<br />' );
		}
	});

	// トピックス作成画面ジャンル選択
	var cat_sel_func = function(){
		$( '#make-cat-sel' ).hide();
		var objId = '#cat-' + $( this ).attr( 'id' );
		$( 'ul', '#cat-sel' ).hide().filter( objId ).show();
		$( 'ul:hidden input:checked', '#cat-sel' ).attr({checked: false});
	};
	$( 'ul', '#cat-sel' ).hide();
	$( ':checked', '#make-genre' ).each(cat_sel_func);
	$( ':radio', '#make-genre' ).click(cat_sel_func);

	// ジャンル別サブメニュー表示
	$( 'body.topic-sec' ).each( function(){
		var subHtml = '';
		$( 'li', 'body.topic-sec #genre' ).each( function(){
			var objId = $( this ).attr( 'id' ).split( '-' )[1];
			var subId = 'sub-' + objId;
			if ( objId != 'gen' ) {
				subHtml += '<ul id="' + subId + '">';
				subHtml += '<li class="list"><a href="/' + genreArray[ objId ] + '/topic/list" title="トピック一覧">トピック一覧</a></li>';
				subHtml += '<li class="attention"><a href="/' + genreArray[ objId ] + '/topic/hot" title="注目トピック">注目トピック</a></li>';
				subHtml += '<li class="ranking"><a href="/' + genreArray[ objId ] + '/topic/voteranking" title="投票数ランキング">投票数ランキング</a></li>';
				subHtml += '</ul>';
			}
		});
		$( '#container' ).append( subHtml );

		var viewFlag = 1;
		$( 'a', 'body.topic-sec #genre' ).hover( function() {
			if ( viewFlag ) {
				viewFlag = 0;
				var objId = $( this ).parents( 'li:first' ).attr( 'id' );
				var subId = 'sub-' + objId.split( '-' )[1];
				$( '#' + subId ).show();
			}
		}, function() {
			viewFlag = 1;
			$( '#container > ul' ).hide();
		});

		$( '#container > ul' ).hover( function() {
			$( this ).show();
		}, function() {
			$( this ).hide();
		});

	});


    // validate
    $("#check-form").formValidate({errorClass: 'alert'});

  /////////////////////
  // top-category
  var html_top_page = function(obj, data)
  {
    $.each(data, function() {
      var genre   = '<span>[' + this.genre + ']</span>';
      var title   = '<a href="' + this.link + '">' + this.title + '</a>';
      var time    = '<var>' + this.date + '</var>';
      var comment = ' (<var title="コメント">' + this.comment + '</var>)';
      obj.append('<li>' + title + genre + time + comment + '</li>');
    });
  }
  var genre_top_page = function(obj, data)
  {
    $.each(data, function() {
      var title   = '<a href="' + this.link + '">' + this.title + '</a>';
      var time    = '<var>' + this.time + '</var>';
      var comment = ' (<var title="コメント">' + this.comment + '</var>)';
      obj.append('<li>' + title + time + comment + '</li>');
    });
  }

  function topic_link_hidden(obj)
  {
    $(obj).hide().after('<span class="sel">' + $(obj).text() + '</span>');
  }
  function topic_link_visible(obj)
  {
    $(obj).show().next().remove();
  }

  function get_topics(obj, html_func, more)
  {
    var self = obj;
    $(self).click(function(){
      var url = '/json/topics/' + $(self).attr('href').substring(1).replace('-', '/');
      $.ajax({
        url: url,
        type: "GET",
        dataType: "json",
        timeout: 5000,
        error: function() {
          alert('エラーが発生しました');
        },
        success: function(data) {
          if (!data.result) {
            alert(data.errormsg);
            return false;
          }

          $("#category-navi a:hidden").each(function(){
             topic_link_visible(this);
          });

          var topic_data = $(document.createElement('ol'));
          html_func(topic_data, data.topics);

          $( 'li:first', topic_data ).addClass( 'first' );
          $( 'li:last', topic_data ).addClass( 'last' );
          $( 'li:odd', topic_data ).addClass( 'odd' );
          $( 'li:even', topic_data ).addClass( 'even' );

          $('#top-category-topics').empty().append(topic_data);

          var append_more = (data.topics_url)
            ? '<a href="' + data.topics_url + '">もっと見る</a>'
            : '&nbsp;';
          $('dd.content-more', more)
            .empty().append(append_more);

          topic_link_hidden(self);
        }
      });

      return false;
    });

    if ($(self).hasClass('sel')) {
      $(self).removeClass('sel');
      topic_link_hidden(self);
    }
  }

  $("#top #category-navi a").each(function(){
    get_topics(this, html_top_page, $("#top-genre-topics"));
  });
  $("#genre-top #category-navi a").each(function(){
    get_topics(this, genre_top_page, $("#category-list"));
  });

  /////////////////////
  // assent
  var assentor_inited = false;
  function assentor_init()
  {
    if (assentor_inited){ return; }

    var html = '\
<div class="assentor-bg"></div> \
<dl class="assentor"> \
<dt></dt> \
<dd class="assentor-list"> \
<ol class="clearfix"> \
</ol> \
</dd> \
<dd class="close"><a href="#">閉じる</a></dd> \
</dl> \
'
    $('body').append(html);
    $( 'dd.close a, div.assentor-bg' ).click( function(){
      $( 'div.assentor-bg , dl.assentor' ).fadeOut( 'fast' );
      return false;
    });
    assentor_inited = true;
  }

  $('a.support').click(function(event){
    if ($("span", this).text() == 0) {
      return false;
    }

    var self = this;
    var id = $(self).attr('id').match(/\d+$/);
    if (!id) { return false; }

    $.ajax({
      url: '/json/assentor/' + id,
      type: "GET",
      dataType: "json",
      timeout: 5000,
      error: function() {
        alert('エラーが発生しました');
      },
      success: function(data) {
        if (!data.result) {
          alert(data.errormsg);
          return false;
        }

        assentor_init();
        var name = data.owner_name;
        if (name == '') { name = '-' }

        $('dl.assentor dt').html(name + 'さんに[賛成]を付けてくれたメンバー');
        var li = [];
        $.each(data.users, function() {
          if (this.id) {
            li.push('<li><a href="' + this.url + '">' + this.name + '</a></li>');
          } else {
            li.push('<li>-</li>');
          }
        });

        $('dl.assentor ol').replaceWith('<ol class="clearfix">' + li.join("") + '</ol>');
        $("div.assentor-bg, dl.assentor").fadeIn('fast');
      }
    });
    return false;
  });

  $("a.assent").click(function(){
    var self = this;
    var self_parent = $(self).parent();
    var self_org = $(self).clone(true);
    var txt = $(this).text();
    $(self).replaceWith('<span>'+txt+'</span>');

    $.ajax({
      url: $(this).attr('href'),
      type: "POST",
      dataType: "json",
      timeout: 5000,
      error: function() {
        alert('エラーが発生しました');
        $(self_parent).empty().append(self_org);
      },
      success: function(data) {
        if (!data.result) {
          alert(data.errormsg);
          $(self_parent).empty().append(self_org);
          return false;
        }

        // assent-user count up
        var assent_user = $("#support-" + data.comment_id + " span");
        assent_user.text(Number(assent_user.text()) + 1);
        $(self_parent).empty().append('<span>投票しました</span>');
      }
    });

    return false;
  });

	$( '#make-title' ).lenCheck( {maxLength:40, includeCR:true} );
	$( '#make-content' ).lenCheck( {maxLength:200, includeCR:true} );
	$( '#make-comment, #comm' ).lenCheck( {maxLength:170, includeCR:false} );
	$( '#prof' ).lenCheck( {maxLength:500, includeCR:true} );

});

function afterFlash() {
	setTimeout( showNumber, loadTime );
}

function showNumber() {
	$( '#topic-box var' ).fadeIn( waitTime );
	setTimeout( function() {
		$( '#select li span' ).css( 'visibility', 'visible' );
	}, waitTime );
}

(function($){
	$.fn.lenCheck = function( op ){
		var options = {
			maxLength:10,
			includeCR:true
		}
		$.extend( options, op || {} );
		return this.each( function(){
			if ( ! ( ( $( this ).val() == '' ) || ( $( this ).val() == defaultComment ) ) ) lengthCheck( this, options );
			$( this ).keyup( function() {
				lengthCheck( this, options );
			});
		});
	}
	function lengthCheck(obj,options){
		var objText = $( obj ).val();
		if ( !options.includeCR ) objText = objText.replace( /\n/g, '' );
		var objLen = objText.length;
		var objId = $( obj ).attr( 'id' );
		var objLimit = Number( options.maxLength ) - objLen;
		var objMsg ='あと ' + objLimit + ' 文字';
		var objLimitElm = $( '#' + objId + '-limit' );
		if ( objLimit < 0 ) {
			objMsg = -objLimit + '文字オーバー';
			objLimitElm.addClass( 'alert' );
		} else {
			objLimitElm.removeClass( 'alert' );
		}
		objLimitElm.text( objMsg );
	}
})(jQuery);

