//チャット画面を制御するイベントなど（リファクタリング対象）

var chat_anime_timer = new Object();

function initChat() {
//	setChatFrameSize();
//	$(window).resize(setChatFrameSize);
}

ajax.chatBefore = function () {
    
	if (getMovieName("chatroom") && $('#chatroom_input').size() > 0) {
//		console.log(getMovieName("chatroom"));
		getMovieName("chatroom").swfFunc('killConnection');
	}
}

ajax.chatComplete = function (data, book_id) {
    $('#mylist_ctrlpanel, #my_folder, #top_frame').hide();
	hideSecondFrame('fast');
	
	$('#chatroom_input, #chatcharaselect_input').hide();
//	$('#chatroom_input').hide();
	
    $('#chat_frame').show();
	
	//チャットエリア大きさ初期化
	setCenterFrameSize();
	
	//logoの選択中を「book」にする
	if (typeof(getMovieName("logo_navi").swfFunc) == 'undefined') {
		setTimeout(function(){
	        getMovieName("logo_navi").swfFunc('select', 'book');
	    }, 1000);
	} else {
		getMovieName("logo_navi").swfFunc('select', 'book');
	}
	
//	jsFunc('focusChatInput');
}

ajax.chatKickBefore = function () {
	$('#mylist_ctrlpanel').hide();
}

ajax.chatKickComplete = function (data) {
    showPopWindow();
	
	$('#kick_cancel').click(function(){
		clearPopWindow();
	});
}

//テストコード
function setChatFrameSize() {
	//チャットルームサイズコントロール
    var ratio_now =  ( $(window).width() - 200 ) / ( $(window).height() - 220 );
    var ratio = 1014 / 613;
    if (ratio_now > ratio) {
        var center_height = $(window).height() - 220;
        var center_width = ratio * center_height;
    } else {
        var center_width = $(window).width() - 200;
        var center_height = (1 / ratio) * center_width;
    }
    $('#chatroom').attr('height', center_height + 'px')
                  .attr('width', center_width + 'px');
    
    $('#chatroom_input').css('top', ( center_height - 30 )  + 'px')
                        .css('left', 200 + 'px');
}


function setChatDraggable() {
	$('div#chat_list div.chatting_user, div#chat_list div.chatting_user_boss').one('mouseover', function(){
//      $(this).css('top', $(this).position().top + 'px');
        $(this).draggable({ revert: 'valid', helper: 'clone'});
    });
}

flash.enterRoom = function (params) {
	
	$.post('/chat/chatlist', 
           {'book_id' : params[0]},
           function (data) {
                if (!data) return;
                $('div#chatting_panel').html(data);
				
				$('#user_list_hide p a').click(userListHandler);
				
                $('#chatting_panel .mute_icon').die().live('click', function(){
					
					var param = $(this).attr('id').split("_");
					if ($(this).hasClass('mute_icon_off')) {
						getMovieName("chatroom").swfFunc('cancelMute', param[1]);
                        $(this).removeClass('mute_icon_off')
                               .attr('src', '/img/icon_vol_on.gif');
					} else {
						getMovieName("chatroom").swfFunc('doMute', param[1]);
						$(this).addClass('mute_icon_off')
						       .attr('src', '/img/icon_vol_off.gif');
					}
				});
                
				if ( isIE7() ) {
					$('div#chatting_panel').show();
				} else {
					$('div#chatting_panel').slideDown('fast');
				}
				
                
                setChatDraggable();
           });
	
//    jsFunc('showChatInput');
}

flash.sendMessage = function () {
	var message = $.trim($('#chatroom_input input').val());
    if (message == '') return;
    
	$('#chatroom_input input').val('');
	
    getMovieName("chatroom").swfFunc('doMessage', message);
};

flash.setMessage = function (msg) {
	$('#chatroom_input input').val(msg[0]);
};

flash.addChatter = function (params) {
	params = params[0];
	var new_user_id = '';
	if (params.role_chara == 0) {
		new_user_id = params.user_id + '_0';
	} else {
		new_user_id = params.chara_id + '_1';
	}
	
	$.post('/chat/addchatter', params,
	       function (data) {
				if (params.user_id == params.owner) {
					$('#chatuser_' + new_user_id + ':first').remove();
                    $('#chatter_' + new_user_id + ':first').before(data).remove();
				} else if ($('#chatter_' + new_user_id).size() == 0) {
					$('#chat_list .panel_footer').before(data);
				} else {
				    $('#chatuser_' + new_user_id).remove();
					$('#chatter_' + new_user_id).before(data).remove();
				}
				setChatDraggable();
		   });
}

flash.removeChatter = function (params) {
	
	params = params[0];
	var new_user_id = '';
    if (params.role_chara == 0) {
        new_user_id = params.user_id + '_0';
    } else {
        new_user_id = params.chara_id + '_1';
    }
	
	if (params.user_id == params.owner) {
		$('#chatter_' + new_user_id + ' .tab_chatchara_ico').attr('class', 'tab_chatchara_ico_off');
		$('#chatter_' + new_user_id + ' .tab_chatchara_ico_off img').attr('src', '/img/icon_user_na.gif');
		$('#chatter_' + new_user_id + ' .mute_icon').remove();
		$('#chatter_' + new_user_id + ' .tab_chatchara_name span').remove();
		$('#chatter_' + new_user_id).attr('class', 'chatting_boss_offline');
	} else if (isNaN(params.user_id)){
        $('#mute_' + params.user_id).parent().remove();
	} else {
		$('#chatuser_' + new_user_id).remove();
        $('#chatter_' + new_user_id).remove();
	}
}

flash.showChatInput = function () {
	
	$('#chatroom_input').show();
    jsFunc('focusChatInput');
}


flash.focusChatInput = function () {
    
	$('#chatroom_input input').focus(function(){
		
		$(this).unbind('keyup').keyup(function(e){
	        if (e.which == 33) {          //PageUp 前ページ
                getMovieName("chatroom").swfFunc('prevPage');
            }
			else if (e.which == 34) {    //PageDown　次ページ
                getMovieName("chatroom").swfFunc('nextPage');
            }
			else if (e.shiftKey && e.which == 37) {    //shift + ←　前のフキダシ
                getMovieName("chatroom").swfFunc('prevBallonType');
            }
			else if (e.shiftKey && e.which == 39) {    //shift + →　次のフキダシ
                getMovieName("chatroom").swfFunc('nextBallonType');
            }
            else if (e.shiftKey && e.which == 38) {    //shift + ↑　前の文字サイズ
				getMovieName("chatroom").swfFunc('nextFontSize');
            }
            else if (e.shiftKey && e.which == 40) {    //shift + ↓　次の文字サイズ
				getMovieName("chatroom").swfFunc('prevFontSize');
            }
			else if (e.ctrlKey && e.which == 37) {    //ctrl + ←　左の表情
                getMovieName("chatroom").swfFunc('leftEmotion');
            }
            else if (e.ctrlKey && e.which == 39) {    //ctrl + →　右の表情
                getMovieName("chatroom").swfFunc('rightEmotion');
            }
            else if (e.ctrlKey && e.which == 38) {    //ctrl + ↑　上の表情
                getMovieName("chatroom").swfFunc('upEmotion');
            }
            else if (e.ctrlKey && e.which == 40) {    //ctrl + ↓　下の表情
                getMovieName("chatroom").swfFunc('downEmotion');
            }
			else if (e.which == 46) {                 //Delete
				getMovieName("chatroom").swfFunc('deleting');
			}
			else if (e.which == 8) {                  //Back Space
                getMovieName("chatroom").swfFunc('deleting');
            }
            else if (!isFirefox() && e.which != 13){  //入力中
                getMovieName("chatroom").swfFunc('typing', 'normal');
            }
	    });
		
		$(this).unbind('keypress').keypress(function(e){
			
			if(e.which == 13) {           //Enter
                jsFunc('sendMessage');
            }
			else if (e.which == 46) {    //Delete
            }
            else if (e.which == 8) {     //Back Space
            }
			else if (isFirefox()){       //入力中
                getMovieName("chatroom").swfFunc('typing', 'extend');
            }
		});
		
	}).focus();
	
}

flash.showHandleNameInput = function () {
	
	var input_select = $('#chatcharaselect_input input');
	
	$('#chatcharaselect_input').show();
	
	if ($('#chatcharaselect_input:visible').size() > 0) {
		var frame_width = $('#chat_frame').width();
        var frame_height = $('#chat_frame').height();
            
        var chara_input_top = (frame_height - CHARA_SELECTER_HEIGHT) / 2;
        var chara_input_left = (frame_width - CHARA_SELECTER_WIDTH) / 2
        
        $('#chatcharaselect_input').css('top',  (chara_input_top + 362) + 'px')
                                   .css('left', (chara_input_left + 341)+ 'px');
    }
	
	input_select.focus(function(){
        
        $(this).keypress(function(e){
			
            if(e.which == 13) {           //Enter
                var message = $.trim(input_select.val());
			    if (message == '') return;
			    
			    getMovieName("chatroom").swfFunc('doHandleName', message);
//			    input_select.val('');
            }
        });
		
		var empty_flag = true;
		$(this).keyup(function(e){
            if ($.trim(input_select.val()) != '' && empty_flag) {
				empty_flag = false;
				getMovieName("chatroom").swfFunc('handleNameInputing');
			}
            if (e.which == 8 && $.trim(input_select.val()) == '' && !empty_flag) {
                empty_flag = true;
				getMovieName("chatroom").swfFunc('handleNameEmpty');
            }
        });
        
    }).focus();
}

flash.hideHandleNameInput = function () {
    $('#chatcharaselect_input').hide();
}

flash.getHandleName = function () {
	return $.trim($('#chatcharaselect_input input').val());
}

flash.moveChatInput = function (data) {
//    $('#chatroom_input').css('top', -(frame_height - data[1]) + 'px')
//                        .css('left', data[0] + 'px');
}

flash.exitRoom = function () {
	$('div#chatting_panel').slideUp('fast', function() {
		$(this).find('.panel_content div:not(.panel_footer)').remove();
	});
	
	getMovieName("logo_navi").swfFunc('unactiveButton', 'book');
	getMovieName("logo_navi").swfFunc('select', 'top');
	$('#chat_frame').html('');
	
}

flash.chatHelp = function () {
	$.post('/help/index',{'subject' : 'helpchat'},
           function(data) {
                $('#pop_frame').html(data);
                showPopWindow();
           });
}

flash.chatInfoFromChat = function(data) {
	if ($('#chatting_owner_elem:visible').size() > 0) {
		data.push($('#chatting_owner_elem').html());
		flash.bookInfo(data);
	}
}

flash.showTypingAnime = function(data) {
	if (typeof(data) == 'undefined') return;
	data = data[0];
	
	var timer_key = data.user_id + '_' + data.role_chara;
	var timer_id;
	if (timer_key in chat_anime_timer) {
		timer_id = chat_anime_timer[timer_key];
		clearTimeout(timer_id);
	}
	
	var img_icon = $('#chatter_' + timer_key).children('.tab_chatchara_ico_on, .tab_chatchara_ico');
    img_icon.children('.chat_deleting').hide();
	img_icon.children('.chat_writing').show();
    
	var play_time;
	if (data.type == 'extend') {
		play_time = 2000;
	} else {
		play_time = 500;
	}
	
	var timer_id = setTimeout(function(){
		              img_icon.children('.chat_writing, .chat_deleting').hide();
	               }, play_time);
				   
	chat_anime_timer[timer_key] = timer_id;
}

flash.showDeletingAnime = function(data) {
    if (typeof(data) == 'undefined') return;
    data = data[0];
    
    var timer_key = data.user_id + '_' + data.role_chara;
    var timer_id;
    if (timer_key in chat_anime_timer) {
        timer_id = chat_anime_timer[timer_key];
        clearTimeout(timer_id);
    }
    
	var img_icon = $('#chatter_' + timer_key).children('.tab_chatchara_ico_on, .tab_chatchara_ico');
	
    img_icon.children('.chat_writing').hide();
    img_icon.children('.chat_deleting').show();
    
    var timer_id = setTimeout(function(){
                      img_icon.children('.chat_writing, .chat_deleting').hide();
                   }, 300);
                   
    chat_anime_timer[timer_key] = timer_id;
}

