$(document).ready(function() {
    TM_contentPreview();
});

function TM_contentPreview() {
    $("div.ton_post").each(function() {
        var c = $(this).html();
        var has_cut = false , num = 0 , tmp_l = 0 , tmp_c = c;
        var tmp_i = tmp_c.indexOf('<br>');
        while(tmp_i != -1) {
            num++;
            tmp_l += tmp_i + 4;
            if(num > 5) {
                var id = $(this).attr('id');
                id = id.replace('tm_content_entry_' , '');

                var nc = c.substring(0 , tmp_l - 4);
                $(this).html(nc)

                $('<span> &nbsp; </span><a href="#" title="查看全文">更多&darr;</a>').click(function() {
                    $('#tm_content_entry_' + id).hide().html( c ).slideDown('fast');
                    return false;
                }).appendTo($(this));
                break;
            }

            tmp_c = tmp_c.substring(tmp_i + 4);
            tmp_i = tmp_c.indexOf('<br>');
        }
    });
}

var TM_TMP = {};

function TM_doPost() {
	var content = $("#post_form_content").val();
	if(content == '最近有啥想法？' || $.trim(content).length == 0) {
		alert('还没有填写内容');
		return false;
	}

	if($("#post_form_edit_btn").length > 0) return TM_doEdit($("#post_form_edit_btn").attr("rel"));

	var cb = function(d) {
		inputEnable('#post_form_btn' , {'text':'发表' , 'className':'bt_tx_s_disable'});
		if(d.error) {
			alert(d.error);
			return;
		}

		$("#post_form_content").val('');
		$("#list_post").prepend('<li id="tm_list_' + d.cid + '" style="display:none"><div class="line"><div id="tm_content_' + d.cid + '" class="tx_post"><div class="ton_post">' + d.content + '</div><p class="info_post"><span class="time">' + d.time + '</span> <a href="#" onclick="TM_doDel(' + d.cid + '); return false;">删除</a></p></div></div></li>');
		$("#tm_list_" + d.cid).fadeIn();
	};
	$.post('index.php?c=post&a=dopost' , {"content":content} , cb , "json");
	inputDisable('#post_form_btn' , {'text':'小等...' , 'className':'bt_tx_s_disable'});
}

/**
 * 修改一篇文章
 */
function TM_edit(cid) {
	var cb = function(d) {
		if(d.error) {
			alert(d.error);
			return;
		}

		$('#post_form_content').val( d.content ).select();
		$(document).scrollTo( '#post_form' , 500 );

		// 添加取消按钮
		$('#post_form_edit_btn').remove();
		$('#post_form_btn').before('<a rel="' + cid + '" id="post_form_edit_btn" href="#" onclick="TM_cancelEdit(); return false" style="position:absolute; right:120px; top:12px; width:30px;">取消</a>');
	};
	$.post('index.php?c=post&a=getone' , {"cid":cid} , cb , "json");
}

function TM_doEdit(cid) {
	var cb = function(d) {
		inputEnable('#post_form_btn' , {'text':'发表' , 'className':'bt_tx_s_disable'});
		if(d.error) {
			alert(d.error);
			return;
		}

		$("#post_form_content").val('');
		$('#post_form_edit_btn').remove();
		$("#tm_content_entry_" + cid).html(d.content);
		$(document).scrollTo( '#tm_content_' + cid , 500 );
	};

	var content = $("#post_form_content").val();
	$.post('index.php?c=post&a=doedit' , {"content":content , "cid":cid} , cb , "json");
	inputDisable('#post_form_btn' , {'text':'小等...' , 'className':'bt_tx_s_disable'});
}

function TM_cancelEdit() {
	$('#post_form_edit_btn').remove();
	$('#post_form_content').val('');
}

function TM_doDelComment(cid , cmid) {
	var cb = function(d) {
		if(d.error) {
			alert(d.error);
		} else {
			$("#comment_" + cmid).fadeOut('normal' , function(){ $("#comment_" + cmid).remove(); });
		}
	};
	$.post('index.php?c=comment&a=dodel' , {"cid":cid , "cmid":cmid} , cb , "json");
}

/**
 * 删除一篇文章
 *
 * @param <int> cid 文章id
 */
function TM_doDel(cid) {
	var cb = function(d) {
		if(d.error) {
			alert(d.error);
		} else {
			$("#tm_list_" + cid).fadeOut('normal' , function(){ $("#tm_list_" + cid).remove(); });
		}
	};
	$.post('index.php?c=post&a=dodel' , {"cid":cid} , cb , "json");
}

/**
 * 读取评论
 */
function TM_loadComments(cid , force) {
	if(force) $('#tm_comment_' + cid + '_other').html('<img src="' + TM_VAR.site_url + '/core/static/images/loading.gif" />');

	// 先自动生成所需div
	if(!force) {
		var _tc = $("#tm_comment_" + cid);
		if(_tc.length > 0) {
			if(_tc.is(':visible')) {
				_tc.slideUp();
				$('#tm_arrow_' + cid).html('');
				if( parseInt($('#tm_commentnum_' + cid).text()) != 0 ) $('#tm_commentnum_' + cid + '_wrap').show();
			} else {
				_tc.slideDown();
				$('#tm_arrow_' + cid).html('&uarr;');
				$('#tm_commentnum_' + cid + '_wrap').hide();
			}
			return;
		} else {
			$("#tm_content_" + cid).after(
				'<div class="comment" id="tm_comment_' + cid + '" style="display:none"><span class="icon_angel"></span>' +
					'<div class="item item_btm"><form id="tm_comment_form_' + cid + '" onsubmit="TM_doComment(' + cid + '); return false">' +
						'<textarea name="comment" id="tm_comment_' + cid + '_content" onkeydown="TM_keyDown(event , $(\'#tm_comment_' + cid + '_btn\'))" onfocus="TM_commentInputFocus(' + cid + ')" cols="" rows="" class="reply c_tx">评论..</textarea>' +
						'<div class="ctrl" id="tm_comment_' + cid + '_ctrl" style="display:none"><input id="tm_comment_' + cid + '_name" name="author" onfocus="if(this.value==\'姓名..\') this.value=\'\';" class="name" value="姓名.." /><button id="tm_comment_' + cid + '_btn" type="submit" class="bt_tx">发表</button></div>' +
					'</form></div>' +
				'</div>');
		}
	}

	var _tc = $("#tm_comment_" + cid);	// 再取一次，因为第一次没取到

	var cb = function(d) {
		if(d.error) {
			alert(d.error);
			return;
		}

		if(force) $('#tm_comment_' + cid + '_other').remove();

		_tc.hide();
		if(d && d.data && d.data.length > 0) {
			var _h = [];
			var limit = (force) ? d.data.length - $('#tm_comment_' + cid + ' > div.item').length + 1 : d.data.length;
			for(var i = 0 ; i < limit ; i++) {
				var c = d.data[i];
				_h.push('<div class="item" id="comment_' + c.cmid + '"><p><span class="name">' + c.author + '</span>：' + c.content + '<span class="time">' + c.time + '</span>' + (d.isLogin ? ' <a href="#" onclick="TM_doDelComment(' + cid + ',' + c.cmid + ');return false;">删除</a>' : '') + '</p></div>');
			}
			_tc.prepend(_h.join(''));
		}

		_tc.show();
	};
	$.post('index.php?c=comment&a=get' , {"cid":cid} , cb , "json");
}

function TM_commentInputFocus(cid) {
	var _c = $('#tm_comment_' + cid + '_content') , _n = $('#tm_comment_' + cid + '_name');
	_c.removeClass('reply').addClass('reply_focus');
	$('#tm_comment_' + cid + '_ctrl').show();

	if(_c.val() == '评论..') _c.val('');

	// 自动填写名字
	if(_n.val() == '姓名..' || _n.val() == '') {
		var cname = $.cookie('tmcname');
		if(cname) _n.val(cname);
	}
}

function TM_commentInputBlur(cid) {
	var t = $('#tm_comment_' + cid + '_content');
	t.addClass('reply').removeClass('reply_focus');
	$('#tm_comment_' + cid + '_ctrl').hide();

	t.val('评论..');
}

/**
 * 评论
 */
function TM_doComment(cid) {
	var _content = $('#tm_comment_' + cid + '_content') , _name = $('#tm_comment_' + cid + '_name');
	if(_content.val() == '' || _content.val() == '评论..') {
		_content.addClass('reply_error').focus();
		return;
	}

	if(_name.val() == '' || _name.val() == '姓名..') {
		_name.addClass('reply_error').focus();
		return;
	}

	_content.removeClass('reply_error');
	_name.removeClass('reply_error');

	var data = $('#tm_comment_form_' + cid).serialize();

	var cb = function(d) {
		inputEnable('#tm_comment_' + cid + '_btn' , {'text':'发表'});

		if(d.error) {
			alert(d.error);
			return;
		}

		// 记 cookie
		$.cookie('tmcname' , _name.val() , {expires: 30});

		$('#tm_comment_' + cid + ' > div.item:last').before('<div class="item"><p><span class="name">' + d.author + '</span>：' + d.content + '<span class="time">' + d.time + '</span></p></div>');
		_content.val('');
		_name.val('');

		TM_commentInputBlur(cid);
		if($('#tm_commentnum_' + cid).length > 0) $('#tm_commentnum_' + cid).text( parseInt($('#tm_commentnum_' + cid).text()) + 1 );
	};

	$.post('index.php?c=comment&a=doadd' , data + '&cid=' + cid , cb , "json");
	inputDisable('#tm_comment_' + cid + '_btn' , {'text':'小等...'});
}

/**
 * 监听按键。 Ctrl+Enter 或 Alt+S 提交
 */
function TM_keyDown(e , jq) {
	if((e.ctrlKey && e.keyCode == 13) || (e.altKey && e.keyCode == 73)) {
		jq.click();
	}
}

/**
 * 登陆
 */
function TM_dologin() {
	var data = $("#login_form").serialize();

	var cb = function(d) {
		if(d.error) {
			alert(d.error);
			return;
		}

		window.location.href = window.location.href;
	};
	$.post('index.php?c=user&a=login' , data , cb , "json");
}

/**
 * 退出登陆
 */
function TM_dologout() {
	var cb = function() {
		window.location.href = 'index.php';
	};

	$.post('index.php?c=user&a=logout' , {"logout":1} , cb , "json");
}

/**
 * 弹出登录框
 */
function TM_showLoginPop() {
	$('#enter_panel').fadeOut('fast');
	$('#login_pop').slideDown(100);
	$('#login_name').select();
}

/**
 * 关闭登录框
 */
function TM_hideLoginPop() {
	$('#login_pop').slideUp(100, function(){ $('#enter_panel').fadeIn(); });	
}


function inputDisable(dis , option) {
	var op = {'className' : 'bt_tx_disable'};
	$.extend(op , option);

	dis = dis ? dis : TM_TMP.input_dis;
	if(dis) $(dis).addClass(op['className']).attr("disabled" , true);
	if(op.text) $(dis).text(op.text);
}

function inputEnable(dis , option) {
	var op = {'className' : 'bt_tx_disable'};
	$.extend(op , option);

	dis = dis ? dis : TM_TMP.input_dis;
	if(dis) {
		$(dis).removeClass(op['className']).removeAttr("disabled");
		TM_TMP.input_dis = null;
		if(op.text) $(dis).text(op.text);
	}
}

/**
 * Tabbmore 编辑器
 */
var TM_editor = (function (){
	var inner = {
		/**
		 * 插入链接
		 */
		insertLink : function() {
			var text = $('#op_fun_link_text').val() ,
				link = $('#op_fun_link_value').val();

			if(link.length == 0) {
				inner.tips('没有填写链接地址');
				return false;
			}

			// var selection = $('#post_form_content').getSelection();

			link = text.length == 0 ? '[url]' + link + '[/url]' : '[url=' + link + ']' + text + '[/url]';
			inner.insertText(link);

			TM_editor.toggleOpFun();
		},

		/**
		 * 插入图片
		 */
		insertImage : function(image) {
			if(!image) image= $('#op_fun_image_url').val();

			if(image.length == 0) {
				inner.tips('没有填写图片地址');
				return false;
			}

			image = '[img]' + image + '[/img]';
			inner.insertText(image);

			TM_editor.toggleOpFun();
		},

		/**
		 * 上传图片
		 */
		uploadImage : {
			init : function () {
				if(inner.swfu) return;
				var jscb = function() {
					inner.swfu = new SWFUpload({
						upload_url : "index.php?c=post&a=uploadimage",
						flash_url : "core/static/swfupload/Flash/swfupload.swf",
						button_placeholder_id : "op_fun_flash_upload",
						button_width : 40,
						button_height: 21,
						button_text : "上传",
						file_types : "*.jpg;*.gif;*.png",
						file_dialog_complete_handler : TM_editor.uploadImage.start,
						upload_progress_handler : TM_editor.uploadImage.progress,
						upload_success_handler : TM_editor.uploadImage.success,
						// upload_complete_handler : TM_editor.uploadImage.complete,

						custom_settings : {
						// 	tdPercentUploaded : document.getElementById("tdPercentUploaded")
						}
					});

				};

				$.getScript("core/static/swfupload/swfupload.js" , jscb);
			},

			start : function() {
				$("#op_fun_flash_upload_percent").html("0%");
				this.startUpload();
			},

			progress : function (file, bytesLoaded, bytesTotal) {
				try {
					// alert(bytesLoaded);
					//alert(bytesTotal);
					// this.customSettings.progressCount++;
					$("#op_fun_flash_upload_percent").html(parseInt(bytesLoaded / bytesTotal * 100) + "%");
				} catch (ex) {
					alert(ex);
				}
			},

			success : function (file , server_data) {
				$("#op_fun_flash_upload_percent").html("");

				eval('var d = ' + server_data + ";");

				if(d.error) {
					alert(d.error);
					return;
				}

				TM_editor.toggleOpFun();
				inner.insertImage(d.image);
			}
		},

		/**
		 * 在编辑器中插入图片
		 */
		insertText : function(str , isReplace) {
			// 文字插入
			if(!isReplace) {
				var selection = $('#post_form_content').getSelection();
				str = selection.text + str;
			}

			$('#post_form_content').replaceSelection(str);
		},

		toggleOpFun : function(op_id) {
			if(!op_id) {
				$('#op_wrap > div.op_fun').slice(1).hide();
				$('#op_fun_index').show();
				return;
			}

			$('#op_fun_index').hide();
			$('#' + op_id).show();
		},

		/**
		 * 提示文字，5秒后自动消失
		 */
		tips : function(str) {
			$('#op_fun_tips').html(str).show();
			if(inner.tipsHideTimerID) clearTimeout(inner.tipsHideTimerID);
			inner.tipsHideTimerID = setTimeout(function() { $('#op_fun_tips').fadeOut(); } , 3000);
		}
	};

	return inner;
})();


