/**
 *
 * AlltosunCMS - comment.js 评论模块JS文件
 * @requires jQuery v1.3.2+
 * @requires jQueryui v1.7.2+
 * @requires Comment Widget
 * @requires Login Popup
 *
 * Copyright (c) 2009-2010 Alltosun.INC - http://www.alltosun.com
 * Date: 2010/02/09
 * @author qih && gaojj
 */
$(function(){
	var commentWidget = $("#commentWidget"); //Namespace like
	// 字数统计
	var maxLength = 10000;
	//@TODO 1.4.1 live可以传多个event
	$(".writeBox", commentWidget).live('keydown', function(e){
		var writeBox = $(this);
		//添加当点击Ctrl+Enter时触发提交时间
		if (e.ctrlKey && e.which == 13 || e.which == 10) {
	        writeBox.nextAll('.btns').children('.submit').click();
		} else if (e.shiftKey && e.which==13 || e.which == 10) {
	    	writeBox.nextAll('.btns').children('.submit').click();
		}
		$(this).nextAll(".btns").children().children(".writeNum").html(10000-writeBox.val().length);
	 	if (writeBox.val().length > maxLength) {
	 		writeBox.val(writeBox.val().substring(0, maxLength));
		}
	}).live('keyup', function(){
		var writeBox = $(this);
			writeBox.nextAll(".btns").children().children(".writeNum").html(10000-writeBox.val().length);
		if (writeBox.val().length > maxLength) {
			writeBox.val(writeBox.val().substring(0, maxLength));
		}
	});
    // 回复
    $(".reply_link", commentWidget).live('click', function(){
        var replyForm = $(this).nextAll('form');
        // 如果已有回复框，则直接做显示隐藏切换
        if (replyForm.children('textarea').length>0) {
        	if(replyForm.css('display') == 'none') {
              replyForm.slideDown();
              return true;
        	}
         	replyForm.slideUp();
     	    return true;
  	    }
        // 没有回复框，产生HTML回复框
        var parent_id = $(this).prev("input").val();
        var rHTML = '<textarea name="content" class="writeBox" ></textarea>';
        	rHTML += '<input type="hidden" class="parent_id" value="'+parent_id+'" />';
        	rHTML += '<div class="btns">';
        	if (user_name) {
        	rHTML += '<span class="contactBox" style="float:right;">发表人:<input type="text" class="contact" value="'+user_name+'" /></span>';
        	} else {
        	rHTML += '<span class="contactBox" style="float:right;">发表人:<input type="text" class="contact" value="匿名" /></span>';
        	}
        	rHTML += '<input type="button" class="submit" value="发表" />&nbsp;&nbsp;<input type="button" class="cancel" value="取消" />';
        	rHTML += '<span class="number">[按Ctrl+Enter键快速发表]</span>';
        	//rHTML += '<span class="number">还允许输入 <label class="writeNum">10000</label> 个字符</span>';
    		rHTML += '</div>';
		var rElem = jQuery(rHTML);
		replyForm.hide().append(rElem).slideDown();
		function submitForm() {
	    	$('.reply .btns').children('.submit').trigger('click');
	    }
		var uploadUrl = "/handler/file_uploader&source=xheditor&immediate=1&file_field=filedata&res_type=comment&type=middle";
		if (typeof(uploadUrl) != 'undefined') {
		  loadJS(site_url+'/js/xheditor/xheditor-zh-cn.js?v=1.0.0-final', function(){$('.writeBox').xheditor({height:150, tools:'simple',beforeSetSource:ubb2html,beforeGetSource:html2ubb,upImgUrl:uploadUrl,upImgExt:"jpg,jpeg,gif,png",emots:{qqpet:{name:'pet',count:11,width:50,height:50,line:5},tusiji:{name:'兔斯基',count:22,width:50,height:50,line:5},boatday:{name:'七夕',count:7,width:50,height:50,line:5},hard:{name:'monkey',count:20,width:50,height:50,line:5}}, shortcuts:{'ctrl+enter':submitForm}});});
		} else {
		  loadJS(site_url+'/js/xheditor/xheditor-zh-cn.js?v=1.0.0-final', function(){$('.writeBox').xheditor({height:150, tools:'simple',beforeSetSource:ubb2html,beforeGetSource:html2ubb,emots:{qqpet:{name:'pet',count:11,width:50,height:50,line:5},tusiji:{name:'兔斯基',count:22,width:50,height:50,line:5},boatday:{name:'七夕',count:7,width:50,height:50,line:5},hard:{name:'monkey',count:20,width:50,height:50,line:5}}, shortcuts:{'ctrl+enter':submitForm}});});
		}
    });
    // 回复取消
    $(".cancel", commentWidget).live('click',function(){
        var replyForm = $(this).closest('form');
        replyForm.slideUp();
    });
    // 发表
    $(".submit", commentWidget).live("click",function(){
        /*if (user_id == "") {
            //没有登录 * require loginDialog in Login Popup
        	loginDialog.show();
            return;
        }*/
        var clickTarget = $(this);
        var parent_id   = clickTarget.parent().prevAll(".parent_id").val();
        var contentObj  = clickTarget.parent().prevAll(".writeBox");
        var content = contentObj.val();
        if (clickTarget.siblings(".contactBox").length != 0) {
        	// 回复的contact
        	var contact = clickTarget.siblings(".contactBox").children('.contact').val();
        } else {
        	var contact = clickTarget.parent('.btns').prevAll('.contactBox').children('.contact').val();
        }
        var privacy = 1;
        if (clickTarget.parent('.btns').prevAll('.contactBox').children('.privacy:checked').length != 0) {
        	// 悄悄话
        	privacy = clickTarget.parent('.btns').prevAll('.contactBox').children('.privacy:checked').val();
        }
        if ($.trim(content) == '') {
        	alert('内容不能为空!');
        	//contentObj.effect("highlight", { color: '#FCD3EE' }, 300).effect("highlight", { color: '#FCD3EE' }, 300);
            return;
        }
        clickTarget.val("保存中...").attr("disabled", "disabled");
        var postData = {
                "res_id"    : res_id,
                "res_type"  : res_type,
                "content"   : content,
                "contact"	: contact,
                "parent_id" : parent_id,
                "privacy"	: privacy
                };
        $.post(site_url+"/comment/save", postData, function(json){
        	clickTarget.val("发表").attr("disabled", "");
            if (json.info != 'ok') {
                alert(json.info);
                return;
            }

            // 发表成功，清空textarea，恢复字数统计
            contentObj.val("");
            contentObj.nextAll(".btns").children().children(".writeNum").html('10000');

            var comment = json.comment;
            if (json.comment.status != 1) {
                alert('您发表的评论正在审核中，请稍后查看。');
                return;
            }
            // 发表时间
            var now = new Date();
            var time = $.datepicker.formatDate('yy-mm-dd', now)+' '+now.getHours()+':'+now.getMinutes();
            var cHTML = '';
            if (parent_id == 0) {
               // 新评论后产生的HTML
               cHTML += '<div class="item clearfix commentList">';
               cHTML += '<div class="thumb"><div class="avatar">';
               // @FIXME user_avatar
               if (user_id) {
               cHTML += '<a href="'+site_url+'/user/'+user_id+'"><img width="45" height="45" src="'+site_url+'/'+user_avatar+'"></a>';
               } else {
               cHTML += '<img width="45" height="45" src="'+site_url+'/images/default/avatar.gif">';
               }
               cHTML += '</div></div>';
               cHTML += '<div class="comt"><div class="name">';
               // @FIXME user_name link
               if (user_id) {
               cHTML += '<a href="'+site_url+'/user/'+user_id+'">' + user_name + '</a> 说道：';
               } else if (contact) {
               //cHTML +=  comment.treat_ip + ' 说道：';
               cHTML +=  contact + ' 说道：';
               } else {
               cHTML += '匿名 说道:';
               }
               cHTML += '<div class="time">' + time +'<a id="comment' + comment.id + '" class="remove" href="javascript:void(0);">删除</a></div></div>';
               cHTML += '<div class="desc">' + comment.content + '</div>';
               cHTML += '<div class="reply"><div class="links">';
               cHTML += '<input type="hidden" name="parent_id" value="' + comment.id + '" />';
               cHTML += '<a class="reply_link" href="javascript:void(0);">回复</a>  ';
//             cHTML += '<a id="comment' + comment.id + '" class="remove" href="javascript:void(0);">删除</a>';
               cHTML += '<form></form>';
               cHTML += '</div></div></div></div>';
               var cElem = jQuery(cHTML);
               $(".commentList:first").after(cElem);
               cElem.effect("highlight", {}, 2000);
               return true;
            }
            // 新回复后产生的HTML
            cHTML += '<div class="reComt">';
            cHTML += '<div class="name">';
            cHTML += '<span class="time">' + time;
            cHTML += '  <a id="comment' + comment.id + '" class="remove" href="javascript:void(0);">删除</a>';
            cHTML += '</span>';
            // @FIXME user_avatar
            if (user_id) {
            cHTML += '<a href="'+site_url+'/user/'+user_id+'"><img width="16" height="16" alt="" src="'+site_url+'/'+user_avatar+'"></a>';
            cHTML += ' <a href="'+site_url+'/user/'+user_id+'">' + user_name + '</a> 回复：';
            } else {
        	cHTML += '<img width="16" height="16" alt="" src="'+site_url+'/images/default/avatar.gif" />';
            if (contact) {
            	cHTML +=   contact + ' 回复：';
            } else {
            	cHTML += '匿名    回复:';
            }
            }
            cHTML += '</div>';
            cHTML += '<div class="desc">' + comment.content + '</div>';
            cHTML += '</div>';
            var cElem = jQuery(cHTML);
            clickTarget.closest(".reply").before(cElem);
            cElem.effect("highlight", {}, 2000);
            clickTarget.closest("form").slideUp();
            return true;
        }, "json");
    });

    // 删除
    $(".remove", commentWidget).live('click', function(){
        if (!confirm("确定要删除该条评论？")) {
			return;
		}
        var id = $(this).attr("id").substring(7);
        var clickedObj = $(this);
        $.getJSON(site_url+"/comment/delete&id="+id, function(json){
            if (json.info != 'ok') {
                alert(json.info);
                return;
            }
            clickedObj.closest('.reComt, .item').fadeOut("slow", function(){
                $(this).remove();
            });
        });
    });
});
function htmlSpecialChars(str){
//	str = str.replace(/</g, '&lt;');
//	str = str.replace(/>/g, '&gt;');
	return str;
}
function loadJS(url,callback,charset)
{
	var script = document.createElement('script');
	script.onload = script.onreadystatechange = function ()
	{
		if (script && script.readyState && /^(?!(?:loaded|complete)$)/.test(script.readyState)) {
			return;
		}
		script.onload = script.onreadystatechange = null;
		script.src = '';
		script.parentNode.removeChild(script);
		script = null;
		if(callback){callback();}
	};
	script.charset=charset || document.charset || document.characterSet;
	script.src = url;
	try {document.getElementsByTagName("head")[0].appendChild(script);} catch (e) {}
}

