var pageSize = 10;
var pageIndex = 1;
var copyDefaultText = "我最近注册加入了地库-悦读通，看到这本杂志不错，去看看吧！";
var emailDefaultText = "我最近注册加入了地库-悦读通，这个网络电子杂志平台给我的工作和生活带来了很多帮助。\r\n    "+
"通过它，我阅读了大量的地产行业杂志，遨游在这些杂志里，或让你沉思、或让你感动、或让你欣喜……"+
"沉淀在地产文化中，让我对这个行业有了更新的认识，让建筑孕育生命，让文化升华认知。不仅对我的工作有指导意义，更使我们加深了对生活的热爱。\r\n    "+
"通过地库-悦读通论坛我也结交了一些志同道合的网友，谈房说地，感知超建筑之外的沉思，或许在工作压力压得你喘不过气来的时候在这里你会找到灵感，会找到繁忙生活中认知的升华！你还在等什么，快点注册加入吧！";
var $input = null;//var date1,date2;
var $button = null;
var $div = null;
var $toolId = null;
var zineId = null;
var $loginFlag = null;
var $userNickName = null;
var $userPhotoPath = null;
var goldNum = null;
var kind = "";
var currentUrl = window.location.href;
var addPostUrl = baseUrl + "/comment/addcomment";
var getPostUrl = baseUrl + "/comment/getcomment";
if (currentUrl.indexOf("people") >= 0) {
	kind = "character";
} else if (currentUrl.indexOf("magazine") >= 0) {
	kind = "magazine";
} else if (currentUrl.indexOf("news") >= 0) {
	kind = "news";
} else if(currentUrl.indexOf("brochure") >= 0){
	kind = "brochure";
} else{
}
var getDateString = function(objDate) {
	if (!objDate.getFullYear()){
		return "";
	}
	var year = objDate.getFullYear();
	var month = objDate.getMonth() + 1;
	var date = objDate.getDate();
	var day = objDate.getDay();
	var hour = objDate.getHours();
	var minute = objDate.getMinutes();
	var second = objDate.getSeconds();
	return year + '-' + (month < 10 ? ('0' + month) : month) + '-'
			+ (date < 10 ? ('0' + date) : date)
			+ (hour < 10 ? (' 0' + hour) : ('\x20' + hour)) + ':'
			+ (minute < 10 ? ('0' + minute) : minute) + ':'
			+ (second < 10 ? ('0' + second) : second);
}
var CheckBrowser = function() {
	var cb = "Unknown";
	if (window.ActiveXObject) {
		cb = "IE";
	} else if (navigator.userAgent.toLowerCase().indexOf("firefox") != -1) {
		cb = "Firefox";
	} else if ((typeof document.implementation != "undefined")
			&& (typeof document.implementation.createDocument != "undefined")
			&& (typeof HTMLDocument != "undefined")) {
		cb = "Mozilla";
	} else if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
		cb = "Opera";
	}
	return cb;
}
var goPage = function(page) {
	if (page == -1){
		return;
	}
	var objDate = new Date();
	var time = objDate.getTime();
	loadMessage(null,200);
	$.ajax( {
		'url' :getPostUrl,
		'data' :'id=' + zineId + '&kind=' + kind + '&page=' + page
				+ '&nocache=' + time,
		'dataType' :'text',
		'type' :'post',
		'success' : function(data) {
			pageIndex = parseInt(page);
			var json = $.evalJSON(data);
			successFunction(json);
		}
	});
}
var successFunction = function(data) {
	if (data != null) {
		var dataList = data.dataList;
		var pageNav = data.pageNav;
		if (dataList != null && dataList.length) {
			var newCommentHTML = new Array();
			for ( var i = 0; i < dataList.length; i++) {
				newCommentHTML
						.push('<div class="test"><div class="user_photo border">');
				if ($userPhotoPath == null || $userPhotoPath.val() == null
						|| $userPhotoPath.val() == "") {
					newCommentHTML
							.push('<img src="' + adminBase + '/upimages/user_photo.gif"/>');
				} else {
					newCommentHTML.push('<img src="' + adminBase + '/upimages/'
							+ $userPhotoPath.val() + '"/>');
				}
				newCommentHTML.push('</div>');
				newCommentHTML.push('<span class="key">【' + ((pageIndex - 1)
						* pageSize + 1 + i) + '】</span>')
				newCommentHTML
						.push('<span class="key">'
								+ dataList[i].userNickName
								+ '</span> <span>'
								+ dataList[i].createTime
								+ '</span>'
								+ (dataList[i].flag=='1' ? '<span><img src="'+adminBase+'/images/jinghua.gif" alt="精华" title="精华"/>&nbsp;&nbsp;奖励'+goldNum+'个<img src="'+adminBase+'/images/jinbi.gif" alt="金币" title="金币"/></span>' : '')
								+ (dataList[i].createTime >= dateString ? '<span class="new_img"></span>'
										: '') + '<br/><span>'
								+ dataList[i].content
								+ '</span><div class="dashed_a"></div></div>');
			
			}
			$div.html("");
			$div.html(newCommentHTML.join(''));
		}
		if (pageNav != null) {
			$("#pagination").html("");
			$("#pagination").html(pageNav);
		}
		if($.browser.msie){
		    $("#inputContent").html("输入您要评论的内容！");
		}else{
		    $("#inputContent").val("输入您要评论的内容！");
		}
		hideMessage();
	} else {
		hideMessage();
		alert("ajax失败");
	}
}

//SETTING UP OUR POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;

//loading popup with jQuery magic!
var loadPopup = function (){
	//loads popup only if it is disabled
	if(popupStatus==0){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$("#popupContact").fadeIn("slow");
		popupStatus = 1;
	}
}

//disabling popup with jQuery magic!
var  disablePopup = function(){
	//disables popup only if it is enabled
	if(popupStatus==1){
		$("#backgroundPopup").fadeOut("slow");
		$("#popupContact").fadeOut("slow");
		popupStatus = 0;
	}
}

//centering popup
var centerPopup = function (){
	//request data for centering
	var windowWidth = document.documentElement.scrollWidth;
	var windowHeight = document.documentElement.scrollHeight;
	var tempHeight = windowHeight - 700;
	tempHeight = 170;
	if($.browser.msie){
		//alert($.browser.version)
		windowWidth = document.body.scrollWidth;
	    windowHeight = document.body.scrollHeight;
	    tempHeight= windowHeight-640;
	    tempHeight = 190;
	    if($.browser.version=="6.0"){
	    	tempHeight = 240;
	    }else if($.browser.version=="8.0"){
	    	tempHeight = 110;
	    }
	    $("#popupContact").css("overflow","hidden");
	}else{
	    $("#popupContact").css("overflow","visible");	
	}//alert(windowHeight);
	var popupHeight = $("#popupContact").height();
	var popupWidth = $("#popupContact").width();
	//alert("windowWidth:"+windowWidth+"\r\n"+"windowHeight:"+windowHeight+"\r\n"+"popupWidth:"+popupWidth+"\r\n"+"popupHeight:"+popupHeight);
	//centering
	$("#popupContact").css({
		"position": "absolute",
		//"top": tempHeight/2-popupHeight/2,
		"top":tempHeight,
		"left": windowWidth/2-popupWidth/2
		
	});
	//only need force for IE6
	
	$("#backgroundPopup").css({
		//"height": ($.browser.msie? windowHeight+500:windowHeight)
		"height": windowHeight
	});	
}

 	function copyit(textit) {
	if (window.clipboardData) {
	window.clipboardData.setData("Text",textit);
	} else {
	var flashcopier = 'flashcopier';
	if(!document.getElementById(flashcopier)) {
	var divholder = document.createElement('div');
	divholder.id = flashcopier;
	document.body.appendChild(divholder);
	}
	document.getElementById(flashcopier).innerHTML = '';
	var divinfo = '<embed src="'+adminBase+'/flash/_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(textit)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	document.getElementById(flashcopier).innerHTML = divinfo;
	}
}
 //去左空格; 
    var ltrim = function(s){ 
       return s.replace( /^\s*/, ""); 
    }; 
    //去右空格; 
    var rtrim = function(s){ 
       return s.replace( /\s*$/, ""); 
    }; 
    //去左右空格; 
    var trim = function(s){ 
       return rtrim(ltrim(s)); 
    };
var text_onfocus = function(obj){
	  if(browserValue=="IE"){
	      var r =obj.createTextRange();
	      r.moveStart('textedit');
	      r.collapse(true);
	      r.select();
      }else{
          obj.onfocus();
          obj.select();
      }
	};
	
	var validateNotNull = function(id,name){
	   var obj = document.getElementById(id);
        if(obj.value.replace(/(^\s*)|(\s*$)/g, "") == ""){
           alert(name+"不可为空！");
           text_onfocus(obj);
           return false;
        }else return true;
	};
	
	
	var validateEmail = function(id,name){
	  var obj = document.getElementById(id);
	  if(!(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/).test(trim(obj.value))){//验证Mail的正则表达式,^[a-zA-Z0-9_-]:开头必须为字母,下划线,数字,
	     alert(name+"电子邮箱格式非法！");
	     text_onfocus(obj);
	     return false;
	  }else return true;
	};
	
	 var validate = function(){
        var flag = true;
        flag = validateNotNull("address","电子邮箱") && validateEmail("address","电子邮箱");
        return flag;
    };


var loadingImage='<img src="'+adminBase+'/images/wait.gif" width="20" height="20">';

var loadMessage = function(message,boxWidth) {
//  if(message==""){//不显示进度信息
//  	hiddenLoadingMessage();
//  	return; 
//  }
  if(boxWidth==null) boxWidth=350;
  var loadingMessage;
  if (message) loadingMessage = message;
  else loadingMessage = '正在加载评论，请稍候...';
    var disabledZone = document.getElementById('disabledZone');
    if (!disabledZone) {
      var windowWidth = document.documentElement.scrollWidth;
      if (browserValue == "IE") {
      	windowWidth = document.body.scrollWidth;
      }
      var popupWidth = boxWidth;
      disabledZone = document.createElement('div');
      document.body.appendChild(disabledZone);
      disabledZone.setAttribute('id', 'disabledZone');
      disabledZone.style.position = "absolute";
      disabledZone.style.zIndex = "1000";
      disabledZone.style.left = "0px";
      disabledZone.style.top = "0px";
      disabledZone.style.width = "100%";
      disabledZone.style.height = "100%";      
      disabledZone.innerHTML='<table width="100%" border="0" cellspacing="0" cellpadding="0" height="100%"><tr><td align="center" valign="middle"><div style="padding-top:5; background:#ffffcc; color:blue; width:'+boxWidth+'px; height:40px; filter:alpha(opacity=80); border:solid 1px black; font-size:11pt; line-height:3" id="messageZone">'+loadingImage+loadingMessage+'</div></td></tr></table>';
    
    }else {
      document.getElementById('messageZone').innerHTML = loadingImage+loadingMessage;
      disabledZone.style.visibility = 'visible';
    }
}

function loadMessage1(message) {
  var loadingMessage;
  if (message) loadingMessage = message;
  else loadingMessage = '正在加载评论，请稍候...';

  
    var disabledZone = document.getElementById('disabledZone');;
    if (!disabledZone) {
      disabledZone = document.createElement('div');
      disabledZone.setAttribute('id', 'disabledZone');
      disabledZone.style.position = "absolute";
      disabledZone.style.zIndex = "1000";
      disabledZone.style.left = "0px";
      disabledZone.style.top = "0px";
      disabledZone.style.width = "100%";
      disabledZone.style.height = "100%";
      document.body.appendChild(disabledZone);
      var messageZone = document.createElement('div');
      messageZone.setAttribute('id', 'messageZone');
      messageZone.style.position = "absolute";
      messageZone.style.top = "100px";　　//定义显示加载信息层的位置
      messageZone.style.left = "400px";//定义显示加载信息层的位置
      messageZone.style.width = "200";　　//定义显示加载信息层的宽度
      messageZone.style.height = "50";    //定义显示加载信息层的高度
      messageZone.style.background = "#ffffcc";//定义显示加载信息层的颜色
      messageZone.style.color ="blue"; //"white";
      messageZone.style.fontFamily = "Arial,Helvetica,sans-serif";
      messageZone.style.padding = "4px";
      disabledZone.appendChild(messageZone);
      var text = document.createTextNode(loadingMessage);
      messageZone.appendChild(text);
    }
    else {
      document.getElementById('messageZone').innerHTML = loadingMessage;
      disabledZone.style.visibility = 'visible';
    }
}


//在提供信息文字时，可以传递“<div align=center><font color=#FF99FF size=5>闹闹爱</font></div>”为信息，不过第一次显示的是代码，并不能居中及字体大小、颜色。


//本文来自CSDN博客，转载请标明出处：http://blog.csdn.net/zengbo0710/archive/2007/05/12/1605733.aspx

var hideMessage=function(){
    document.getElementById('disabledZone').style.visibility = 'hidden';
}


var browserValue = CheckBrowser();
var flag = true;
$(document)
		.ready(
				function() {
					$input = $('#inputContent');
					$button = $('#ajax');
					$div = $('#contents');
					$toolId = $('#toolId');
					$loginFlag = $('#loginFlag');
					$userNickName = $('#userNickName');
					$userPhotoPath = $('#userPhotoPath');
					$checkbox = $('#isshow');
					zineId = $toolId.val();
					goldNum = $('#goldNum').val();
					$button.css({'cursor':'pointer'});
					$button
							.click( function() {
								if ($loginFlag.val() == "no") {
									alert("请先登录!");
									return;
								}
								var inputContent = "";
								var postInputContent = null;
								if (browserValue == "IE") {
									inputContent = $.trim($input.html());
								} else if (browserValue == "Firefox") {
									inputContent = $.trim($input.val());
								}
								if (inputContent.replace(/(^\s*)|(\s*$)/g, "") == ""
										|| inputContent.replace(
												/(^\s*)|(\s*$)/g, "") == "输入您要评论的内容！") {
									alert("请填写评论内容！");
									return;
								}
								var regx = new RegExp(
										'<.*?src=\\".*?(\\d+.gif)\\".*?>', 'gi');
								if (regx.test(inputContent)) {
									postInputContent = inputContent.replace(
											regx, "[$1]");
								} else {
									postInputContent = inputContent;
								}
								var postInputContentInfo = encodeURI(
										postInputContent, "utf-8");
								if(browserValue=="IE"){
									postInputContentInfo = encodeURIComponent(
										postInputContent);
								}
								var objDate = new Date();
								var time = objDate.getTime();
								var anonymous = "false";
								if ($checkbox.attr("checked")) {
									anonymous = "true";
								} else {
									anonymous = "false";
								}
								loadMessage('正在提交评论并加载评论信息，请稍候...');
								$.ajax( {
									'url' :addPostUrl,
									'data' :'id=' + zineId + '&kind=' + kind
											+ '&anonymous=' + anonymous
											+ '&content='
											+ postInputContentInfo
											+ '&nocache=' + time,
									'dataType' :'text',
									'type' :'post',
									'success' : function(data) {
										pageIndex = 1;
										var json = $.evalJSON(data);
										successFunction(json);
//									   if(data=="1"){
//									   	 alert("评论成功");
//									   }else{
//									   	 alert("评论失败");
//									   }
									}
								});
								return false;
							});
					$input
							.focus(
									function() {
										if (flag
												&& (($.browser.msie && $input.html().replace(
														/(^\s*)|(\s*$)/g, "") == "输入您要评论的内容！" )||(!$.browser.msie && $input.val().replace(/(^\s*)|(\s*$)/g, "") == "输入您要评论的内容！" ))){
											if($.browser.msie){
											  $input.html("");
											}else{
											  $input.val("");
											}
										}	
									})
							.blur(
							        function(){
									if (flag
												&& (($.browser.msie && $input.html().replace(
														/(^\s*)|(\s*$)/g, "") == "" )||(!$.browser.msie && $input.val().replace(/(^\s*)|(\s*$)/g, "") == "" ))){
											if($.browser.msie){
											  $input.html("输入您要评论的内容！");
											}else{
											  $input.val("输入您要评论的内容！");
											}
										}
									});
					$("#imgTable")
							.find("img")
							.each(
									function() {
										var $thisImg = $(this);
										$thisImg.removeAttr("onclick");
										$thisImg
												.click( function() {
													if (browserValue == "Firefox") {
														alert("对不起，在火狐浏览器中的文本域不支持非纯文本信息，如果您一定需要，请用IE浏览器！");
														return;
													}
													if ($input.html().replace(
															/(^\s*)|(\s*$)/g,
															"") == "输入您要评论的内容！") {
														$input.html("");
													}
													$input
															.append($("<img/>")
																	.attr(
																			"src",
																			$thisImg
																					.attr("src"))
																	.attr(
																			"title",
																			$thisImg
																					.attr("title")));
													flag = false;
													if (browserValue == "IE") {
														var r = $input
																.get(0)
																.createTextRange();
														r.moveStart('textedit');
														r.collapse(true);
														r.select();
													} else if (browserValue == "Firefox") {
													}
													flag = true;
												});
									});
	$('#copyText').val(copyDefaultText + '<a href="'+currentUrl+'">点此阅读</a>');
	//$('#emailText').val('您好!\r\n    '+emailDefaultText+'\r\n                 '+((!$('#sourceNickName').val() || $('#sourceNickName').val() == '')? "悦读通" : $.trim($('#sourceNickName').val())));
	//$('#emailText').val((((!$('#targetNickName').val()) || ($.trim($('#targetNickName').val()==''))) ?"亲爱的悦读通用户" : $('#targetNickName').val())+",您好！\r\n    "+emailDefaultText+'\r\n                 '+((!$('#sourceNickName').val() || $('#sourceNickName').val() == '')? "悦读通" : $.trim($('#sourceNickName').val())));
	//$('#targetNickName').trigger("change");
	//alert($('#copyText').width());
	//$('#copyText').width($('#copyText').width() * 1.4);
	//LOADING POPUP
	//Click the button event!
	
	$('#targetNickName').keyup(function(){
		//var emailTextValue = $('emailText').val();
		//alert($('#emailText').val().indexOf('您好!'));
		//alert($('#emailText').val().replace('您好!',$('#targetNickName').val()+',您好!'));
		//$('#emailText').val($('#emailText').val().replace('您好!',$('#targetNickName').val()+',您好!'));
		//alert((($('#targetNickName').val()) || ($.trim($('#targetNickName').val())=='')) ? ($('#targetNickName').val()+",您好！\r\n    "):"您好！\r\n    ");
	      $('#emailText').val((((!$('#targetNickName').val()) || ($.trim($('#targetNickName').val()==''))) ?"亲爱的悦读通用户" : $('#targetNickName').val())+",您好！\r\n    "+emailDefaultText+'\r\n                 '+((!$('#sourceNickName').val() || $('#sourceNickName').val() == '')? "悦读通" : $.trim($('#sourceNickName').val())));
	}).change(function(){
		$(this).keyup();
	}).keyup();
	
	$('#sourceNickName').keyup(function(){
		$('#targetNickName').keyup();
	}).change(function(){
		$('#targetNickName').keyup();
	});
	
	
	$(".show_but03").click(function(){
		//centering with css
		centerPopup();
		//load popup
		loadPopup();
	});
				
	//CLOSING POPUP
	//Click the x event!
	$("#popupContactClose").click(function(){
		disablePopup();
	});
	//Click out event!
//	$("#backgroundPopup").click(function(){
//		disablePopup();
//	});

    
	
    $('.button').eq(0).click(function(){
    	//clip.setText( $('#emailText').val());
    	copyit($.trim($('#copyText').val()));
    	if($.trim($('#copyText').val())==""){
    	    alert("您还没有输入任何内容");
    	}else{
    		//alert($('#copyText').val());
    		alert("成功复制内容到剪切板");
    	}
    });
    
	$('.button').eq(1).click(function(){
	
//	alert('提交结果为：'+'address=' + $.trim($('#address').val()) + '&targetnickname=' + ($('#targetNickName').val()==null ? '' : $.trim($('#targetNickName').val()))
//											+ '&sourcenickname=' + ($('#sourceNickName').val()==null ? '' : $.trim($('#sourceNickName').val()))
//											+ '&emailtext='
//											+ ($('#emailText').val()==null ? '' : $.trim($('#emailText').val())));
		if(validate()){
			//date1=new Date();
		//	useMessage('正在发送邮件，请稍候...');
			$.ajax( {
									'url' : baseUrl + '/email/send',
									'data' :'address=' + $.trim($('#address').val()) + '&targetnickname=' + ($('#targetNickName').val()==null ? '' : $.trim($('#targetNickName').val()))
											+ '&sourcenickname=' + ($('#sourceNickName').val()==null ? '' : $.trim($('#sourceNickName').val()))
											+ '&emailtext='
											+ ($('#emailText').val()==null ? '' : $.trim($('#emailText').val())),
									'dataType' :'text',
									'type' :'post',
									'success' : function(data) {
										hideMessage();
										if(data=="1"){
											//date2=new Date();alert((date2 - date1)/1000 + "秒钟");
											alert('发送成功!');
											$('#popupContactClose').click();
										}else{
											alert('发送失败，请检查!');
										}
									}
								});
		}
		return false;
	});
	$('.button').eq(2).click(function(){
		$("#popupContactClose").click();
	});	
	goPage(1);		

     
	
				});
