if (typeof OmoiTwitter == 'undefined') OmoiTwitter = {};

new function(){
	var C = OmoiTwitter.Contents = {};
	
	C.Title = function(data){
		this.data = data;
		this.template = [
          '<div class="themeBox">',
            '<ul class="userIcn">',
              '<li>',
                '<a href="http://twitter.com/##userName##" class="external" title="##userName##のTwitterページ">',
                  '<img src="##userIcn##" width="48" height="48" alt="basix" />',
                '</a>',
              '</li>',
            '</ul>',
            '<div class="themeBg">',
               '<div class="themeTop">',
                '<div class="themeBottom">',
                  '<ul class="userName">',
                     '<li>',
                       '<a href="http://twitter.com/##userName##" class="external" title="##userName##のTwitterページ">##userName##</a>：',
                     '</li>',
                  '<!--//.userName--></ul>',
                  '<p>',
                    '<a href="##themeDetailURL##">##theme## (##answerNumber##)</a>',
                      '<img src="/img/icn_new.gif" alt="新着" width="17" height="9" />',
                    '</p>',
                  '<div class="subject">',
                    '<ul>',
                      '<li class="date">##date##</li>',
                      '<li class="fav"><a href="/favs/create/##statusID##" title="お気に入りに入れる">',
                        '<img src="/img/icn_fav.gif" alt="お気に入りに入れる" width="16" height="16" class="btn" /></a></li>',
                    '</ul>',
                  '<!--//.subject--></div>',
                  '<ul class="reply">',
                    '<li>',
                      '<a href="http://twitter.com/home?status=@##userName##%20&in_reply_to_status_id=##statusID##&in_reply_to=##userName##" title="アイデアを投稿する" class="external">',
                        '<img src="/img/icn_reply.gif" alt="おもいついったー！アイデアを投稿する" width="46" height="39" class="btn" />',
                      '</a>',
                    '</li>',
                  '</ul>',
                '<!--//.themrBottom--></div>',
              '<!--//.themeTop--></div>',
            '<!--//.themeBg--></div>',
          '<!--//.themeBox--></div>'
		].join('');
	}
	C.Title.prototype = {
		show : function(settings){
			var self = this;
			var user  = self.data.user;
			var theme = self.data.theme;
			
			this.template = this.template.replace( /\#\#(\w+)\#\#/g, function(){
				var key = arguments[1];
				
				if (key === 'userName') return user.name;
				if (key === 'userIcn') return user.icn;
				if (key === 'theme') return theme.status;
				if (key === 'answerNumber') return theme.answers;
                if (key === 'themeDetailURL') return '/q_statuses/detail/' + theme.id;
				if (key === 'statusID') return theme.id;
				if (key === 'date') return theme.date;
				
				return '';
			});
			
			settings.title_show.prepend(this.template);
			
			if ( typeof theme.date != 'string' ) {
				var date = new Date().getFullYear()
				theme.date = date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
			} else {
				theme.date = theme.date.split(' ')[0];
			}
//			settings.new_title_date.text( theme.date );
			
		}
	}
	
	
	OmoiTwitter.functions = (function(){
		return {
			// 設定情報やイベントを追加
			setup : function(settings, messages){
				this.settings = settings;
				this.messages = messages;
				
				this.add_title( settings.title_submit );
				//this.char_counter($(settings.title_text));
			},
			// お題投稿
			add_title : function(node){
				var self = this;
				var new_title = '';
				
				node.click(function(){
					new_title = self.settings.title_text.val();
                    if(!new_title) return;
                    self.settings.title_text.val('');
					
					$.ajax({
						url : '/api/tweet',
						type : 'POST',
						data: { 'text' : new_title },
						dataType: "json",
						cache: true,
						success : function( data, status ){
							if ( status != 'success' ) 
								return alert(self.messages.new_title_failed);
							new C.Title(data).show( self.settings );
                            var src = '/img/icn_fav.gif';
                            var src_o = src.replace(/\.\w+$/, $.Meca.hover.config.postfix + '$&');
                            $('div.themeWrap:eq(0) li.fav a').click(favImageToggle())
                                .find('img').hover(
                                    function() { this.src = src_o; },
                                    function() { this.src = src; }
                                );
                            var reply_src = '/img/icn_reply.gif';
                            var reply_src_o = reply_src.replace(/\.\w+$/, $.Meca.hover.config.postfix + '$&');
                            $('div.themeWrap:eq(0) ul.reply img').hover(
                                function() { this.src = reply_src_o; },
                                function() { this.src = reply_src; }
                            );
						}
					});
				});
			},
			// TODO 必要な機能かどうかが確定してから実装する
			char_counter : function(node){
				node.bind('blur keyup', function(){
					
				});
			}
		}
	
	})();

}

$(function(){
	// イベントをつける対象のセレクタを設定
	var settings = {
		title_text     : $('.formBox input:text'),
		title_submit   : $('.formBox input:image'),
		title_show     : $('div.themeWrap:eq(0)')
//		new_title_date : $('#topTheme ul.date li')
	}
	// アラート類のメッセージを定義
	var messages = {
		new_title_failed : 'お題の投稿に失敗しました。\n再度投稿しなおして下さい。'
	}
	
	OmoiTwitter.functions.setup(settings, messages);
    $('li.fav a').click(favImageToggle());

});

function favImageToggle() {
    var _toggle_image = function(self, src_new) {
        var src_new_o = src_new.replace(/\.\w+$/, $.Meca.hover.config.postfix + '$&');
        var img = $(self).find('img');
        img.unbind('mouseenter').unbind('mouseleave').attr('src', src_new);
        img.hover(
            function() { this.src = src_new_o; },
            function() { this.src = src_new; }
        );
        return false;
    };

    return function() {
        var self = this;
        var href = self.href;
        var src = '/img/icn_fav.gif';
        $.post(href, {}, function() {
            var is_create = /create/;
            if(is_create.exec(href)) {
                self.href = href.replace('create', 'destroy');
                var src_new = src.replace('.gif', '_on.gif');
                _toggle_image(self, src_new);
            }
            else {
                self.href = href.replace('destroy', 'create');
                _toggle_image(self, src);
            }   
            return false;
        })              
        return false;
    };
}
