﻿/// <reference path="mootoolsIntellisense.js" />
/// <reference path="Tips.js" />
/// <reference path="Utils.js" />
/**
* PostMessage.js
* Author: Fdream
*/

// Message Class
function Comment(){
    this.logId = 0;
    this.memName = '';
    this.memPass = '';
    this.memCode = '';
    this.saveMem = '';
    this.content = '';
    
    // check the value
    this.checkInstance = function(){
        var errMsg = '';
        if(this.memName.trim() == ''){
            errMsg = '用户名不能为空！';
            return errMsg;
        }
        if(this.memCode.trim() == ''){
            errMsg = '验证码不能为空！';
            return errMsg;
        }
        if(this.content.trim() == ''){
            errMsg = '评论内容不能为空！';
            return errMsg;
        }
        return true;
    }
}

// get form
function getForm(){
    var comm = new Comment();
    comm.logId = $('log_Id').get('value');
    comm.memName = $('comm_memName').get('value').trim();
    comm.memCode = $('comm_code').get('value').trim();
    comm.content = $('message').get('value').trim();
    if($('comm_memPassword') != null){
        comm.memPass = $('comm_memPassword').get('value').trim();
    }
    if($('comm_saveMem') != null){
        comm.saveMem = $('comm_saveMem').get('value');
    }
    
    return comm;
}

// post a comment
function postComment(e){
    $('messageSubmit').disabled = true;
	postSubmited = true;
    var msg = getForm();
    var result = msg.checkInstance();
    if(result != true){
        Tip.showBeside($(e.target), Tip.tip(result));
    }
    else{
        submitComment(msg);
    }
    $('messageSubmit').disabled = false;
    postSubmited = false;
}

// submit a comment
function submitComment(msg){
    var req = new Request({url:commPostUrl, method:'post'}).send(Utils.Hash.toQueryString(msg));
    req.onFailure = function(r){
        Tip.showBeside($('messageSubmit'), Tip.tip('非常抱歉，提交评论失败！'));
    }
    req.onSuccess = function(responseText, responseXML){
        var xmlDoc = responseXML;
        var succeed = xmlDoc.getElementsByTagName('succeed')[0].childNodes[0].nodeValue;
        var message = xmlDoc.getElementsByTagName('message')[0].childNodes[0].nodeValue;
        var login = xmlDoc.getElementsByTagName('login')[0].childNodes[0].nodeValue;
        // if succeed
        if(succeed.toLowerCase() == 'true')
        {
            var commentNode = xmlDoc.getElementsByTagName('comment')[0];
            var author = commentNode.getElementsByTagName('author')[0].childNodes[0].nodeValue;
            var time = commentNode.getElementsByTagName('time')[0].childNodes[0].nodeValue;
            var content = commentNode.getElementsByTagName('content')[0].childNodes[0].nodeValue;
            var contentSrc = commentNode.getElementsByTagName('contentsrc')[0].childNodes[0].nodeValue;
            DisplayMessage(author, time, content, contentSrc);
            message = message + '<p><b style="cursor:pointer;color:#000;" onclick="scroll.toElement($(\'comm_' + commentCount +'\'));">确定</b></p>';
        }
        // if login
        if(login.toLowerCase() == 'true')
        {
            $('comm_memName').set('readOnly', true);
            $('comm_register').destroy();
        }
        $('messageSubmit').disabled = false;
        postSubmited = false;
        
        Tip.showBeside($('messageSubmit'), Tip.tip(message));
    }
    Tip.showBeside($('messageSubmit'), 0, Tip.tip('正在为您提交评论，请稍后...'));
}

// display the message
function DisplayMessage(author, time, content, contentSrc){
    // 0: serial no.
    // 1: blog root url
    // 2: author
    // 3: time
    // 4: author encoded
    // 5: content encoded
    // 6: contend source
    var htmlString = ['<div id="comm_{0}" class="comment_head">',
    '<a name="commmark_{0}"></a>',
    '<img src="{1}images/icon_quote.gif" alt="引用这个评论" style="cursor:hand;" onclick="blogquote(\'quote_{0}\',\'{2}\',\'{3}\')" />&nbsp;',
    '<b><a href="{1}member/{4}.aspx">{2}</a> 于 {3} 发表评论：</b>',
    '</div>',
    '<div class="comment_main">{5}</div>',
    '<span class="comment_quote" id="quote_{0}">{6}</span>'].join('');
	htmlString = htmlString.replace(new RegExp('\\{0\\}', 'g'), ++commentCount);
	htmlString = htmlString.replace(new RegExp('\\{1\\}', 'g'), blogUrl);
	htmlString = htmlString.replace(new RegExp('\\{2\\}', 'g'), author);
	htmlString = htmlString.replace(new RegExp('\\{3\\}', 'g'), time);
	htmlString = htmlString.replace(new RegExp('\\{4\\}', 'g'), encodeURIComponent(author));
	htmlString = htmlString.replace(new RegExp('\\{5\\}', 'g'), content);
	htmlString = htmlString.replace(new RegExp('\\{6\\}', 'g'), contentSrc);
	
	var newComment = new Element('div', {
	    'class': 'comment',
	    'html': htmlString
	    }).inject($('comm_0'), 'after');
	    
    if(commentCount > commentMax)
    {
        $('comm_' + (commentCount - commentMax)).destroy();
    }
    
    $('message').set('value', '');
    $('message').set('class', 'normal');
    $('comm_code').set('value', '');
    $('codeImage').src = blogUrl + 'ValidateCode.aspx?sid=' + $('log_Id').value + '&' + Math.random();
}

// is submitting
var postSubmited = false;
function CtrlEnter(evt) 
{
	if(postSubmited == false && (evt.ctrlKey && evt.keyCode == 13) || (evt.altKey && evt.keyCode == 83)) 
	{
		postComment(evt);
	}
}

var scroll = {toElement: function(){return;}};
window.addEvent('domready', function(){
    $('messageSubmit').addEvent('click', function(e){
        postComment(e);
        return false;
    });
    
    $('comm_form').addEvent('submit', function(e){
        postComment(e);
        return false;
    });
    
    initTips();

    scroll = new Fx.Scroll($(document), {
	    wait: false,
	    duration: 1000,
	    transition: Fx.Transitions.Quad.easeInOut
    });
    
    $('wanttosay').addEvent('click', function(){
        scroll.toElement($(document).getElement('a[name=post_comment]'));
        return false;
    });
});