




// vote 
if(typeof(Vote)=='undefined'){
  var Vote = {};
}
Vote.Count = Class.create();
Vote.Count.prototype = {
	 initialize: function(container,params) {
	    this.setParams(params);
	    this.container = container;
	 	this.start();
	 },
	 setParams: function(params){
	    this.params = {
	      articleId:  '',
	      action:'getVoteCount'
	    }
	    Object.extend(this.params, params || {});
	 },
	 start:function(){
		var url =  "/AJAXVOTE.HTM?rnd=" + new Date().getTime();
		new Ajax.Request(url,{method: 'post', parameters:this.params, onComplete:this.renderVoteCount.bind(this)});
	 },
	 renderVoteCount:function(req) {
			var reqText = req.responseText;
			if(reqText.match(/^\d+$/)){
				$(this.container).innerHTML = reqText;
			}else{
				$(this.container) = 0;
			}
    }   
}

Vote.Cast = Class.create();
Vote.Cast.prototype =  {
	 initialize: function(container,params) {
	    this.setParams(params);
	    this.container = container;
	    this.start();
	 },
	 setParams:function(params){
	    this.params = {
	      articleId:  ''
	    }
	   Object.extend(this.params, params || {});
	 },
	 start:function (){	
		var url = "/AJAXVOTE_" + this.params.articleId + ".HTM?rnd=" + new Date().getTime();
	    new Ajax.Request(url,{method: 'post',onComplete:this.renderVoteCount.bind(this)} );
	},
	renderVoteCount:function(req) {
			var reqText = req.responseText;
			var array = reqText.split(",");
			if(array.length < 2) {
				return;
			} 
			var status = array[0];
			if(status == "alreadyVoted"){
				alert('You have already voted for this article.');
			}else{
			    alert('You have successfully voted for this article.');
	        }
			var count = array[1];
			if(count.match(/^\d+$/)){
				$(this.container).innerHTML = count;
			}else{
				$(this.container) = 0;
			}
    }   
}

function voteRequest(container,params){
   new Vote.Cast(container,params);
   return ;
}

var XMLHelper = {
  	 getElement:function(oNode,tagName){
  	    if (oNode === undefined) return null;
	    if (oNode === null) return null;
	    if (tagName === null) return null;
	 	return oNode.getElementsByTagName(tagName);
	 },
	 getFirstElement:function(oNode,tagName){	   
	    var obj = this.getElement(oNode,tagName);
	    if (obj === undefined) return null;
	    if (obj === null) return null;
	 	return this.getElement(oNode,tagName)[0];
	 },
	 getElementFirstValue:function(oNode,tagName){
	 	var obj = this.getFirstElement(oNode,tagName);
	 	if (obj!=null){
		    var val = obj.firstChild.data;
		    return (val==null)? '': val;
	    }
	},toHash:function(oNode){
	   var nodes = oNode.childNodes;
	   var hash = new $H();
	   for(var i=0; i < nodes.length ; i++){
	     var pair = [key, value];
	     var key = nodes.item(i).nodeName;
	     var value = this.getElementFirstValue(oNode,nodes.item(i).nodeName);
	     hash[key] = value;
   	   }
 	   //alert(hash.inspect());
	   return hash;
	}
}

// comment
if(typeof(Comment)=='undefined'){
  var Comment = {};
}

Comment.List = Class.create();
Comment.List.prototype =  {
	 initialize: function(container,params) {
	    this.setParams(params);
	    this.container = container;
	    if(this.params.isStart){
	      this.start();
	    }
	 },
	 setParams:function(params){
	    this.params = {
	      objectId: '',
	      objectType:  'ARTICLE',
	      numberResults: '5',
	      requestType: '',
	      title: '',
	      isStart: true,
	      action:'list',
	      topContainer:'topCommentCount'
	  }
	   Object.extend(this.params, params || {});
	 },
	 start:function (){	
  	   var url = "/ajaxComment.do?rnd=" + new Date().getTime();
	   var myAjax;
	   if("alertComment" == this.params.requestType){

  		 myAjax = new Ajax.Request(url,{method:'post', parameters:this.params, onComplete:this.renderCommentCount.bind(this)} );
  	   }else{
  		 myAjax = new Ajax.Request(url,{method:'post', parameters:this.params, onComplete:this.renderCommentList.bind(this)} );
  	   }

	 },
    renderCommentCount:function(req) {
		  var oXml = req.responseXML;

		  var count = XMLHelper.getElementFirstValue(oXml,"count");
		  var oMoreLink = "";
		  var moreURL = ""; 
		  var commentInfo = "";
		  if("0" == count){
			  commentInfo = '';
		  }else{
			  oMoreLink = XMLHelper.getFirstElement(oXml,"morelink");
			  moreURL = XMLHelper.getElementFirstValue(oMoreLink,"url");	
	  		  var viewCommentsTemplate = '';
		 	  var pattern =/(^|.|\r|\n)(\{(.*?)\})/;
		 	  var oCommentsTopTemplate = new Template(viewCommentsTemplate, pattern);
		 	  var commentContent= oCommentsTopTemplate.evaluate({"count":count});
		 	  commentInfo = "<a href='" + moreURL + "' target=\"_blank\">" + commentContent+ "</a>";
		  }
		  $(this.container).update(commentInfo);
     },

	 renderCommentList:function(req) {
		 //alert(req.responseText);
		 var titleContent = '';
	     var commentsContent = '';
	     var pattern =/(^|.|\r|\n)(\{(.*?)\})/;
	     var oXml = req.responseXML;
	  	 var oCommentList = XMLHelper.getFirstElement(oXml,"commentlist");
		 
	  	 //comment's title
	  	 var titleParams = XMLHelper.toHash(oCommentList);
	  	 //alert(titleParams.inspect());
		
		 var titleTemplate = '<h3>There are [{count}] readers reviews - ' + this.params.title + '</h3>';
		 var oTitleTemplate = new Template(titleTemplate, pattern);
	     titleContent =  oTitleTemplate.evaluate(titleParams);
				
	     var lineTemplate = '<tr><th width="55"><p><img src="{iconurl}" align="absmiddle" >&nbsp;Username:</p></th>'
		 var pubCode = XMLHelper.getElementFirstValue(oXml,"pubCode");
		 if(pubCode == "EETOL" || pubCode == "EEOL" || pubCode == "EEIOL"){
		 	lineTemplate = lineTemplate + '<td width="180">{authorurl}</td>';
		 }else{
		 	lineTemplate = lineTemplate + '<td width="180"><a href="javascript:NewWin(\'{authorurl}\',540,400);">{username}</a></td>';
		 }
		 lineTemplate = lineTemplate + '<td width="50" class="date_item">{sdate}</td>';
		 lineTemplate = lineTemplate + '</tr>'
		 
		 lineTemplate = lineTemplate + '<tr><th>Comments:</th>';
		 lineTemplate = lineTemplate + '<td colspan="2">{content}</td></tr>';
		 //comment's content.
		 var oTemplate = new Template(lineTemplate, pattern);
		 oComments = XMLHelper.getFirstElement(oCommentList,"comments");
		 if(oComments != null){
		     var oCommentInfos = XMLHelper.getElement(oComments,"commentInfo");
		  	 for(var i = 0; i < oCommentInfos.length; i++){
		  	   var hashValues =XMLHelper.toHash(oCommentInfos[i]);
		  	   var date = new Date();
		  	   date.setTime(XMLHelper.getElementFirstValue(oCommentInfos[i],"time"));
		  	   var sdate = date.getFullYear() + "-" + (date.getMonth()+1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes();
		   	   hashValues['sdate']=sdate;
		   	   //alert(hashValues.inspect());
		   	   commentsContent = commentsContent +  oTemplate.evaluate(hashValues);
		  	   if(i != oCommentInfos.length-1) {
		  	    commentsContent = commentsContent + '<tr><th colspan="3" class="brokenline">&nbsp;</th></tr>';
		  	   }
		     }  
		     
		 	if(commentsContent != ''){
		      commentsContent = '<div class="interaction_right_txt"><div class="scroll"><div id="commentList2" class="commentbox"><div class="commentlist"><table width="100%" border="0" cellspacing="0" cellpadding="0">'+commentsContent+"</table></div>"
		    }
		    var oMoreLink = XMLHelper.getFirstElement(oXml,"morelink");
		    var moreURL = XMLHelper.getElementFirstValue(oMoreLink,"url");
			commentsContent = commentsContent +  '<div class="more"><a href="' + moreURL + '"><img src="http://image.eetasia.com/post-16x16.gif" align="absmiddle">View full comments</a></div></div></div></div>';
	 	    $(this.container).update(titleContent + commentsContent);  
	     } 
	//end if country
     }   
}

Comment.Add = Class.create();
Comment.Add.prototype =  {
	 initialize: function(container,params) {
	    this.setParams(params);
	    this.isSuccess = true;
	    this.container = container;
	    this.resultCode = '';
	    this.start();
	 },
	 setParams:function(params){
	    this.params = {
	      objectId: '',
	      objectType:  'ARTICLE',
	      numberResults: '10',
	      content:'',
	      checkCode:'',
	      fromUrl:'',
	      messageId:'errorMessage',
	      action:'add'
	   }
	   Object.extend(this.params, params || {});
	 },
	 start:function (){	
  	   var url = "/ajaxComment.do";
  	   new Ajax.Request(url,{method: 'post',asynchronous: false,parameters:this.params,onComplete:this.renderCommentList.bind(this)} );
	 },
	 renderCommentList:function(req){

	 	var oXml = req.responseXML;
	 	var oResult = XMLHelper.getFirstElement(oXml,"commentResult");
 	 	var hasError = XMLHelper.getElementFirstValue(oResult,"hasError");
 	 	//alert(hasError);
   	 	$(this.params.messageId).update('');
 	 	if(hasError == "true" ){
	 		var errorCode = XMLHelper.getElementFirstValue(oResult,"errorCode");
			this.resultCode = errorCode;
	 	    if(errorCode == "E001"){
				$(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">Sorry, the comment can&acute;t be empty.');
				this.isSuccess = false;
			}
			if(errorCode == "E002"){
			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">Sorry, the comment length can&acute;t over than 1000 characters.');

			   this.isSuccess = false;
			}
			if(errorCode == "E007"){
			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">As you serious violation of the rules of the Forum, your operations will be prohibited. For inquiries and complaints, please click <a href="mailto:chnserv@globalsources.com">here</a> to contact Forum administrators!');

			   this.isSuccess = false;
			}

			if(errorCode == "E008"){

			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">Please input verify code');

			   this.isSuccess = false;

			}

			if(errorCode == "E009"){

			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">Inputed an error verify code, please check');

			   this.isSuccess = false;

			}
			if(errorCode == "E010"){
			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">You are trying to submit too fast. ');
			   this.isSuccess = false;
			}
			if(errorCode == "E011"){
			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">Please input verify code');
			   this.isSuccess = false;
			}
			if(errorCode == "E012"){
			   $(this.params.messageId).update('<img src="http://image.eetasia.com/error-16x16.gif" align="absmiddle">');
			   this.isSuccess = false;
			}
			if(errorCode == "E013"){
			   $(this.params.messageId).update('');
			}
			if(errorCode == "E014"){
			   $(this.params.messageId).update('Submit successfully. Will be shown after we review.');
			}
	 	}
	 }
}



function addComment(container,formId){
  var params = $H(Form.serialize(formId,true));
  //alert(params.inspect());
  params.content = encodeURIComponent(params.content);
  //alert(params.inspect());
  var addComment = new Comment.Add(container,params);
  if($('verifyCodeField')!= null && $('checkCodeImage') != null ){
  	if(addComment.resultCode == 'E011'){
  	 $('verifyCodeField').show();
  	}else{
  	 var isAnonymousUser = true;
  	 if(isAnonymousUser){
  		$('verifyCodeField').show();
  	 }else{	
  	 	$('verifyCodeField').hide();
  	 }
  	}
  }  
  //Reload verify code
  if(($('verifyCodeField')!= null && $('checkCodeImage') != null &&  $('verifyCodeField').visible())){

    $("checkCodeImage").setAttribute("src", "/Captcha.do?r="+(new Date().getTime()))

    $(formId).checkCode.value='';

  }
  if(addComment.isSuccess==true)
  $(formId).content.value='';

  new Comment.List(container,params);
  return;
}
function getArtComment(articleId){
     var params = {'objectId':articleId, requestType:'alertComment',numberResults:0,action:'list'};
	 var container = "commentLink_" + articleId;
     new Comment.List(container,params);
}

function $E(b){
	var a=typeof b=="string"?document.getElementById(b):b;
	if(a!=null){return a}else{}return null
}

String.prototype.replaceAll  = function(s1,s2){
	return this.replace(new RegExp(s1,"gm"),s2);
}

/*
 * Create Date:2011-08-24
 * Author: Piano Pi
 * Check the limit
 */
function inputCounter(objectid, msgId, isEditor, maxLength,type){
	var expectLength = maxLength;
	if(isEditor=="true"){
		var body = editor.getData();
		body = body.replaceAll("\t","");
		body = body.replaceAll("\n","");
		body = body.replaceAll("\r","");
		
		expectLength = maxLength - body.length;
	}else{
		var body= $E(objectid).value;
		body = body.replaceAll("\t","");
		body = body.replaceAll("\n","");
		body = body.replaceAll("\r","");
		var len = body.length;
		expectLength = maxLength - len;
	}

	//show the message
	var messageBox = $E(msgId);
	if(expectLength>=0){
		messageBox.innerHTML = '*&nbsp;You can enter [0] more charecters.';
		var message=messageBox.innerHTML;
		message=message.replace("[0]",expectLength);
		messageBox.innerHTML=message;
	}else{
		if(type=='title'){
			messageBox.innerHTML = '*&nbsp;';
		}else if(type=='center'){
			messageBox.innerHTML = '*&nbsp;';
		}else{
			messageBox.innerHTML = '*&nbsp;The maximal length of message is [0] charecters.';
		}
		var message=messageBox.innerHTML;
		message=message.replace("[0]",maxLength);
		messageBox.innerHTML=message;
	}
}
