var CommentWindow = Class.create();
CommentWindow.instance = {};
CommentWindow.prototype = {
    initialize: function(seq,category){
        this.seq = seq;
        this.id = CommentWindow_initialValue[seq].entryid;
        this.parentObj = $('commentwindow-' + seq);
        if(category){
            this.category = category;
        }else{
            this.category = '';
        }
        this.element = document.createElement('div');

        //DOM組み立て
        var html = '<div class="comment_waku"> '
                 + '  <form action="' + gBASE_URL + 'comment" method="post">'
                 + '    <input type="hidden" name="action_comment" value="1" >'
                 + '    <input type="hidden" name="submit" value="submit" >'
                 + '    <input type="hidden" name="url" value="' + CommentWindow_initialValue[seq].entryurl+ '" >'
                 + '    <input type="hidden" name="c" value="' + this.category + '" >'
                 + '    <div class="comment_back"> '
                 + '      <table width="100%" border="0" cellspacing="0" cellpadding="0">'
                 + '        <tr height="20" valign="bottom"> '
                 + '          <td width="15"><img src="/common/images/spacer.gif" width="15" height="1" alt=""></td>'
                 + '          <td align="left" class="main-txt">コメント</td>'
                 + '          <td align="right"><span id="commentwindow-clickclose-' + this.seq + '"><a href="javascript:void(0);" class="medium"><img src="/common/images/icn/icn_close.gif" width="13" height="13" align="absmiddle" border="0">&nbsp;閉じる</a></span></td>'
                 + '          <td width="15"><img src="/common/images/spacer.gif" width="15" height="1" alt=""></td>'
                 + '        </tr>'
                 + '      </table>'
                 + '    </div>'
                 + '    &nbsp;&nbsp;このニュースは？'
                 + '    <table width="100%" border="0" cellspacing="0" cellpadding="0">'
                 + '      <tr>'
                 + '        <td  valign="middle" align="left" nowrap>'
                 + '          &nbsp;&nbsp;<input id="commentwindow-thumbup-' + this.seq + '" type="radio" value="1" name="thumb" checked ><label for="commentwindow-thumbup-' + this.seq + '">&nbsp;<img src="/common/images/icn/icn_circle.gif" alt="支持する" width="20" height="18" align="absmiddle"></label>&nbsp;&nbsp;'
                 + '          <input id="commentwindow-thumbdown-' + this.seq + '" type="radio" value="0" name="thumb" ><label for="commentwindow-thumbdown-' + this.seq + '">&nbsp;<img src="/common/images/icn/icn_cross.gif" alt="支持しない" width="20" height="18" align="absmiddle"></label>'
                 + '        </td>'
                 + '        <td align="right">'
                 + '        </td>'
                 + '      </tr>'
                 + '      <tr> '
                 + '        <td colspan="2">'
                 + '          <textarea name="comment" class="comment_area" id="commentwindow-textarea-' + this.seq + '" wrap="soft">' + CommentWindow_initialValue[seq].comment + '</textarea><br>'
                 + '          <span style="font-size:90%;">&nbsp;&nbsp;&nbsp;&nbsp;全角400字以内で入力してください。<span id="commentcount-' + this.seq + '"></span></span>'
                 + '        </td>'
                 + '      </tr>'
                 + '    </table>'
                 + '    <table border="0" cellspacing="0" cellpadding="0" style="font-size:85%">'
                 + '      <tr>'
                 + '        <td>&nbsp;&nbsp;&nbsp;</td>'
                 + '        <td>';

        //タグ入力UI
        this.tagInputUI = new TagInputInterface(this.seq, ('commentwindow-tag-' + this.seq));
        html += this.tagInputUI.getHtmlInsert();

        html += '        </td>'
             +  '      </tr>'
             +  '    </table>'
             +  '    <table border="0" cellspacing="0" cellpadding="0">'
             +  '      <tr valign="middle">'
             +  '        <td>&nbsp;&nbsp;タグ:&nbsp;</td>'
             +  '        <td><input type="text" maxlength="50" value="' + CommentWindow_initialValue[seq].tag + '" name="tag" class="comment_tag" style="width:300px;" id="commentwindow-tag-' + this.seq + '"></td>'
             +  '      </tr>'
             +  '      <tr valign="middle">'
             +  '        <td>&nbsp;</td>'
             +  '        <td>&nbsp;<span style="font-size:80%;"><span id="alertMaxItemsOver">カテゴリーは2個まで、タグは合計5個まで（空白区切り）</span><br /> （<a href="' + gBASE_URL + 'help/pickup#pickup05" target="_blank">タグとは？</a>）</span></td>'
             +  '      </tr>'
             +  '    </table>'
             +  '    <table width="100%" border="0" cellspacing="0" cellpadding="0">'
             +  '      <tr> '
             +  '        <td align="right" valign="middle">'
             +  '          <input type="hidden" name="fromcommentwindow" value="true">'
             +  '          <input value="" type="image" name="submit" src="/common/images/bt_go.gif" width="41" height="22" alt="送信" align="absmiddle" id="commentwindow-form-' + this.seq + '">'
             +  '        &nbsp;&nbsp;</td>'
             +  '      </tr>'
             +  '    </table>'
             +  '  </form>'
             +  '</div>';
        this.element.innerHTML = html;

        this.parentObj.appendChild(this.element);

        this.closeButton = document.getElementById('commentwindow-clickclose-' + this.seq);
        this.commentArea = document.getElementById('commentwindow-textarea-' + this.seq);

        this.tagInputUI.setEvent();
        this.tagInputUI.refreshTagList();

        this.slideHeight = this.element.offsetHeight; //この行は「一瞬表示させた状態」で取得する

        var s = this.element.style;
        s.visibility = 'visible';
        s.display = 'none';
        s.overflow = 'hidden';
        s.height = '1px';

        Event.observe(this.closeButton,  'click', this.slideClose.bindAsEventListener(this), false);
        Event.observe(this.commentArea,  'keyup', this.setCommentCount.bindAsEventListener(this), false);

        this.setGoodBadButton(CommentWindow_initialValue[this.seq].vote);
        this.slideOpen();
    },
    slideOpen: function(){
        var objTextArea = $('commentwindow-textarea-' + this.seq);
        var objSubmitButton = $('commentwindow-form-' + this.seq);

        this.element.style.display = 'block';
        new Rico.Effect.Size( this.element, null, this.slideHeight, 120, 8, {complete: function(){objSubmitButton.focus();objTextArea.focus();}});
    },
    slideClose: function(){
        var myObj = this.element;
        myObj.style.overflow = "hidden";
        new Rico.Effect.Size( myObj, null, 1, 120, 8, {complete: function(){myObj.style.display = 'none';}});
    },
    setCommentCount: function(){
        var cnt = jstrlen(this.commentArea.value);
        $('commentcount-' + this.seq).innerHTML = '（現在 ' + cnt + ' 文字）';

    },
    setGoodBadButton: function(buttonName){
        if(buttonName == 'good'){
            $('commentwindow-thumbup-' + this.seq).checked = true;
        }
        else if(buttonName == 'bad'){
            $('commentwindow-thumbdown-' + this.seq).checked = true;
        }
    }
}

//タグ入力支援UI
var gTagList = [
    {
        items: [
            'クルマ',
            'インターネット',
            '科学',
            'テクノロジー',
            'ビジネス',
            '政治',
            '社会',
            'くらし',
            'マネー',
            'マーケティング',
            'キャリア',
            '医療',
            '健康',
            '教育',
            '子ども',
            'エンタメ',
            'スポーツ',
            '恋愛',
            '結婚',
            '海外',
            '雑学',
            'ネタ',
            '写真',
            '動画']
    }];
    
var TagInputInterface = Class.create();
TagInputInterface.prototype = {
    initialize: function(seq, tagfieldID){
        //seq: html中で一意な連番、tagfieldID: タグ入力textboxのid
        this.seq = seq;
        this.tagfieldID = tagfieldID;
        this.selectAreaID = 'commentwindow-taglist-' + this.seq; //タグ選択UIのエリア
        this.tagArea = null;
        this.separator = '(　| )+';
    },
    getHtmlInsert: function(){
        var html = '<table border="0" cellpadding="0" cellspacing="0">'
                 + '  <tr><td style="margin:0px;padding:0px;"><div style="margin:5px 0px 0px 0px;padding:0px;width:89px;height:15px;"><img src="/common/images/tab_tagcategory.gif" width="100" height="15" alt="ニュースカテゴリー"></div>'
                 + '  <div style="margin:0px;padding:0px 0px;"><span id="' + this.selectAreaID + '"></span></div></td></tr>'
                 + '  <tr><td style="margin:0px;padding:0px;"><div style="margin:0px;padding:0px;width:30px;height:7px;text-align:right;"><img src="/common/images/tab_tagcategory_down.gif" width="9" height="7" alt=""></div></td></tr>'
                 + '</table>';
        return html;
    },
    setEvent: function(){
        //タグ入力フィールド
        this.tagArea = $(this.tagfieldID);
        Event.observe(this.tagArea, 'keyup', this.refreshTagList.bindAsEventListener(this), false);
        // このid要素がinnerHTMLに反映されたあとに実行させること。
    },
    refreshTagList: function(){
        var target = document.getElementById(this.selectAreaID);
        var checkstr = ' ' + this.tagArea.value + ' ';
        var html = '<table border="0" cellpadding="0" cellspacing="0" bgcolor="#F0EDE7"><tr>';

        for(var j = 0; j < gTagList.length; j++){
            //選択中のタブパネルのみを表示
            //タグごとにループ
            this.tagItem = Array();
            for(var i = 0; i < gTagList[j].items.length; i++){
                var strSelected = checkstr.match(new RegExp(this.separator + gTagList[j].items[i] + this.separator, 'ig')) ? ' style="background-color:#999;color:#fff;"' : '';
                if(i % 4 == 0){
                    html += '</tr><tr>';
                }
                html += '<td width="92" height="25" style="font-size: 13px;"><a href="javascript:void(0);" class="tagitem"' + strSelected + ' onclick="CommentWindow.instance[' + this.seq + '].tagInputUI.clickTagItem(\'' + gTagList[j].items[i] + '\')"><img src="/common/images/icn/category/comment_form/'
                if(gTagList[j].items[i] == 'ビジネス'){
                    html += 'icn_biz.gif';
                }else if(gTagList[j].items[i] == '政治'){
                    html += 'icn_poli.gif';
                }else if(gTagList[j].items[i] == 'インターネット'){
                    html += 'icn_it.gif';
                }else if(gTagList[j].items[i] == 'IT'){
                    html += 'icn_it.gif';
                }else if(gTagList[j].items[i] == 'くらし'){
                    html += 'icn_life.gif';
                }else if(gTagList[j].items[i] == '社会'){
                    html += 'icn_soc.gif';
                }else if(gTagList[j].items[i] == '医療'){
                    html += 'icn_medical.gif';
                }else if(gTagList[j].items[i] == '健康'){
                    html += 'icn_health.gif';
                }else if(gTagList[j].items[i] == '科学'){
                    html += 'icn_science.gif';
                }else if(gTagList[j].items[i] == 'テクノロジー'){
                    html += 'icn_tech.gif';
                }else if(gTagList[j].items[i] == 'キャリア'){
                    html += 'icn_career.gif';
                }else if(gTagList[j].items[i] == '海外'){
                    html += 'icn_global.gif';
                }else if(gTagList[j].items[i] == '芸能'){
                    html += 'icn_entertainment.gif';
                }else if(gTagList[j].items[i] == 'エンタメ'){
                    html += 'icn_entertainment.gif';
                }else if(gTagList[j].items[i] == 'スポーツ'){
                    html += 'icn_sports.gif';
                }else if(gTagList[j].items[i] == '雑学'){
                    html += 'icn_trivia.gif';
                }else if(gTagList[j].items[i] == 'ネタ'){
                    html += 'icn_neta.gif';
                }else if(gTagList[j].items[i] == '動画'){
                    html += 'icn_movie.gif';
                }else if(gTagList[j].items[i] == '写真'){
                    html += 'icn_image.gif';
                }else if(gTagList[j].items[i] == 'マーケティング'){
                    html += 'icn_marketing.gif';
                }else if(gTagList[j].items[i] == 'マネー'){
                    html += 'icn_money.gif';
                }else if(gTagList[j].items[i] == '恋愛'){
                    html += 'icn_love.gif';
                }else if(gTagList[j].items[i] == '結婚'){
                    html += 'icn_marriage.gif';
                }else if(gTagList[j].items[i] == '教育'){
                    html += 'icn_education.gif';
                }else if(gTagList[j].items[i] == '子ども'){
                    html += 'icn_children.gif';
                }else if(gTagList[j].items[i] == 'クルマ'){
                    html += 'icn_car.gif';
                }
                html += '" align="absmiddle">' + gTagList[j].items[i] + '</a></td> ';
                // ↑onclickのなかの関数表記に注意（グローバルアクセス可能な関数であること）
            }
        }

        html += '</tr></table>'
        target.innerHTML = html;
    },
    clickTagItem: function(tag){
        var target = this.tagArea;
        var tmpStr = (' ' + target.value + ' ');
        if(tmpStr.match(new RegExp(this.separator + tag + this.separator, 'ig'))){
            //削除 - 前後の空白を考慮
            if(target.value.match(new RegExp(this.separator + tag, 'ig'))) { 
                target.value = target.value.replace(new RegExp(this.separator + tag, 'ig'), ''); 
            }
            else if(target.value.match(new RegExp(tag + this.separator, 'ig'))) {
                target.value = target.value.replace(new RegExp(tag + this.separator, 'ig'), ''); 
            }
            else { 
                target.value = target.value.replace(tag, ''); 
            }
        }
        else{
            //項目が多いときはアラート表示
            var tmpStr = target.value.replace(new RegExp(this.separator, 'ig'), " ");
            tmpStr = tmpStr.replace(new RegExp("^( +)"), "");
            tmpStr = tmpStr.replace(new RegExp("( +)$"), "");

            var tmpStrArray = tmpStr.split(" ");
            var gTagItemCount = 0;
            for(var i = 0; i < tmpStrArray.length; i++){
                for(var j = 0; j < gTagList.length; j++){
                    for(var k = 0; k < gTagList[j].items.length; k++){
                        if(tmpStrArray[i] == gTagList[j].items[k]){
                            gTagItemCount++;  
                        }
                    }
                }
            }
            
            if(gTagItemCount > 1 || tmpStr.split(" ").length > 4 ){
                fadeYellow2White('alertMaxItemsOver', 40);
            }else {
                //追加
                target.value += (target.value == '') ? tag : ' ' + tag;
            }
        }
        this.refreshTagList();
    }
}
/*
function closeOtherCategories(){
	var i  = $('other_categories');
	i.style.visibility='hidden';
}
*/

/**
 *    イチオシボタンの動作
 */
var BuryExcellentButton = Class.create();
BuryExcellentButton.prototype = {
	initialize: function(seq, bury, excellent, entryid, bury_login_state, excellent_login_state){
		this.seq = seq;
		this.entryid = entryid;
		this.excellent_login_state = excellent_login_state;
		var idNameExcellentButton = 'excellentbutton-' + seq;
		var idNameExcellentPoint  = 'excellentbuttonpoint-' + seq;
		var idNameLoading = 'loading-' + seq;

		var html = '<tr>'
				+ '  <td>'
				+ '    <table class="table_w88" border="0" cellspacing="0" cellpadding="0">'
				+ '      <tr>'
				+ '        <td class="ichioshi_td" style="vertical-align:bottom;" onmouseover="this.style.backgroundImage=\'url(/common/images/bukumatch/onmouse.gif)\'" onmouseout="this.style.backgroundImage=\'url(/common/images/bukumatch/default.gif)\'" id="' + idNameExcellentButton + '">'
				+ '          <div style="text-align:center;font-size:11px;padding-bottom:3px;color:#E6634D;">'
				+ '            <span id ="' + idNameExcellentPoint + '">' + excellent + 'イチオシ</span>'
				+ '          </div>'
				+ '        </td>'
				+ '      </tr>'
				+ '    </table>'
				+ '  </td>'
				+ '</tr>';

		document.open();
		document.write(html);
		document.close();

		this.objExcellentButton = $(idNameExcellentButton);
		this.objExcellentPoint = $(idNameExcellentPoint);
		this.objLoading = $(idNameLoading);
		this.objPoint = $('id-' + this.entryid);

		//IEバグ対策 widthを指定しないとrico.jsが効かない　背景画像を入れないと、文字・数字の枠に黒が入る
		this.objExcellentButton.style.width = '88px';
		this.objExcellentButton.style.cursor = 'pointer';
		this.objExcellentPoint.style.width = '88px';
		this.objLoading.style.width = '16px';
		this.objPoint.style.width = '76px';
		this.objPoint.style.backgroundImage = 'url(/common/images/blank1x1.jpg)';

		Event.observe(this.objExcellentButton, 'click', this.excellentClick.bindAsEventListener(this));
		if(this.excellent_login_state == 'pushed'){
			this.setUnable('e');
		}
	},
	AjaxRequest: function(flag){
		//ロード中アイコン表示 
		//this.objLoading.style.visibility = "visible";
		var url = gBASE_URL + 'api/clickburyexcellent?id=' + this.entryid + '&flag=' + flag;
		var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			onComplete: this.AjaxReturned.bind(this)
		}
		);
	},
	AjaxReturned: function(originalRequest){
		//ロード中アイコン消す
		//this.objLoading.style.visibility = "hidden";

		var res = originalRequest.responseText;
		resdata = res.split(",");
		res = resdata[0];
		btn_flag = resdata[1];
		update_flag = resdata[2];
		if(res >= 0){//処理成功の場合
			this.startCountupAnimation(res,btn_flag,update_flag);
		}else if(res == -4){
			//-4の場合はCookieが無効のエラー
			alert('Cookieを有効にしてください'); 
		}else{
			//マイナスの場合はエラー
			alert('エラーが発生しました'); 
		}
	},
	excellentClick: function(){
		if(this.isExcellentClicked){
			//何も起こらない
		}else{
			this.objExcellentButton.onmouseover = null;
			this.objExcellentButton.onmouseout = null;
			this.objExcellentButton.style.cursor = 'default';
			this.startButtonAnimation('e');
			this.isExcellentClicked = true;
			this.AjaxRequest('e');
		}
	},
	setUnable: function(btn_flag){
		var myObj = this;
		this.isExcellentClicked = true;
		this.objExcellentButton.style.backgroundImage = 'url(/common/images/bukumatch/pushed.gif)';
		this.objExcellentButton.onmouseover = null;
		this.objExcellentButton.onmouseout = null;
		this.objExcellentButton.style.cursor = 'default';
	},
	startButtonAnimation: function(btn_flag){
		var myObj = this;
		new Rico.Effect.FadeTo($(myObj).objExcellentButton, 1, 300, 10, {
			complete:function(){
				$(myObj).objExcellentButton.style.backgroundImage = 'url(/common/images/bukumatch/pushed.gif)';
				new Rico.Effect.FadeTo($(myObj).objExcellentButton, 1, 500, 10, {
					complete:function(){
					    //
					}
				});
			}
		});
	},
	startCountupAnimation: function(res,btn_flag,update_flag){
		var myObj = this;
		new Rico.Effect.FadeTo($(myObj).objExcellentPoint, 0.01, 200, 10, {
		complete:function(){
		$(myObj).objExcellentPoint.innerHTML = parseInt($(myObj).objExcellentPoint.innerHTML) + 1 + 'イチオシ'; 
		new Rico.Effect.FadeTo($(myObj).objExcellentPoint, 1, 200, 10, {
				complete:function(){
					if(update_flag == 1){
						new Rico.Effect.FadeTo($(myObj).objBuryPoint, 0.01, 200, 10, {
							complete:function(){
							$(myObj).objBuryPoint.innerHTML = parseInt($(myObj).objBuryPoint.innerHTML) - 1;
							new Rico.Effect.FadeTo($(myObj).objBuryPoint, 1, 200, 10, {
								complete:function(){
									new Rico.Effect.FadeTo($(myObj).objPoint, 0.01, 300, 10, {
											complete:function(){
											$(myObj).objPoint.innerHTML = res; //表示ポイント数値
											//記事詳細ページのマルバツグラフ
											if($('graph_point')){
												$('graph_point').innerHTML = res;
											}
												new Rico.Effect.FadeTo($(myObj).objPoint, 1, 500, 10, {
													complete:function(){
														//
													}
												});
											}
										});
									}
								});
							}
						});
					}else{
						new Rico.Effect.FadeTo($(myObj).objPoint, 0.01, 300, 10, {
						complete:function(){
							$(myObj).objPoint.innerHTML = res; //表示ポイント数値
							//記事詳細ページのマルバツグラフ
							if($('graph_point')){
								$('graph_point').innerHTML = res;
							}
							new Rico.Effect.FadeTo($(myObj).objPoint, 1, 500, 10, {
									complete:function(){
									//
									}
							});
						}
						});
					}
				}    
			});
		}
		});
	}
}