Commit b6baf3ad authored by Liang Ding's avatar Liang Ding

Fixed #276

重构了获取评论人头像的代码
parent 8109d3b1
...@@ -19,6 +19,7 @@ Without this configuration present, some functionality in the IDE may be limited ...@@ -19,6 +19,7 @@ Without this configuration present, some functionality in the IDE may be limited
<word>datastore</word> <word>datastore</word>
<word>ftl</word> <word>ftl</word>
<word>Gmail</word> <word>Gmail</word>
<word>Gravatar</word>
<word>http</word> <word>http</word>
<word>json</word> <word>json</word>
<word>Latke</word> <word>Latke</word>
......
...@@ -16,17 +16,14 @@ ...@@ -16,17 +16,14 @@
package org.b3log.solo.api.symphony; package org.b3log.solo.api.symphony;
import java.io.IOException;
import java.net.MalformedURLException; import java.net.MalformedURLException;
import java.net.URL; import java.net.URL;
import java.util.Date; import java.util.Date;
import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateFormatUtils;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
import org.b3log.latke.Latkes;
import org.b3log.latke.event.Event; import org.b3log.latke.event.Event;
import org.b3log.latke.event.EventManager; import org.b3log.latke.event.EventManager;
import org.b3log.latke.logging.Level; import org.b3log.latke.logging.Level;
...@@ -38,12 +35,8 @@ import org.b3log.latke.servlet.HTTPRequestMethod; ...@@ -38,12 +35,8 @@ import org.b3log.latke.servlet.HTTPRequestMethod;
import org.b3log.latke.servlet.annotation.RequestProcessing; import org.b3log.latke.servlet.annotation.RequestProcessing;
import org.b3log.latke.servlet.annotation.RequestProcessor; import org.b3log.latke.servlet.annotation.RequestProcessor;
import org.b3log.latke.servlet.renderer.JSONRenderer; import org.b3log.latke.servlet.renderer.JSONRenderer;
import org.b3log.latke.urlfetch.HTTPHeader;
import org.b3log.latke.urlfetch.HTTPRequest;
import org.b3log.latke.urlfetch.HTTPResponse;
import org.b3log.latke.urlfetch.URLFetchService; import org.b3log.latke.urlfetch.URLFetchService;
import org.b3log.latke.urlfetch.URLFetchServiceFactory; import org.b3log.latke.urlfetch.URLFetchServiceFactory;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Requests; import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Strings; import org.b3log.latke.util.Strings;
import org.b3log.solo.event.EventTypes; import org.b3log.solo.event.EventTypes;
...@@ -56,9 +49,9 @@ import org.b3log.solo.service.ArticleMgmtService; ...@@ -56,9 +49,9 @@ import org.b3log.solo.service.ArticleMgmtService;
import org.b3log.solo.service.CommentMgmtService; import org.b3log.solo.service.CommentMgmtService;
import org.b3log.solo.service.PreferenceQueryService; import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.service.StatisticMgmtService; import org.b3log.solo.service.StatisticMgmtService;
import org.b3log.solo.util.Comments;
import org.b3log.solo.util.QueryResults; import org.b3log.solo.util.QueryResults;
import org.b3log.solo.util.TimeZones; import org.b3log.solo.util.TimeZones;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -66,7 +59,7 @@ import org.json.JSONObject; ...@@ -66,7 +59,7 @@ import org.json.JSONObject;
* Comment receiver (from B3log Symphony). * Comment receiver (from B3log Symphony).
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.6, Mar 18, 2013 * @version 1.0.0.7, Jul 10, 2013
* @since 0.5.5 * @since 0.5.5
*/ */
@RequestProcessor @RequestProcessor
...@@ -249,13 +242,13 @@ public class CommentReceiver { ...@@ -249,13 +242,13 @@ public class CommentReceiver {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, ""); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
} }
setCommentThumbnailURL(comment); CommentMgmtService.setCommentThumbnailURL(comment);
ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL)); ret.put(Comment.COMMENT_THUMBNAIL_URL, comment.getString(Comment.COMMENT_THUMBNAIL_URL));
// Sets comment on article.... // Sets comment on article....
comment.put(Comment.COMMENT_ON_ID, articleId); comment.put(Comment.COMMENT_ON_ID, articleId);
comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE); comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
final String commentSharpURL = getCommentSharpURLForArticle(article, commentId); final String commentSharpURL = Comments.getCommentSharpURLForArticle(article, commentId);
comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL); comment.put(Comment.COMMENT_SHARP_URL, commentSharpURL);
...@@ -296,83 +289,4 @@ public class CommentReceiver { ...@@ -296,83 +289,4 @@ public class CommentReceiver {
jsonObject.put(Keys.MSG, e.getMessage()); jsonObject.put(Keys.MSG, e.getMessage());
} }
} }
/**
* Gets comment sharp URL with the specified article and comment id.
*
* @param article the specified article
* @param commentId the specified comment id
* @return comment sharp URL
* @throws JSONException json exception
*/
private static String getCommentSharpURLForArticle(final JSONObject article,
final String commentId)
throws JSONException {
final String articleLink = article.getString(Article.ARTICLE_PERMALINK);
return articleLink + "#" + commentId;
}
/**
* Sets commenter thumbnail URL for the specified comment.
*
* @param comment the specified comment
* @throws Exception exception
*/
private static void setCommentThumbnailURL(final JSONObject comment)
throws Exception {
final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
final String id = commentEmail.split("@")[0];
final String domain = commentEmail.split("@")[1];
String thumbnailURL = null;
// Try to set thumbnail URL using Gravatar service
final String hashedEmail = MD5.hash(commentEmail.toLowerCase());
final int size = 60;
final URL gravatarURL = new URL(
"http://secure.gravatar.com/avatar/" + hashedEmail + "?s=" + size + "&d=" + Latkes.getServePath()
+ "/images/default-user-thumbnail.png");
try {
final HTTPRequest request = new HTTPRequest();
request.setURL(gravatarURL);
final HTTPResponse response = urlFetchService.fetch(request);
final int statusCode = response.getResponseCode();
if (HttpServletResponse.SC_OK == statusCode) {
final List<HTTPHeader> headers = response.getHeaders();
boolean defaultFileLengthMatched = false;
for (final HTTPHeader httpHeader : headers) {
if ("Content-Length".equalsIgnoreCase(httpHeader.getName())) {
if (httpHeader.getValue().equals("2147")) {
defaultFileLengthMatched = true;
}
}
}
if (!defaultFileLengthMatched) {
thumbnailURL = "http://secure.gravatar.com/avatar/" + hashedEmail + "?s=" + size + "&d=" + Latkes.getServePath()
+ "/images/default-user-thumbnail.png";
comment.put(Comment.COMMENT_THUMBNAIL_URL, thumbnailURL);
LOGGER.log(Level.TRACE, "Comment thumbnail[URL={0}]", thumbnailURL);
return;
}
} else {
LOGGER.log(Level.WARN, "Can not fetch thumbnail from Gravatar[commentEmail={0}, statusCode={1}]",
new Object[] {commentEmail, statusCode});
}
} catch (final IOException e) {
LOGGER.warn(e.getMessage());
LOGGER.log(Level.WARN, "Can not fetch thumbnail from Gravatar[commentEmail={0}]", commentEmail);
}
if (null == thumbnailURL) {
LOGGER.log(Level.WARN, "Not supported yet for comment thumbnail for email[{0}]", commentEmail);
thumbnailURL = "/images/" + DEFAULT_USER_THUMBNAIL;
comment.put(Comment.COMMENT_THUMBNAIL_URL, thumbnailURL);
}
}
} }
...@@ -15,6 +15,8 @@ ...@@ -15,6 +15,8 @@
*/ */
package org.b3log.solo.model; package org.b3log.solo.model;
import org.b3log.solo.util.Thumbnails;
/** /**
* This class defines all common model relevant keys. * This class defines all common model relevant keys.
...@@ -311,6 +313,11 @@ public final class Common { ...@@ -311,6 +313,11 @@ public final class Common {
*/ */
public static final String ARTICLES_VIEW_PWD = "articlesViewPwd"; public static final String ARTICLES_VIEW_PWD = "articlesViewPwd";
/**
* Key of Gravatar.
*/
public static final String GRAVATAR = "gravatar";
/** /**
* Private default constructor. * Private default constructor.
*/ */
......
...@@ -45,7 +45,6 @@ import org.b3log.latke.servlet.renderer.TextHTMLRenderer; ...@@ -45,7 +45,6 @@ import org.b3log.latke.servlet.renderer.TextHTMLRenderer;
import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer; import org.b3log.latke.servlet.renderer.freemarker.AbstractFreeMarkerRenderer;
import org.b3log.latke.util.Dates; import org.b3log.latke.util.Dates;
import org.b3log.latke.util.Locales; import org.b3log.latke.util.Locales;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Paginator; import org.b3log.latke.util.Paginator;
import org.b3log.latke.util.Requests; import org.b3log.latke.util.Requests;
import org.b3log.latke.util.Stopwatchs; import org.b3log.latke.util.Stopwatchs;
...@@ -57,6 +56,7 @@ import org.b3log.solo.processor.renderer.FrontRenderer; ...@@ -57,6 +56,7 @@ import org.b3log.solo.processor.renderer.FrontRenderer;
import org.b3log.solo.processor.util.Filler; import org.b3log.solo.processor.util.Filler;
import org.b3log.solo.service.*; import org.b3log.solo.service.*;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.comparator.Comparators; import org.b3log.solo.util.comparator.Comparators;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -1191,8 +1191,7 @@ public class ArticleProcessor { ...@@ -1191,8 +1191,7 @@ public class ArticleProcessor {
dataModel.put(Keys.OBJECT_ID, authorId); dataModel.put(Keys.OBJECT_ID, authorId);
dataModel.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME)); dataModel.put(Common.AUTHOR_NAME, author.optString(User.USER_NAME));
final String thumbnailURL = "http://secure.gravatar.com/avatar/" + MD5.hash(author.optString(User.USER_EMAIL)) + "?s=60&d=" final String thumbnailURL = Thumbnails.getGravatarURL(author.optString(User.USER_EMAIL), "60");
+ Latkes.getStaticServePath() + "/images/default-user-thumbnail.png";
dataModel.put(Common.AUTHOR_THUMBNAIL_URL, thumbnailURL); dataModel.put(Common.AUTHOR_THUMBNAIL_URL, thumbnailURL);
......
...@@ -53,7 +53,6 @@ import org.b3log.solo.service.PreferenceQueryService; ...@@ -53,7 +53,6 @@ import org.b3log.solo.service.PreferenceQueryService;
import org.b3log.solo.service.TagQueryService; import org.b3log.solo.service.TagQueryService;
import org.b3log.solo.service.UserQueryService; import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Tags;
import org.b3log.solo.util.comparator.Comparators; import org.b3log.solo.util.comparator.Comparators;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -110,11 +109,6 @@ public class TagProcessor { ...@@ -110,11 +109,6 @@ public class TagProcessor {
@Inject @Inject
private TagQueryService tagQueryService; private TagQueryService tagQueryService;
/**
* Tag utilities.
*/
private Tags tagUtils = Tags.getInstance();
/** /**
* Shows articles related with a tag with the specified context. * Shows articles related with a tag with the specified context.
* *
...@@ -304,7 +298,7 @@ public class TagProcessor { ...@@ -304,7 +298,7 @@ public class TagProcessor {
final List<JSONObject> tags = tagQueryService.getTags(); final List<JSONObject> tags = tagQueryService.getTags();
tagUtils.removeForUnpublishedArticles(tags); tagQueryService.removeForUnpublishedArticles(tags);
Collections.sort(tags, Comparators.TAG_REF_CNT_COMPARATOR); Collections.sort(tags, Comparators.TAG_REF_CNT_COMPARATOR);
dataModel.put(Tag.TAGS, tags); dataModel.put(Tag.TAGS, tags);
......
...@@ -55,7 +55,7 @@ import org.b3log.solo.service.ArticleQueryService; ...@@ -55,7 +55,7 @@ import org.b3log.solo.service.ArticleQueryService;
import org.b3log.solo.service.StatisticQueryService; import org.b3log.solo.service.StatisticQueryService;
import org.b3log.solo.service.TagQueryService; import org.b3log.solo.service.TagQueryService;
import org.b3log.solo.service.UserQueryService; import org.b3log.solo.service.UserQueryService;
import org.b3log.solo.util.Tags; import org.b3log.solo.util.Thumbnails;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -65,7 +65,7 @@ import org.json.JSONObject; ...@@ -65,7 +65,7 @@ import org.json.JSONObject;
* Filler utilities. * Filler utilities.
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.6.5, May 17, 2013 * @version 1.0.6.6, Jul 10, 2013
* @since 0.3.1 * @since 0.3.1
*/ */
@Service @Service
...@@ -100,11 +100,6 @@ public class Filler { ...@@ -100,11 +100,6 @@ public class Filler {
@Inject @Inject
private TagRepository tagRepository; private TagRepository tagRepository;
/**
* Tag utilities.
*/
private Tags tagUtils = Tags.getInstance();
/** /**
* Link repository. * Link repository.
*/ */
...@@ -158,36 +153,6 @@ public class Filler { ...@@ -158,36 +153,6 @@ public class Filler {
@Inject @Inject
private FillTagArticles fillTagArticles; private FillTagArticles fillTagArticles;
/**
* default page.
*/
private static final int DEFAULT_PAGE = 0;
/**
* default page size.
*/
private static final int DEFAULT_PAGESIZE = 10;
/**
* march1.
*/
private static final int MARCH1 = 1;
/**
* march2.
*/
private static final int MARCH2 = 2;
/**
* march3.
*/
private static final int MARCH3 = 3;
/**
* march4.
*/
private static final int MARCH4 = 4;
/** /**
* Fills articles in index.ftl. * Fills articles in index.ftl.
* *
...@@ -323,7 +288,7 @@ public class Filler { ...@@ -323,7 +288,7 @@ public class Filler {
final List<JSONObject> tags = tagRepository.getMostUsedTags(mostUsedTagDisplayCnt); final List<JSONObject> tags = tagRepository.getMostUsedTags(mostUsedTagDisplayCnt);
tagUtils.removeForUnpublishedArticles(tags); tagQueryService.removeForUnpublishedArticles(tags);
dataModel.put(Common.MOST_USED_TAGS, tags); dataModel.put(Common.MOST_USED_TAGS, tags);
} catch (final JSONException e) { } catch (final JSONException e) {
...@@ -544,6 +509,8 @@ public class Filler { ...@@ -544,6 +509,8 @@ public class Filler {
dataModel.put(Keys.Server.STATIC_SERVER, Latkes.getStaticServer()); dataModel.put(Keys.Server.STATIC_SERVER, Latkes.getStaticServer());
dataModel.put(Keys.Server.SERVER, Latkes.getServer()); dataModel.put(Keys.Server.SERVER, Latkes.getServer());
dataModel.put(Common.GRAVATAR, Thumbnails.GRAVATAR);
// Activates plugins // Activates plugins
try { try {
final ViewLoadEventData data = new ViewLoadEventData(); final ViewLoadEventData data = new ViewLoadEventData();
......
...@@ -38,7 +38,6 @@ import org.b3log.latke.service.ServiceException; ...@@ -38,7 +38,6 @@ import org.b3log.latke.service.ServiceException;
import org.b3log.latke.service.annotation.Service; import org.b3log.latke.service.annotation.Service;
import org.b3log.latke.urlfetch.*; import org.b3log.latke.urlfetch.*;
import org.b3log.latke.util.Ids; import org.b3log.latke.util.Ids;
import org.b3log.latke.util.MD5;
import org.b3log.latke.util.Strings; import org.b3log.latke.util.Strings;
import org.b3log.solo.SoloServletListener; import org.b3log.solo.SoloServletListener;
import org.b3log.solo.event.EventTypes; import org.b3log.solo.event.EventTypes;
...@@ -47,6 +46,7 @@ import org.b3log.solo.repository.ArticleRepository; ...@@ -47,6 +46,7 @@ import org.b3log.solo.repository.ArticleRepository;
import org.b3log.solo.repository.CommentRepository; import org.b3log.solo.repository.CommentRepository;
import org.b3log.solo.repository.PageRepository; import org.b3log.solo.repository.PageRepository;
import org.b3log.solo.util.Comments; import org.b3log.solo.util.Comments;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.TimeZones; import org.b3log.solo.util.TimeZones;
import org.json.JSONException; import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -415,8 +415,8 @@ public class CommentMgmtService { ...@@ -415,8 +415,8 @@ public class CommentMgmtService {
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName); ret.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, originalCommentName);
} else { } else {
LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", LOGGER.log(Level.WARN, "Not found orginal comment[id={0}] of reply[name={1}, content={2}]", originalCommentId,
new String[] {originalCommentId, commentName, commentContent}); commentName, commentContent);
} }
} }
setCommentThumbnailURL(comment); setCommentThumbnailURL(comment);
...@@ -592,8 +592,7 @@ public class CommentMgmtService { ...@@ -592,8 +592,7 @@ public class CommentMgmtService {
* @param commentId the given comment id * @param commentId the given comment id
* @throws ServiceException service exception * @throws ServiceException service exception
*/ */
public void removePageComment(final String commentId) public void removePageComment(final String commentId) throws ServiceException {
throws ServiceException {
final Transaction transaction = commentRepository.beginTransaction(); final Transaction transaction = commentRepository.beginTransaction();
try { try {
...@@ -719,10 +718,7 @@ public class CommentMgmtService { ...@@ -719,10 +718,7 @@ public class CommentMgmtService {
public static void setCommentThumbnailURL(final JSONObject comment) throws Exception { public static void setCommentThumbnailURL(final JSONObject comment) throws Exception {
final String commentEmail = comment.getString(Comment.COMMENT_EMAIL); final String commentEmail = comment.getString(Comment.COMMENT_EMAIL);
final String hashedEmail = MD5.hash(commentEmail.toLowerCase()); String thumbnailURL = Thumbnails.getGravatarURL(commentEmail.toLowerCase(), "60");
String thumbnailURL = "http://secure.gravatar.com/avatar/" + hashedEmail + "?s=60&d=" + Latkes.getStaticServePath()
+ "/images/default-user-thumbnail.png";
final URL gravatarURL = new URL(thumbnailURL); final URL gravatarURL = new URL(thumbnailURL);
int statusCode = HttpServletResponse.SC_OK; int statusCode = HttpServletResponse.SC_OK;
......
...@@ -50,6 +50,7 @@ import org.b3log.solo.model.Preference.Default; ...@@ -50,6 +50,7 @@ import org.b3log.solo.model.Preference.Default;
import org.b3log.solo.repository.*; import org.b3log.solo.repository.*;
import org.b3log.solo.util.Comments; import org.b3log.solo.util.Comments;
import org.b3log.solo.util.Skins; import org.b3log.solo.util.Skins;
import org.b3log.solo.util.Thumbnails;
import org.b3log.solo.util.TimeZones; import org.b3log.solo.util.TimeZones;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException; import org.json.JSONException;
...@@ -295,7 +296,7 @@ public class InitService { ...@@ -295,7 +296,7 @@ public class InitService {
comment.put(Comment.COMMENT_CONTENT, StringEscapeUtils.escapeHtml(langPropsService.get("helloWorld.comment.content"))); comment.put(Comment.COMMENT_CONTENT, StringEscapeUtils.escapeHtml(langPropsService.get("helloWorld.comment.content")));
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, ""); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_ID, "");
comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, ""); comment.put(Comment.COMMENT_ORIGINAL_COMMENT_NAME, "");
comment.put(Comment.COMMENT_THUMBNAIL_URL, "http://secure.gravatar.com/avatar/59a5e8209c780307dbe9c9ba728073f5??s=60&r=G"); comment.put(Comment.COMMENT_THUMBNAIL_URL, Thumbnails.GRAVATAR + "59a5e8209c780307dbe9c9ba728073f5??s=60&r=G");
comment.put(Comment.COMMENT_DATE, date); comment.put(Comment.COMMENT_DATE, date);
comment.put(Comment.COMMENT_ON_ID, articleId); comment.put(Comment.COMMENT_ON_ID, articleId);
comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE); comment.put(Comment.COMMENT_ON_TYPE, Article.ARTICLE);
......
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
package org.b3log.solo.service; package org.b3log.solo.service;
import java.util.Iterator;
import java.util.List; import java.util.List;
import javax.inject.Inject; import javax.inject.Inject;
import org.b3log.latke.Keys; import org.b3log.latke.Keys;
...@@ -29,6 +30,7 @@ import org.b3log.latke.util.CollectionUtils; ...@@ -29,6 +30,7 @@ import org.b3log.latke.util.CollectionUtils;
import org.b3log.solo.model.Tag; import org.b3log.solo.model.Tag;
import org.b3log.solo.repository.TagRepository; import org.b3log.solo.repository.TagRepository;
import org.json.JSONArray; import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject; import org.json.JSONObject;
...@@ -134,6 +136,25 @@ public class TagQueryService { ...@@ -134,6 +136,25 @@ public class TagQueryService {
} }
} }
/**
* Removes tags of unpublished articles from the specified tags.
*
* @param tags the specified tags
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/
public void removeForUnpublishedArticles(final List<JSONObject> tags) throws JSONException, RepositoryException {
final Iterator<JSONObject> iterator = tags.iterator();
while (iterator.hasNext()) {
final JSONObject tag = iterator.next();
if (0 == tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT)) {
iterator.remove();
}
}
}
/** /**
* Sets the tag repository with the specified tag repository. * Sets the tag repository with the specified tag repository.
* *
......
...@@ -16,72 +16,42 @@ ...@@ -16,72 +16,42 @@
package org.b3log.solo.util; package org.b3log.solo.util;
import java.util.Iterator; import org.b3log.latke.Latkes;
import java.util.List; import org.b3log.latke.util.MD5;
import org.b3log.solo.model.Tag;
import org.b3log.latke.repository.RepositoryException;
import org.json.JSONException;
import org.json.JSONObject;
/** /**
* Tag utilities. * Thumbnail utilities.
*
* <p>
* By using <a href="http://gravatar.com">Gravatar</a> for user thumbnail.
* </p>
* *
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a> * @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.6, Mar 8, 2011 * @version 1.0.0.0, Jul 10, 2013
* @since 0.3.1 * @since 0.6.1
*/ */
public final class Tags { public final class Thumbnails {
/** /**
* Removes tags of unpublished articles from the specified tags. * Gravatar address.
*
* @param tags the specified tags
* @throws JSONException json exception
* @throws RepositoryException repository exception
*/ */
public static void removeForUnpublishedArticles(final List<JSONObject> tags) throws JSONException, RepositoryException { public static final String GRAVATAR = "http://secure.gravatar.com/avatar/";
final Iterator<JSONObject> iterator = tags.iterator();
while (iterator.hasNext()) {
final JSONObject tag = iterator.next();
if (0 == tag.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT)) {
iterator.remove();
}
}
}
/** /**
* Gets the {@link Tags} singleton. * Gets the Gravatar URL for the specified email with the specified size.
* *
* @return the singleton * @param email the specified email
* @param size the specified size
* @return the Gravatar URL
*/ */
public static Tags getInstance() { public static String getGravatarURL(final String email, final String size) {
return SingletonHolder.SINGLETON; return Thumbnails.GRAVATAR + MD5.hash(email) + "?s=" + size + "&d=" + Latkes.getStaticServePath()
+ "/images/default-user-thumbnail.png";
} }
/** /**
* Private default constructor. * Private constructor.
*/ */
private Tags() {} private Thumbnails() {}
/**
* Singleton holder.
*
* @author <a href="mailto:DL88250@gmail.com">Liang Ding</a>
* @version 1.0.0.0, Jan 12, 2011
*/
private static final class SingletonHolder {
/**
* Singleton.
*/
private static final Tags SINGLETON = new Tags();
/**
* Private default constructor.
*/
private SingletonHolder() {}
}
} }
/*
* Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Admin=function(){this.register={};this.tools=["#page-list","#file-list","#link-list","#preference","#user-list","#plugin-list","#others"];this.adTools=["link-list","preference","file-list","page-list","user-list","plugin-list","others"]};$.extend(Admin.prototype,{logout:function(){window.location.href=latkeConfig.servePath+"/logout?goto="+latkeConfig.servePath},clearTip:function(){$("#tipMsg").text("");$("#loadMsg").text("")},setHashByPage:function(currentPage){var hash=window.location.hash,hashList=hash.split("/");if(/^\d*$/.test(hashList[hashList.length-1])){hashList[hashList.length-1]=currentPage}else{hashList.push(currentPage)}window.location.hash=hashList.join("/")},selectTab:function(id){window.location.hash="#"+id},analyseHash:function(){var hash=window.location.hash;var tag=hash.substr(1,hash.length-1);var tagList=tag.split("/");var tags={};tags.page=1,tags.hashList=[];for(var i=0;i<tagList.length;i++){if(i===tagList.length-1&&(/^\d+$/.test(tagList[i]))){tags.page=tagList[i]}else{tags.hashList.push(tagList[i])}}return tags},setCurByHash:function(){$("#tipMsg").text("");var tags=admin.analyseHash();var tab=tags.hashList[1],subTab=tags.hashList[2];if(tags.hashList.length===1){tab=tags.hashList[0]}if(tab===""){return}if(tab!=="article"){admin.article.clearDraftTimer()}else{if(tab==="article"){admin.article.autoSaveDraftTimer=setInterval(function(){admin.article._autoSaveToDraft()},admin.article.AUTOSAVETIME)}}try{if(tab!=="article"&&admin.article.isConfirm&&admin.editors.articleEditor.getContent().replace(/\s/g,"")!==""&&admin.article.content!==admin.editors.articleEditor.getContent()){if(!confirm(Label.editorLeaveLabel)){window.location.hash="#article/article";return}}if(tab==="article"&&admin.article.isConfirm&&admin.editors.articleEditor.getContent().replace(/\s/g,"")!==""&&admin.article.content!==admin.editors.articleEditor.getContent()){return}}catch(e){var $articleContent=$("#articleContent");if($articleContent.length>0){if(tab!=="article"&&admin.article.isConfirm&&$articleContent.val().replace(/\s/g,"")!==""&&admin.article.content!==$articleContent.val()){if(!confirm(Label.editorLeaveLabel)){window.location.hash="#article/article";return}}if(tab==="article"&&admin.article.isConfirm&&$articleContent.val().replace(/\s/g,"")!==""&&admin.article.content!==$articleContent.val()){return}}}if(tab!=="article"&&admin.editors.articleEditor.setContent){admin.article.clear()}admin.article.isConfirm=true;$("#tabs").tabs("setCurrent",tab);$("#loadMsg").text(Label.loadingLabel);if($("#tabsPanel_"+tab).length===1){if($("#tabsPanel_"+tab).html().replace(/\s/g,"")===""){$("#tabsPanel_"+tab).load("admin-"+tab+".do",function(){if(tab==="article"&&admin.article.status.id){admin.register[tab].init.call(admin.register[tab].obj,admin.article.getAndSet)}else{admin.register[tab].init.call(admin.register[tab].obj,tags.page)}if(subTab){$("#tab"+tab.substring(0,1).toUpperCase()+tab.substring(1)).tabs("setCurrent",subTab)}admin.plugin.setCurByHash(tags)})}else{if(tab==="article"&&admin.article.status.id){admin.article.getAndSet()}if(admin.register[tab]&&admin.register[tab].refresh){admin.register[tab].refresh.call(admin.register[tab].obj,tags.page)}if(subTab){$("#tab"+tab.substring(0,1).toUpperCase()+tab.substring(1)).tabs("setCurrent",subTab)}admin.plugin.setCurByHash(tags)}}else{$("#tipMsg").text("Error: No tab! "+Label.reportIssueLabel);$("#loadMsg").text("")}},init:function(){Util.killIE();$("#loadMsg").text(Label.loadingLabel);$("#tabs").tabs();setInterval(function(){if($("#tipMsg").text()!==""){setTimeout(function(){$("#tipMsg").text("")},7000)}},6000);$("#loadMsg").text("")},collapseNav:function(it){var subNav=$(it).next();subNav.slideToggle("normal",function(){if(this.style.display!=="none"){$(it).find(".ico-arrow-down")[0].className="ico-arrow-up"}else{$(it).find(".ico-arrow-up")[0].className="ico-arrow-down"}})},inited:function(){if(Label.userRole!=="adminRole"){for(var i=0;i<this.adTools.length;i++){$("#tabs").tabs("remove",this.adTools[i])}}else{for(var j=0;j<this.tools.length;j++){if("#"+window.location.hash.split("/")[1]===this.tools[j]){$("#tabToolsTitle").click();break}}}this.setCurByHash()}});var admin=new Admin();admin.editors={};var Editor=function(conf){this._defaults={type:"tinyMCE",kind:"",id:"",language:""};conf.type=Label.editorType;this.conf=conf;this._init()};$.extend(Editor.prototype,{_init:function(){this.init()},init:function(){var conf=this.conf;var types=conf.type.split("-");if(types.length===2){conf.codeMirrorLanguage=types[1];conf.type=types[0]}admin.editors[conf.type].init(conf)},getContent:function(){var conf=this.conf;return admin.editors[conf.type].getContent(conf.id)},setContent:function(content){var conf=this.conf;admin.editors[conf.type].setContent(conf.id,content)}});admin.editors.articleEditor={};admin.editors.abstractEditor={};admin.editors.pageEditor={};admin.editors.tinyMCE={init:function(conf){var language=Label.localeString.substring(0,2);if(language==="zh"){language="zh-cn"}if(conf.kind&&conf.kind==="simple"){try{tinyMCE.init({language:language,mode:"exact",elements:conf.id,theme:"advanced",plugins:"media",theme_advanced_buttons1:"bold,italic,underline,strikethrough,|,undo,redo,|,bullist,numlist,|,code",theme_advanced_buttons2:"",theme_advanced_buttons3:"",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",valid_children:"+body[style]"})}catch(e){$("#tipMsg").text("TinyMCE load fail")}}else{try{tinyMCE.init({language:language,mode:"exact",elements:conf.id,theme:"advanced",plugins:"autosave,style,advhr,advimage,advlink,preview,inlinepopups,media,paste,syntaxhl,wordcount",theme_advanced_buttons1:"formatselect,fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,forecolor,|,advhr,blockquote,syntaxhl,",theme_advanced_buttons2:"undo,redo,|,bullist,numlist,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull,|,pastetext,pasteword,|,link,unlink,image,iespell,media,|,cleanup,code,preview,",theme_advanced_buttons3:"",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",theme_advanced_resizing:true,theme_advanced_statusbar_location:"bottom",extended_valid_elements:"link[type|rel|href|charset],pre[name|class],iframe[src|width|height|name|align],+a[*]",valid_children:"+body[style]",relative_urls:false,remove_script_host:false,oninit:function(){if(typeof(conf.fun)==="function"){conf.fun()}}})}catch(e){$("#tipMsg").text("TinyMCE load fail")}}},getContent:function(id){var content="";try{content=tinyMCE.get(id).getContent()}catch(e){content=$("#"+id).val()}return content},setContent:function(id,content){try{if(tinyMCE.get(id)){tinyMCE.get(id).setContent(content)}else{$("#"+id).val(content)}}catch(e){$("#"+id).val(content)}}};admin.editors.KindEditor={init:function(conf){var language="zh_CN";if("en_US"===Label.localeString){language="en"}if(conf.kind&&conf.kind==="simple"){try{this[conf.id]=KindEditor.create("#"+conf.id,{langType:language,resizeType:0,items:["bold","italic","underline","strikethrough","|","undo","redo","|","insertunorderedlist","insertorderedlist","|","source"]})}catch(e){$("#tipMsg").text("KindEditor load fail")}}else{try{this[conf.id]=KindEditor.create("#"+conf.id,{langType:language,items:["formatblock","fontname","fontsize","|","bold","italic","underline","strikethrough","forecolor","|","link","unlink","image","media","|","pagebreak","emoticons","code","/","undo","redo","|","insertunorderedlist","insertorderedlist","indent","outdent","|","justifyleft","justifycenter","justifyright","justifyfull","|","plainpaste","wordpaste","|","clearhtml","source","preview"],afterCreate:function(){if(typeof(conf.fun)==="function"){conf.fun()}}})}catch(e){$("#tipMsg").text("KindEditor load fail")}}},getContent:function(id){var content="";try{content=this[id].html()}catch(e){content=$("#"+id).val()}return content},setContent:function(id,content){try{this[id].html(content)}catch(e){$("#"+id).val(content)}}};admin.editors.CodeMirror={init:function(conf){var it=this;var previewHTML="<div class='clear'></div>";if(conf.kind!=="simple"){previewHTML="<div class='markdown-preivew'><div class='markdown-help ico-close'></div><div class='clear'></div><div class='markdown-preview-main none'></div><div class='markdown-help-main'>"+Label.markdownHelpLabel+"</div></div><div class='clear'></div>"}$("#"+conf.id).after(previewHTML);if(conf.kind==="simple"){this[conf.id]=CodeMirror.fromTextArea(document.getElementById(conf.id),{mode:"markdown",lineNumbers:true,matchBrackets:true,theme:"default",height:conf.height})}else{it[conf.id+"Timers"]=[];it[conf.id+"IsFirst"]=true;var $preview=$("#"+conf.id).parent().find(".markdown-preivew"),$help=$("#"+conf.id).parent().find(".markdown-preivew").find(".markdown-help");this[conf.id]=CodeMirror.fromTextArea(document.getElementById(conf.id),{mode:"markdown",lineNumbers:true,matchBrackets:true,theme:"default",height:conf.height,onUpdate:function(){var update=function(){if(it[conf.id].getValue()===""){return}$.ajax({url:latkeConfig.servePath+"/console/markdown/2html",type:"POST",cache:false,data:JSON.stringify({markdownText:it[conf.id].getValue()}),success:function(data,textStatus){if(data.sc){if(it[conf.id+"IsFirst"]&&$help.hasClass("ico-close")){$help.click()}it[conf.id+"IsFirst"]=false;$preview.find(".markdown-preview-main").html(data.html)}else{$preview.find(".markdown-preview-main").html(data.msg)}}})};it[conf.id+"Timers"].push(update)}});this._callPreview(conf.id,it[conf.id+"Timers"])}if(conf.kind==="simple"){$("#"+conf.id).next().width("99%")}else{this._bindEvent(conf.id)}if(typeof(conf.fun)==="function"){conf.fun()}},_callPreview:function(id){setInterval(function(){var timers=admin.editors.CodeMirror[id+"Timers"];$(document).queue("myAnimation",[timers[timers.length-1]]);$(document).dequeue("myAnimation");admin.editors.CodeMirror[id+"Timers"]=[]},2000)},_bindEvent:function(id){var $preview=$("#"+id).parent().find(".markdown-preivew");$preview.find(".markdown-help").click(function(){var $it=$(this);if($it.hasClass("ico-help")){$it.removeClass("ico-help").addClass("ico-close");$preview.find(".markdown-preview-main").hide();$preview.find(".markdown-help-main").show()}else{$it.addClass("ico-help").removeClass("ico-close");$preview.find(".markdown-preview-main").show();$preview.find(".markdown-help-main").hide()}})},getContent:function(id){return this[id].getValue()},setContent:function(id,content){this[id].setValue(content)}};var TablePaginate=function(id){this.id=id;this.currentPage=1};$.extend(TablePaginate.prototype,{buildTable:function(colModel,noExpend){var tableData={colModel:colModel,noDataTip:Label.noDataLabel};if(!noExpend){tableData.expendRow={index:"expendRow"}}$("#"+this.id+"Table").table(tableData)},initPagination:function(){var id=this.id;$("#"+id+"Pagination").paginate({bind:function(currentPage,errorMessage){if(errorMessage){$("#tipMsg").text(errorMessage)}else{admin.setHashByPage(currentPage)}},currentPage:1,errorMessage:Label.inputErrorLabel,nextPageText:Label.nextPagePabel,previousPageText:Label.previousPageLabel,goText:Label.gotoLabel,type:"custom",custom:[1],pageCount:1})},initCommentsDialog:function(){var that=this;$("#"+this.id+"Comments").dialog({modal:true,hideFooter:true,close:function(){admin[that.id+"List"].getList(that.currentPage);return true}})},updateTablePagination:function(data,currentPage,pageInfo){currentPage=parseInt(currentPage);if(currentPage>pageInfo.paginationPageCount&&currentPage>1){$("#tipMsg").text(Label.pageLabel+currentPage+Label.notFoundLabel);$("#loadMsg").text("");return}$("#"+this.id+"Table").table("update",{data:[{groupName:"all",groupData:data}]});if(pageInfo.paginationPageCount===0){pageInfo.paginationPageCount=1}$("#"+this.id+"Pagination").paginate("update",{pageCount:pageInfo.paginationPageCount,currentPage:currentPage,custom:pageInfo.paginationPageNums});this.currentPage=currentPage}});admin.article={isConfirm:true,status:{id:undefined,isArticle:undefined,articleHadBeenPublished:undefined},content:"",autoSaveDraftTimer:"",AUTOSAVETIME:1000*60,get:function(id,isArticle){this.status.id=id;this.status.isArticle=isArticle;admin.selectTab("article/article")},getAndSet:function(){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/article/"+admin.article.status.id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#title").val(result.article.articleTitle);admin.article.status.articleHadBeenPublished=result.article.articleHadBeenPublished;admin.editors.articleEditor.setContent(result.article.articleContent);admin.editors.abstractEditor.setContent(result.article.articleAbstract);admin.article.content=admin.editors.articleEditor.getContent();var tags=result.article.articleTags,tagsString="";for(var i=0;i<tags.length;i++){if(0===i){tagsString=tags[i].tagTitle}else{tagsString+=","+tags[i].tagTitle}}$("#tag").val(tagsString);$("#permalink").val(result.article.articlePermalink);$("#viewPwd").val(result.article.articleViewPwd);$("#articleCommentable").prop("checked",result.article.articleCommentable);var signs=result.article.signs;$(".signs button").each(function(i){if(parseInt(result.article.articleSignId)===parseInt(signs[i].oId)){$("#articleSign"+signs[i].oId).addClass("selected")}else{$("#articleSign"+signs[i].oId).removeClass("selected")}});admin.article.setStatus();$("#loadMsg").text("")}})},del:function(id,fromId,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.articleLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/article/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin[fromId+"List"].getList(1)}})}},add:function(articleIsPublished,isAuto){if(admin.article.validate()){var that=this;that._addDisabled();$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var signId="";$(".signs button").each(function(){if(this.className==="selected"){signId=this.id.substr(this.id.length-1,1)}});var articleContent=admin.editors.articleEditor.getContent(),articleAbstract=admin.editors.abstractEditor.getContent();var requestJSONObject={article:{articleTitle:$("#title").val(),articleContent:articleContent,articleAbstract:articleAbstract,articleTags:this.trimUniqueArray($("#tag").val()).toString(),articlePermalink:$("#permalink").val(),articleIsPublished:articleIsPublished,articleSignId:signId,postToCommunity:$("#postToCommunity").prop("checked"),articleCommentable:$("#articleCommentable").prop("checked"),articleViewPwd:$("#viewPwd").val()}};$.ajax({url:latkeConfig.servePath+"/console/article/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);admin.article.status.id=result.oId;return}$("#tipMsg").text(result.msg);if(!result.sc){return}if(articleIsPublished){admin.article.status.id=undefined;admin.selectTab("article/article-list")}else{admin.selectTab("article/draft-list")}admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.add(articleIsPublished)}}})}},update:function(articleIsPublished,isAuto){if(admin.article.validate()){var that=this;that._addDisabled();$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var signId="";$(".signs button").each(function(){if(this.className==="selected"){signId=this.id.substr(this.id.length-1,1)}});var articleContent=admin.editors.articleEditor.getContent(),articleAbstract=admin.editors.abstractEditor.getContent();var requestJSONObject={article:{oId:this.status.id,articleTitle:$("#title").val(),articleContent:articleContent,articleAbstract:articleAbstract,articleTags:this.trimUniqueArray($("#tag").val()).toString(),articlePermalink:$("#permalink").val(),articleIsPublished:articleIsPublished,articleSignId:signId,articleCommentable:$("#articleCommentable").prop("checked"),articleViewPwd:$("#viewPwd").val(),postToCommunity:$("#postToCommunity").prop("checked")}};$.ajax({url:latkeConfig.servePath+"/console/article/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);return}$("#tipMsg").text(result.msg);if(!result.sc){return}if(articleIsPublished){admin.selectTab("article/article-list")}else{admin.selectTab("article/draft-list")}$("#tipMsg").text(Label.updateSuccLabel);admin.article.status.id=undefined;admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.update(articleIsPublished)}}})}},setStatus:function(){if(this.status){if(this.status.isArticle){$("#unSubmitArticle").show();$("#submitArticle").hide()}else{$("#submitArticle").show();$("#unSubmitArticle").hide()}if(this.status.articleHadBeenPublished){$("#postToCommunityPanel").hide()}else{$("#postToCommunityPanel").show()}}else{$("#submitArticle").show();$("#unSubmitArticle").hide();$("#postToCommunityPanel").show()}$("#postToCommunity").attr("checked","checked")},clear:function(){this.status={id:undefined,isArticle:undefined,articleHadBeenPublished:undefined};this.setStatus();$("#title").val("");admin.editors.articleEditor.setContent("");admin.editors.abstractEditor.setContent("");$("#tag").val("");$("#tagCheckboxPanel").hide().find("span").removeClass("selected");$("#permalink").val("");$("#articleCammentable").prop("checked",true);$("#postToCommunity").prop("checked",true);$(".signs button").each(function(i){if(i===0){this.className="selected"}else{this.className=""}});$(".markdown-preview-main").html("")},init:function(fun){$.ajax({url:latkeConfig.servePath+"/console/signs/",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$(".signs button").each(function(i){if(i===result.signs.length){$("#articleSign1").addClass("selected")}else{$("#articleSign"+result.signs[i].oId).tip({content:result.signs[i].signHTML===""?Label.signIsNullLabel:result.signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""),position:"top"})}$(this).click(function(){if(this.className!=="selected"){$(".signs button").each(function(){this.className=""});this.className="selected"}})});$("#loadMsg").text("")}});$.ajax({url:latkeConfig.servePath+"/console/tags",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}if(0>=result.tags.length){return}var tags=[];for(var i=0;i<result.tags.length;i++){tags.push(result.tags[i].tagTitle)}$("#tag").completed({height:160,buttonText:Label.selectLabel,data:tags});$("#loadMsg").text("")}});$("#submitArticle").click(function(){if(admin.article.status.id){admin.article.update(true)}else{admin.article.add(true)}});$("#saveArticle").click(function(){if(admin.article.status.id){admin.article.update(admin.article.status.isArticle)}else{admin.article.add(false)}});admin.editors.articleEditor=new Editor({id:"articleContent",kind:"all",fun:fun,height:500});admin.editors.abstractEditor=new Editor({id:"abstract",kind:"simple",height:200});admin.article.clearDraftTimer();admin.article.autoSaveDraftTimer=setInterval(function(){admin.article._autoSaveToDraft()},admin.article.AUTOSAVETIME)},_autoSaveToDraft:function(){if($("#title").val().replace(/\s/g,"")===""||admin.editors.articleEditor.getContent().replace(/\s/g,"")===""||$("#tag").val().replace(/\s/g,"")===""){return}if(admin.article.status.id){if(admin.article.status.isArticle){admin.article.status.isArticle=false;admin.article.setStatus();admin.article.unPublish(true)}else{admin.article.update(false,true)}}else{admin.article.add(false,true);admin.article.status.isArticle=false}},clearDraftTimer:function(){if(admin.article.autoSaveDraftTimer!==""){window.clearInterval(admin.article.autoSaveDraftTimer);admin.article.autoSaveDraftTimer=""}},validate:function(){var articleContent=admin.editors.articleEditor.getContent();if($("#title").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#title").focus().val("")}else{if(articleContent.replace(/\s/g,"")===""){$("#tipMsg").text(Label.contentEmptyLabel)}else{if($("#tag").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.tagsEmptyLabel);$("#tag").focus().val("")}else{return true}}}return false},unPublish:function(isAuto){var that=this;that._addDisabled();$.ajax({url:latkeConfig.servePath+"/console/article/unpublish/"+admin.article.status.id,type:"PUT",cache:false,success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);return}$("#tipMsg").text(result.msg);if(!result.sc){return}admin.selectTab("article/draft-list");admin.article.status.id=undefined;admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.unPublish()}}})},trimUniqueArray:function(str){str=str.toString();var arr=str.split(",");for(var i=0;i<arr.length;i++){arr[i]=arr[i].replace(/(^\s*)|(\s*$)/g,"");if(arr[i]===""){arr.splice(i,1);i--}}var unique=$.unique(arr);return unique.toString()},prePost:function(){$("#loadMsg").text(Label.loadingLabel);admin.article.content="";if(!admin.editors.articleEditor.getContent){return}var articleContent=admin.editors.articleEditor.getContent();if(window.location.hash==="#article/article"&&articleContent.replace(/\s/g,"")!==""){if(confirm(Label.editorPostLabel)){admin.article.clear()}}$("#tipMsg").text("");$("#loadMsg").text("")},_addDisabled:function(){$("#unSubmitArticle").attr("disabled","disabled");$("#saveArticle").attr("disabled","disabled");$("#submitArticle").attr("disabled","disabled")},_removeDisabled:function(){$("#unSubmitArticle").removeAttr("disabled");$("#saveArticle").removeAttr("disabled");$("#submitArticle").removeAttr("disabled")}};admin.register.article={obj:admin.article,init:admin.article.init,refresh:function(){$("#loadMsg").text("");$("#tipMsg").text("")}};admin.comment={open:function(id,fromId){this.getList(id,fromId);$("#"+fromId+"Comments").dialog("open")},getList:function(onId,fromId){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$("#"+fromId+"Comments").html("");var from="article";if(fromId==="page"){from="page"}$.ajax({url:latkeConfig.servePath+"/console/comments/"+from+"/"+onId,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var comments=result.comments,commentsHTML="";for(var i=0;i<comments.length;i++){var hrefHTML="<a target='_blank' href='"+comments[i].commentURL+"'>",content=comments[i].commentContent,contentHTML=Util.replaceEmString(content);if(comments[i].commentURL==="http://"){hrefHTML="<a target='_blank'>"}commentsHTML+="<div class='comment-title'><span class='left'>"+hrefHTML+comments[i].commentName+"</a>";if(comments[i].commentOriginalCommentName){commentsHTML+="@"+comments[i].commentOriginalCommentName}commentsHTML+="</span><span title='"+Label.removeLabel+"' class='right deleteIcon' onclick=\"admin.comment.del('"+comments[i].oId+"', '"+fromId+"', '"+onId+"')\"></span><span class='right'><a href='mailto:"+comments[i].commentEmail+"'>"+comments[i].commentEmail+"</a>&nbsp;&nbsp;"+$.bowknot.getDate(comments[i].commentTime)+"&nbsp;</span><div class='clear'></div></div><div class='margin12'>"+contentHTML+"</div>"}if(""===commentsHTML){commentsHTML=Label.noCommentLabel}$("#"+fromId+"Comments").html(commentsHTML);$("#loadMsg").text("")}})},del:function(id,fromId,articleId){var isDelete=confirm(Label.confirmRemoveLabel+Label.commentLabel+"?");if(isDelete){$("#loadMsg").text(Label.loadingLabel);var from="article";if(fromId==="page"){from="page"}$.ajax({url:latkeConfig.servePath+"/console/"+from+"/comment/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.comment.getList(articleId,fromId);$("#loadMsg").text("")}})}}};admin.articleList={tablePagination:new TablePaginate("article"),init:function(page){this.tablePagination.buildTable([{text:Label.titleLabel,index:"title",minWidth:110,style:"padding-left: 12px;font-size:14px;"},{text:Label.authorLabel,index:"author",width:150,style:"padding-left: 12px;"},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"},{text:Label.viewLabel,width:60,index:"articleViewCount",style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page)},getList:function(pageNum){var that=this;$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/articles/status/published/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var articles=result.articles,articleData=[];for(var i=0;i<articles.length;i++){articleData[i]={};articleData[i].title="<a href='"+latkeConfig.servePath+articles[i].articlePermalink+"' target='_blank' title='"+articles[i].articleTitle+"' class='no-underline'>"+articles[i].articleTitle+"</a><span class='table-tag'>"+articles[i].articleTags+"</span>";articleData[i].date=$.bowknot.getDate(articles[i].articleCreateTime);articleData[i].comments=articles[i].articleCommentCount;articleData[i].articleViewCount=articles[i].articleViewCount;articleData[i].author=articles[i].authorName;var topClass=articles[i].articlePutTop?Label.cancelPutTopLabel:Label.putTopLabel;articleData[i].expendRow="<a target='_blank' href='"+latkeConfig.servePath+articles[i].articlePermalink+"'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.get('"+articles[i].oId+"', true)\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.del('"+articles[i].oId+"', 'article', '"+articles[i].articleTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.articleList.popTop(this, '"+articles[i].oId+"')\">"+topClass+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+articles[i].oId+"', 'article')\">"+Label.commentLabel+"</a>"}that.tablePagination.updateTablePagination(articleData,pageNum,result.pagination);$("#loadMsg").text("")}})},popTop:function(it,id){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var $it=$(it),ajaxUrl="canceltop",tip=Label.putTopLabel;if($it.html()===Label.putTopLabel){ajaxUrl="puttop";tip=Label.cancelPutTopLabel}$.ajax({url:latkeConfig.servePath+"/console/article/"+ajaxUrl+"/"+id,type:"PUT",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$it.html(tip);$("#loadMsg").text("")}})}};admin.register["article-list"]={obj:admin.articleList,init:admin.articleList.init,refresh:admin.articleList.getList};admin.draftList={tablePagination:new TablePaginate("draft"),init:function(page){this.tablePagination.buildTable([{text:Label.titleLabel,index:"title",minWidth:110,style:"padding-left: 12px;font-size:14px;"},{text:Label.authorLabel,index:"author",width:150,style:"padding-left: 12px;"},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"},{text:Label.viewLabel,width:60,index:"articleViewCount",style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page)},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);var that=this;$.ajax({url:latkeConfig.servePath+"/console/articles/status/unpublished/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var articles=result.articles,articleData=[];for(var i=0;i<articles.length;i++){articleData[i]={};articleData[i].tags=articles[i].articleTags;articleData[i].date=$.bowknot.getDate(articles[i].articleCreateTime);articleData[i].comments=articles[i].articleCommentCount;articleData[i].articleViewCount=articles[i].articleViewCount;articleData[i].author=articles[i].authorName;articleData[i].title="<a class='no-underline' href='"+latkeConfig.servePath+articles[i].articlePermalink+"' target='_blank'>"+articles[i].articleTitle+"</a><span class='table-tag'>"+articles[i].articleTags+"</span>";articleData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.article.get('"+articles[i].oId+"', false);\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.del('"+articles[i].oId+"', 'draft', '"+articles[i].articleTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+articles[i].oId+"', 'draft')\">"+Label.commentLabel+"</a>"}that.tablePagination.updateTablePagination(articleData,pageNum,result.pagination);$("#loadMsg").text("")}})}};admin.register["draft-list"]={obj:admin.draftList,init:admin.draftList.init,refresh:admin.draftList.getList};admin.pageList={tablePagination:new TablePaginate("page"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},id:"",type:"link",init:function(page){this.tablePagination.buildTable([{text:"",index:"pageOrder",width:60,style:"padding-left: 12px;font-size:14px;"},{style:"padding-left: 12px;",text:Label.titleLabel,index:"pageTitle",width:300},{style:"padding-left: 12px;",text:Label.permalinkLabel,index:"pagePermalink",minWidth:300},{style:"padding-left: 12px;",text:Label.openMethodLabel,index:"pageTarget",width:120},{style:"padding-left: 12px;",text:Label.typeLabel,index:"pageType",width:80},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page);var language=Label.localeString.substring(0,2);if(language==="zh"){language="zh-cn"}admin.editors.pageEditor=new Editor({language:language,kind:"all",id:"pageContent"});$(".fn-type").click(function(){var $it=$(this);if($it.hasClass("selected")){return}$(".fn-type").removeClass("selected");$it.addClass("selected");admin.pageList.type=$it.data("type");if(admin.pageList.type==="page"){$("#pagePagePanel").slideDown();if(Label.editorType==="CodeMirror-Markdown"&&admin.editors.pageEditor.getContent()===""){admin.editors.pageEditor.setContent("")}}else{$("#pagePagePanel").slideUp()}})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var that=this;$.ajax({url:latkeConfig.servePath+"/console/pages/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pages=result.pages;var pageData=[];admin.pageList.pageInfo.currentCount=pages.length;admin.pageList.pageInfo.pageCount=result.pagination.paginationPageCount===0?1:result.pagination.paginationPageCount;for(var i=0;i<pages.length;i++){pageData[i]={};if(i===0){if(pages.length===1){pageData[i].pageOrder=""}else{pageData[i].pageOrder='<div class="table-center" style="width:14px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'down\');" class="table-downIcon"></span></div>'}}else{if(i===pages.length-1){pageData[i].pageOrder='<div class="table-center" style="width:14px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> </div>'}else{pageData[i].pageOrder='<div class="table-center" style="width:38px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}pageData[i].pageTitle="<a class='no-underline' href='"+pages[i].pagePermalink+"' target='_blank'>"+pages[i].pageTitle+"</a>";pageData[i].pagePermalink="<a class='no-underline' href='"+pages[i].pagePermalink+"' target='_blank'>"+pages[i].pagePermalink+"</a>";pageData[i].pageTarget=pages[i].pageOpenTarget;pageData[i].pageType=pages[i].pageType;pageData[i].comments=pages[i].pageCommentCount;pageData[i].expendRow="<span><a href='"+pages[i].pagePermalink+"' target='_blank'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.pageList.get('"+pages[i].oId+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.pageList.del('"+pages[i].oId+"', '"+pages[i].pageTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+pages[i].oId+"', 'page')\">"+Label.commentLabel+"</a></span>"}that.tablePagination.updateTablePagination(pageData,pageNum,result.pagination);$("#loadMsg").text("")}})},get:function(id){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/page/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id=id;$("#pageTitle").val(result.page.pageTitle);$("#pagePermalink").val(result.page.pagePermalink);$("#pageTarget").val(result.page.pageOpenTarget);if(result.page.pageType==="page"){$($(".fn-type").get(1)).click()}else{$($(".fn-type").get(0)).click()}$("#pageCommentable").prop("checked",result.page.pageCommentable);admin.editors.pageEditor.setContent(result.page.pageContent);$("#loadMsg").text("")}})},del:function(id,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.navLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/page/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.pageList.pageInfo.currentPage;if(admin.pageList.pageInfo.currentCount===1&&admin.pageList.pageInfo.pageCount!==1&&admin.pageList.pageInfo.currentPage===admin.pageList.pageInfo.pageCount){admin.pageList.pageInfo.pageCount--;pageNum=admin.pageList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum==hashList[hashList.length-1]){admin.pageList.getList(pageNum)}else{admin.setHashByPage(pageNum)}$("#loadMsg").text("")}})}},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var pageContent=admin.editors.pageEditor.getContent();var pagePermalink=$("#pagePermalink").val().replace(/(^\s*)|(\s*$)/g,"");if(admin.pageList.type==="link"){pagePermalink=Util.proessURL(pagePermalink)}var requestJSONObject={page:{pageTitle:$("#pageTitle").val(),pageContent:pageContent,pagePermalink:pagePermalink,pageCommentable:$("#pageCommentable").prop("checked"),pageType:admin.pageList.type,pageOpenTarget:$("#pageTarget").val()}};$.ajax({url:latkeConfig.servePath+"/console/page/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id="";$("#pagePermalink").val("");$("#pageTitle").val("");$("#pageCommentable").prop("cheked",false);$("#pageTarget").val("_self");$($(".fn-type").get(0)).click();admin.editors.pageEditor.setContent("");if(admin.pageList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.pageList.pageInfo.currentPage===admin.pageList.pageInfo.pageCount){admin.pageList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.pageList.pageInfo.pageCount==hashList[hashList.length-1]){admin.pageList.getList(admin.pageList.pageInfo.pageCount)}else{admin.setHashByPage(admin.pageList.pageInfo.pageCount)}$("#loadMsg").text("")}})}},update:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var pageContent=admin.editors.pageEditor.getContent();var pagePermalink=$("#pagePermalink").val().replace(/(^\s*)|(\s*$)/g,"");if(admin.pageList.type==="link"){pagePermalink=Util.proessURL(pagePermalink)}var requestJSONObject={page:{pageTitle:$("#pageTitle").val(),oId:this.id,pageContent:pageContent,pagePermalink:pagePermalink,pageCommentable:$("#pageCommentable").prop("checked"),pageType:admin.pageList.type,pageOpenTarget:$("#pageTarget").val()}};$.ajax({url:latkeConfig.servePath+"/console/page/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id="";admin.pageList.getList(admin.pageList.pageInfo.currentPage);$("#pageTitle").val("");$("#pagePermalink").val("");$("#pageCommentable").prop("cheked",false);$("#pageTarget").val("_self");$($(".fn-type").get(0)).click();admin.editors.pageEditor.setContent("");$("#loadMsg").text("")}})}},validate:function(){if($("#pageTitle").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#pageTitle").focus()}else{if(admin.pageList.type==="link"&&$("#pagePermalink").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.linkEmptyLabel)}else{return true}}return false},submit:function(){if(this.id!==""){this.update()}else{this.add()}},changeOrder:function(id,order,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:id.toString(),direction:status};$.ajax({url:latkeConfig.servePath+"/console/page/order/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);admin.pageList.getList(admin.pageList.pageInfo.currentPage);$("#loadMsg").text("")}})}};admin.register["page-list"]={obj:admin.pageList,init:admin.pageList.init,refresh:admin.pageList.getList};admin.others={init:function(){$("#tabOthers").tabs();$.ajax({url:latkeConfig.servePath+"/console/reply/notification/template",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#replayEmailTemplateTitle").val(result.replyNotificationTemplate.subject);$("#replayEmailTemplateBody").val(result.replyNotificationTemplate.body);$("#loadMsg").text("")}})},removeUnusedTags:function(){$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/tag/unused",type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg)}})},getUnusedTags:function(){$.ajax({url:latkeConfig.servePath+"/console/tag/unused",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var unusedTags=result.unusedTags;if(0===unusedTags.length){return}}})},update:function(){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={replyNotificationTemplate:{subject:$("#replayEmailTemplateTitle").val(),body:$("#replayEmailTemplateBody").val()}};$.ajax({url:latkeConfig.servePath+"/console/reply/notification/template",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);$("#loadMsg").text("")}})}};admin.register.others={obj:admin.others,init:admin.others.init,refresh:function(){admin.clearTip()}};admin.linkList={tablePagination:new TablePaginate("link"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},id:"",init:function(page){this.tablePagination.buildTable([{text:"",index:"linkOrder",width:60},{style:"padding-left: 12px;",text:Label.linkTitleLabel,index:"linkTitle",width:230},{style:"padding-left: 12px;",text:Label.urlLabel,index:"linkAddress",minWidth:180},{style:"padding-left: 12px;",text:Label.linkDescriptionLabel,index:"linkDescription",width:360}]);this.tablePagination.initPagination();this.getList(page);$("#updateLink").dialog({width:700,height:180,modal:true,hideFooter:true})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);if(pageNum===0){pageNum=1}this.pageInfo.currentPage=pageNum;var that=this;$.ajax({url:latkeConfig.servePath+"/console/links/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var links=result.links;var linkData=[];admin.linkList.pageInfo.currentCount=links.length;admin.linkList.pageInfo.pageCount=result.pagination.paginationPageCount===0?1:result.pagination.paginationPageCount;for(var i=0;i<links.length;i++){linkData[i]={};if(i===0){if(links.length===1){linkData[i].linkOrder=""}else{linkData[i].linkOrder='<div class="table-center" style="width:14px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}else{if(i===links.length-1){linkData[i].linkOrder='<div class="table-center" style="width:14px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> </div>'}else{linkData[i].linkOrder='<div class="table-center" style="width:38px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}linkData[i].linkTitle=links[i].linkTitle;linkData[i].linkAddress="<a target='_blank' class='no-underline' href='"+links[i].linkAddress+"'>"+links[i].linkAddress+"</a>";linkData[i].linkDescription=links[i].linkDescription;linkData[i].expendRow="<span><a href='"+links[i].linkAddress+"' target='_blank'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.linkList.get('"+links[i].oId+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.linkList.del('"+links[i].oId+"', '"+links[i].linkTitle+"')\">"+Label.removeLabel+"</a></span>"}that.tablePagination.updateTablePagination(linkData,pageNum,result.pagination);$("#loadMsg").text("")}})},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={link:{linkTitle:$("#linkTitle").val(),linkAddress:$("#linkAddress").val(),linkDescription:$("#linkDescription").val()}};$.ajax({url:latkeConfig.servePath+"/console/link/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#linkTitle").val("");$("#linkAddress").val("");$("#linkDescription").val("");if(admin.linkList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.linkList.pageInfo.currentPage===admin.linkList.pageInfo.pageCount){admin.linkList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.linkList.pageInfo.pageCount!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(admin.linkList.pageInfo.pageCount)}admin.linkList.getList(admin.linkList.pageInfo.pageCount);$("#loadMsg").text("")}})}},get:function(id){$("#loadMsg").text(Label.loadingLabel);$("#updateLink").dialog("open");$.ajax({url:latkeConfig.servePath+"/console/link/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.linkList.id=id;$("#linkTitleUpdate").val(result.link.linkTitle);$("#linkAddressUpdate").val(result.link.linkAddress);$("#linkDescriptionUpdate").val(result.link.linkDescription);$("#loadMsg").text("")}})},update:function(){if(this.validate("Update")){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={link:{linkTitle:$("#linkTitleUpdate").val(),oId:this.id,linkAddress:$("#linkAddressUpdate").val(),linkDescription:$("#linkDescriptionUpdate").val()}};$.ajax({url:latkeConfig.servePath+"/console/link/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#updateLink").dialog("close");$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.linkList.getList(admin.linkList.pageInfo.currentPage);$("#loadMsg").text("")}})}},del:function(id,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.permalinkLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/link/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.linkList.pageInfo.currentPage;if(admin.linkList.pageInfo.currentCount===1&&admin.linkList.pageInfo.pageCount!==1&&admin.linkList.pageInfo.currentPage===admin.linkList.pageInfo.pageCount){admin.linkList.pageInfo.pageCount--;pageNum=admin.linkList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.linkList.getList(pageNum);$("#loadMsg").text("")}})}},validate:function(status){if(!status){status=""}if($("#linkTitle"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#linkTitle"+status).focus().val("")}else{if($("#linkAddress"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.addressEmptyLabel);$("#linkAddress"+status).focus().val("")}else{if(!/^\w+:\/\//.test($("#linkAddress"+status).val())){$("#tipMsg").text(Label.addressInvalidLabel);$("#linkAddress"+status).focus().val("")}else{return true}}}return false},changeOrder:function(id,order,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:id.toString(),direction:status};$.ajax({url:latkeConfig.servePath+"/console/link/order/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);admin.linkList.getList(admin.linkList.pageInfo.currentPage);$("#loadMsg").text("")}})}};admin.register["link-list"]={obj:admin.linkList,init:admin.linkList.init,refresh:admin.linkList.getList};admin.preference={locale:"",editorType:"",init:function(){$("#tabPreference").tabs();$.ajax({url:latkeConfig.servePath+"/console/preference/",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var preference=result.preference;$("#metaKeywords").val(preference.metaKeywords),$("#metaDescription").val(preference.metaDescription),$("#blogTitle").val(preference.blogTitle),$("#blogSubtitle").val(preference.blogSubtitle),$("#mostCommentArticleDisplayCount").val(preference.mostCommentArticleDisplayCount);$("#mostViewArticleDisplayCount").val(preference.mostViewArticleDisplayCount),$("#recentCommentDisplayCount").val(preference.recentCommentDisplayCount);$("#mostUsedTagDisplayCount").val(preference.mostUsedTagDisplayCount);$("#articleListDisplayCount").val(preference.articleListDisplayCount);$("#articleListPaginationWindowSize").val(preference.articleListPaginationWindowSize);$("#localeString").val(preference.localeString);$("#timeZoneId").val(preference.timeZoneId);$("#noticeBoard").val(preference.noticeBoard);$("#htmlHead").val(preference.htmlHead);$("#externalRelevantArticlesDisplayCount").val(preference.externalRelevantArticlesDisplayCount);$("#relevantArticlesDisplayCount").val(preference.relevantArticlesDisplayCount);$("#randomArticlesDisplayCount").val(preference.randomArticlesDisplayCount);$("#keyOfSolo").val(preference.keyOfSolo);preference.enableArticleUpdateHint?$("#enableArticleUpdateHint").attr("checked","checked"):$("#enableArticleUpdateHint").removeAttr("checked");preference.allowVisitDraftViaPermalink?$("#allowVisitDraftViaPermalink").attr("checked","checked"):$("allowVisitDraftViaPermalink").removeAttr("checked");admin.preference.locale=preference.localeString;admin.preference.editorType=preference.editorType;$("#skinMain").data("skinDirName",preference.skinDirName);var skins=eval("("+preference.skins+")");var skinsHTML="";for(var i=0;i<skins.length;i++){var selectedClass="";if(skins[i].skinName===preference.skinName&&skins[i].skinDirName===preference.skinDirName){selectedClass+=" selected"}skinsHTML+="<div title='"+skins[i].skinDirName+"' class='left skinItem"+selectedClass+"'><img class='skinPreview' src='"+latkeConfig.staticServePath+"/skins/"+skins[i].skinDirName+"/preview.png'/><div>"+skins[i].skinName+"</div></div>"}$("#skinMain").append(skinsHTML+"<div class='clear'></div>");$(".skinItem").click(function(){$(".skinItem").removeClass("selected");$(this).addClass("selected");$("#skinMain").data("skinDirName",this.title)});var signs=eval("("+preference.signs+")");for(var j=1;j<signs.length;j++){$("#preferenceSign"+j).val(signs[j].signHTML);$("#preferenceSignButton"+j).tip({content:signs[j].signHTML===""?Label.signIsNullLabel:signs[j].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""),position:"bottom"})}$("#articleListDisplay").val(preference.articleListStyle);$("#editorType").val(preference.editorType);$("#feedOutputMode").val(preference.feedOutputMode);$("#feedOutputCnt").val(preference.feedOutputCnt);preference.commentable?$("#commentable").attr("checked","checked"):$("commentable").removeAttr("checked");$("#loadMsg").text("")}})},validate:function(){if(!/^\d+$/.test($("#mostUsedTagDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexTagDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostUsedTagDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#recentCommentDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexRecentCommentDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#recentCommentDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#mostCommentArticleDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexMostCommentArticleDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostCommentArticleDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#mostViewArticleDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexMostViewArticleDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostViewArticleDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#articleListDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.pageSizeLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#articleListDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#articleListPaginationWindowSize").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.windowSizeLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#articleListPaginationWindowSize").focus();return false}else{if(!/^\d+$/.test($("#randomArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.randomArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#randomArticlesDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#relevantArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.relevantArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#relevantArticlesDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#externalRelevantArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.externalRelevantArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#externalRelevantArticlesDisplayCount").focus();return false}}}}}}}}}return true},update:function(){if(!admin.preference.validate()){return}$("#tipMsg").text("");$("#loadMsg").text(Label.loadingLabel);var signs=[{oId:0,signHTML:""},{oId:1,signHTML:$("#preferenceSign1").val()},{oId:2,signHTML:$("#preferenceSign2").val()},{oId:3,signHTML:$("#preferenceSign3").val()}];var requestJSONObject={preference:{metaKeywords:$("#metaKeywords").val(),metaDescription:$("#metaDescription").val(),blogTitle:$("#blogTitle").val(),blogSubtitle:$("#blogSubtitle").val(),mostCommentArticleDisplayCount:$("#mostCommentArticleDisplayCount").val(),mostViewArticleDisplayCount:$("#mostViewArticleDisplayCount").val(),recentCommentDisplayCount:$("#recentCommentDisplayCount").val(),mostUsedTagDisplayCount:$("#mostUsedTagDisplayCount").val(),articleListDisplayCount:$("#articleListDisplayCount").val(),articleListPaginationWindowSize:$("#articleListPaginationWindowSize").val(),skinDirName:$("#skinMain").data("skinDirName"),localeString:$("#localeString").val(),timeZoneId:$("#timeZoneId").val(),noticeBoard:$("#noticeBoard").val(),htmlHead:$("#htmlHead").val(),externalRelevantArticlesDisplayCount:$("#externalRelevantArticlesDisplayCount").val(),relevantArticlesDisplayCount:$("#relevantArticlesDisplayCount").val(),randomArticlesDisplayCount:$("#randomArticlesDisplayCount").val(),enableArticleUpdateHint:$("#enableArticleUpdateHint").prop("checked"),signs:signs,keyOfSolo:$("#keyOfSolo").val(),allowVisitDraftViaPermalink:$("#allowVisitDraftViaPermalink").prop("checked"),articleListStyle:$("#articleListDisplay").val(),editorType:$("#editorType").val(),feedOutputMode:$("#feedOutputMode").val(),feedOutputCnt:$("#feedOutputCnt").val(),commentable:$("#commentable").prop("checked")}};$.ajax({url:latkeConfig.servePath+"/console/preference/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}if($("#localeString").val()!==admin.preference.locale||$("#editorType").val()!==admin.preference.editorType){window.location.reload()}for(var i=1;i<signs.length;i++){if($("#articleSign"+signs[i].oId).length===1){$("#articleSign"+signs[i].oId).tip("option","content",signs[i].signHTML===""?Label.signIsNullLabel:signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""))}$("#preferenceSignButton"+signs[i].oId).tip("option","content",signs[i].signHTML===""?Label.signIsNullLabel:signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""))}$("#loadMsg").text("")}})}};admin.register.preference={obj:admin.preference,init:admin.preference.init,refresh:function(){admin.clearTip()}};admin.pluginList={tablePagination:new TablePaginate("plugin"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},init:function(page){this.tablePagination.buildTable([{style:"padding-left: 12px;",text:Label.pluginNameLabel,index:"name",width:230},{style:"padding-left: 12px;",text:Label.statusLabel,index:"status",minWidth:180},{style:"padding-left: 12px;",text:Label.authorLabel,index:"author",width:200},{style:"padding-left: 12px;",text:Label.versionLabel,index:"version",width:120}]);this.tablePagination.initPagination();$("#pluginSetting").dialog({width:700,height:180,modal:true,hideFooter:true});this.getList(page)},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var that=this;$.ajax({url:latkeConfig.servePath+"/console/plugins/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pluginList.pageInfo.currentPage=pageNum;var datas=result.plugins;for(var i=0;i<datas.length;i++){datas[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.pluginList.changeStatus('"+datas[i].oId+"', '"+datas[i].status+"')\">";if(datas[i].status==="ENABLED"){datas[i].status=Label.enabledLabel;datas[i].expendRow+=Label.disableLabel}else{datas[i].status=Label.disabledLabel;datas[i].expendRow+=Label.enableLabel}datas[i].expendRow+="</a> ";if(datas[i].setting!="{}"){datas[i].expendRow+="<a href='javascript:void(0)' onclick=\"admin.pluginList.toSetting('"+datas[i].oId+"')\"> "+Label.settingLabel+" </a> "}}that.tablePagination.updateTablePagination(result.plugins,pageNum,result.pagination);$("#loadMsg").text("")}})},toSetting:function(pluginId){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:pluginId};$.ajax({url:latkeConfig.servePath+"/console/plugin/toSetting",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);$("#pluginSetting").html(result);$("#pluginSetting").dialog("open");$("#loadMsg").text("")}})},changeStatus:function(pluginId,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");if(status==="ENABLED"){status="DISABLED"}else{status="ENABLED"}var requestJSONObject={oId:pluginId,status:status};$.ajax({url:latkeConfig.servePath+"/console/plugin/status/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#loadMsg").text("");window.location.reload()}})}};admin.register["plugin-list"]={obj:admin.pluginList,init:admin.pluginList.init,refresh:function(){admin.claerTip()}};admin.userList={tablePagination:new TablePaginate("user"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},userInfo:{oId:"",userRole:""},init:function(page){this.tablePagination.buildTable([{style:"padding-left: 12px;",text:Label.commentNameLabel,index:"userName",width:230},{style:"padding-left: 12px;",text:Label.commentEmailLabel,index:"userEmail",minWidth:180},{style:"padding-left: 12px;",text:Label.roleLabel,index:"isAdmin",width:120}]);this.tablePagination.initPagination();this.getList(page);$("#userUpdate").dialog({width:700,height:230,modal:true,hideFooter:true})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");this.pageInfo.currentPage=pageNum;var that=this;$.ajax({url:latkeConfig.servePath+"/console/users/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var users=result.users;var userData=[];admin.userList.pageInfo.currentCount=users.length;admin.userList.pageInfo.pageCount=result.pagination.paginationPageCount;if(users.length<1){$("#tipMsg").text("No user "+Label.reportIssueLabel);$("#loadMsg").text("");return}for(var i=0;i<users.length;i++){userData[i]={};userData[i].userName=users[i].userName;userData[i].userEmail=users[i].userEmail;if("adminRole"===users[i].userRole){userData[i].isAdmin="&nbsp;"+Label.administratorLabel;userData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.userList.get('"+users[i].oId+"', '"+users[i].userRole+"')\">"+Label.updateLabel+"</a>"}else{userData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.userList.get('"+users[i].oId+"', '"+users[i].userRole+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.userList.del('"+users[i].oId+"', '"+users[i].userName+"')\">"+Label.removeLabel+"</a><a href='javascript:void(0)' onclick=\"admin.userList.changeRole('"+users[i].oId+"')\">"+Label.changeRoleLabel+"</a>";if("defaultRole"===users[i].userRole){userData[i].isAdmin=Label.commonUserLabel}else{userData[i].isAdmin=Label.visitorUserLabel}}that.tablePagination.updateTablePagination(userData,pageNum,result.pagination);$("#loadMsg").text("")}}})},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={userName:$("#userName").val(),userEmail:$("#userEmail").val(),userURL:$("#userURL").val(),userPassword:$("#userPassword").val()};$.ajax({url:latkeConfig.servePath+"/console/user/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#userName").val("");$("#userEmail").val("");$("#userURL").val("");$("#userPassword").val("");if(admin.userList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.userList.pageInfo.pageCount!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(admin.userList.pageInfo.pageCount)}admin.userList.getList(admin.userList.pageInfo.pageCount);$("#loadMsg").text("")}})}},get:function(id,userRole){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$("#userUpdate").dialog("open");$.ajax({url:latkeConfig.servePath+"/console/user/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var $userEmailUpdate=$("#userEmailUpdate");$("#userNameUpdate").val(result.user.userName).data("userInfo",{oId:id,userRole:userRole});$userEmailUpdate.val(result.user.userEmail);if("adminRole"===userRole){$userEmailUpdate.attr("disabled","disabled")}else{$userEmailUpdate.removeAttr("disabled")}$("#userURLUpdate").val(result.user.userURL);$("#userPasswordUpdate").val(result.user.userPassword);$("#loadMsg").text("")}})},update:function(){if(this.validate("Update")){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var userInfo=$("#userNameUpdate").data("userInfo");var requestJSONObject={userName:$("#userNameUpdate").val(),oId:userInfo.oId,userEmail:$("#userEmailUpdate").val(),userURL:$("#userURLUpdate").val(),userRole:userInfo.userRole,userPassword:$("#userPasswordUpdate").val()};$.ajax({url:latkeConfig.servePath+"/console/user/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#userUpdate").dialog("close");$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.userList.getList(admin.userList.pageInfo.currentPage);$("#loadMsg").text("")}})}},del:function(id,userName){var isDelete=confirm(Label.confirmRemoveLabel+Label.userLabel+'"'+userName+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/user/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.userList.pageInfo.currentPage;if(admin.userList.pageInfo.currentCount===1&&admin.userList.pageInfo.pageCount!==1&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount--;pageNum=admin.userList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.userList.getList(pageNum);$("#loadMsg").text("")}})}},changeRole:function(id){$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/changeRole/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.userList.pageInfo.currentPage;if(admin.userList.pageInfo.currentCount===1&&admin.userList.pageInfo.pageCount!==1&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount--;pageNum=admin.userList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.userList.getList(pageNum);$("#loadMsg").text("")}})},validate:function(status){if(!status){status=""}var userName=$("#userName"+status).val().replace(/(^\s*)|(\s*$)/g,"");if(2>userName.length||userName.length>20){$("#tipMsg").text(Label.nameTooLongLabel);$("#userName"+status).focus()}else{if($("#userEmail"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.mailCannotEmptyLabel);$("#userEmail"+status).focus()}else{if(!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($("#userEmail"+status).val())){$("#tipMsg").text(Label.mailInvalidLabel);$("#userEmail"+status).focus()}else{if($("#userPassword"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.passwordEmptyLabel);$("#userPassword"+status).focus()}else{return true}}}}return false}};admin.register["user-list"]={obj:admin.userList,init:admin.userList.init,refresh:function(){admin.clearTip()}};admin.commentList={tablePagination:new TablePaginate("comment"),pageInfo:{currentPage:1},init:function(page){this.tablePagination.buildTable([{text:Label.commentContentLabel,index:"content",minWidth:300,style:"padding-left: 12px;"},{text:Label.authorLabel,index:"title",width:230,style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.getList(page)},getList:function(pageNum){var that=this;$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/comments/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}that.pageInfo.currentPage=pageNum;var comments=result.comments,commentsData=[];for(var i=0;i<comments.length;i++){var type="Article";if(comments[i].type==="pageComment"){type="Page"}commentsData[i]={};commentsData[i].content=Util.replaceEmString(comments[i].commentContent)+"<span class='table-tag'> on &nbsp;&nbsp;</span><a href='"+latkeConfig.servePath+comments[i].commentSharpURL+"' target='_blank'>"+comments[i].commentTitle+"</a>";commentsData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.commentList.del('"+comments[i].oId+"', '"+type+"')\">"+Label.removeLabel+"</a>";commentsData[i].title="<img class='small-head' src='"+comments[i].commentThumbnailURL+"'/>";if("http://"===comments[i].commentURL){commentsData[i].title+=comments[i].commentName}else{commentsData[i].title+="<a href='"+comments[i].commentURL+"' target='_blank' class='no-underline'>"+comments[i].commentName+"</a>"}commentsData[i].title+="<br/><a href='mailto:"+comments[i].commentEmail+"'>"+comments[i].commentEmail+"</a>";commentsData[i].date=$.bowknot.getDate(comments[i].commentTime)}that.tablePagination.updateTablePagination(commentsData,pageNum,result.pagination);$("#loadMsg").text("")}})},del:function(id,type){if(confirm(Label.confirmRemoveLabel+Label.commentLabel+"?")){$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/"+type.toLowerCase()+"/comment/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.commentList.getList(admin.commentList.pageInfo.currentPage);$("#loadMsg").text("")}})}}};admin.register["comment-list"]={obj:admin.commentList,init:admin.commentList.init,refresh:admin.commentList.getList};var plugins={};admin.plugin={plugins:[],add:function(data){data.isInit=false;data.hash=data.path.replace("/","#")+"/"+data.id;this.plugins.push(data);var pathList=this._analysePath(data.path);if(data.index&&pathList.length<2){this._addNew(data,pathList)}},setCurByHash:function(tags){var pluginList=this.plugins;for(var i=0;i<pluginList.length;i++){var data=pluginList[i];var pathList=this._analysePath(data.path),isCurrentPlugin=false;if(data.index&&window.location.hash.indexOf(data.hash)>-1){isCurrentPlugin=true}else{if(data.path.replace("/","#")===window.location.hash||(window.location.hash==="#main"&&data.path.indexOf("/main/panel")>-1)){isCurrentPlugin=true}}if(isCurrentPlugin){if(data.isInit){if(plugins[data.id].refresh){plugins[data.id].refresh(tags.page)}}else{if(!data.index){this._addToExist(data,pathList)}else{if(pathList.length===2){this._addNew(data,pathList)}}plugins[data.id].init(tags.page);data.isInit=true}}}},_analysePath:function(path){var paths=path.split("/");paths.splice(0,1);return paths},_addNew:function(data,pathList){if(pathList.length===2){data.target=$("#tabPreference li").get(data.index-1);$("#tabPreference").tabs("add",data);return}else{if(pathList[0]===""){data.target=$("#tabs>ul>li").get(data.index-1)}else{if(pathList[0]==="article"){data.target=$("#tabArticleMgt>li").get(data.index-1)}else{if(pathList[0]==="tools"){admin.tools.push("#"+data.id);data.target=$("#tabTools>li").get(data.index-1)}}}}if(!data.target){alert("data.index is error!")}$("#tabs").tabs("add",data)},_addToExist:function(data,pathList){switch(pathList[0]){case"main":$("#mainPanel"+pathList[1].charAt(5)).append(data.content);break;case"tools":case"article":if(pathList.length===2){$("#tabsPanel_"+pathList[1]).append(data.content)}else{$("#tabPreferencePanel_"+pathList[2]).append(data.content)}break;case"comment-list":$("#tabsPanel_comment-list").append(data.content);break}}};admin.main={};admin.register.main={obj:admin.main,init:function(){admin.clearTip()},refresh:function(){admin.clearTip()}};admin.about={init:function(){$.ajax({url:"http://rhythm.b3log.org/version/solo/latest/"+Label.version,type:"GET",cache:false,dataType:"jsonp",success:function(data,textStatus){var version=data.soloVersion;if(version===Label.version){$("#aboutLatest").text(Label.upToDateLabel)}else{$("#aboutLatest").html(Label.outOfDateLabel+"<a href='"+data.soloDownload+"'>"+version+"</a>")}},complete:function(XHR,TS){admin.clearTip()}})}};admin.register.about={obj:admin.about,init:admin.about.init,refresh:function(){admin.clearTip()}}; var Admin=function(){this.register={};this.tools=["#page-list","#file-list","#link-list","#preference","#user-list","#plugin-list","#others"];this.adTools=["link-list","preference","file-list","page-list","user-list","plugin-list","others"]};$.extend(Admin.prototype,{logout:function(){window.location.href=latkeConfig.servePath+"/logout?goto="+latkeConfig.servePath},clearTip:function(){$("#tipMsg").text("");$("#loadMsg").text("")},setHashByPage:function(currentPage){var hash=window.location.hash,hashList=hash.split("/");if(/^\d*$/.test(hashList[hashList.length-1])){hashList[hashList.length-1]=currentPage}else{hashList.push(currentPage)}window.location.hash=hashList.join("/")},selectTab:function(id){window.location.hash="#"+id},analyseHash:function(){var hash=window.location.hash;var tag=hash.substr(1,hash.length-1);var tagList=tag.split("/");var tags={};tags.page=1,tags.hashList=[];for(var i=0;i<tagList.length;i++){if(i===tagList.length-1&&(/^\d+$/.test(tagList[i]))){tags.page=tagList[i]}else{tags.hashList.push(tagList[i])}}return tags},setCurByHash:function(){$("#tipMsg").text("");var tags=admin.analyseHash();var tab=tags.hashList[1],subTab=tags.hashList[2];if(tags.hashList.length===1){tab=tags.hashList[0]}if(tab===""){return}if(tab!=="article"){admin.article.clearDraftTimer()}else{if(tab==="article"){admin.article.autoSaveDraftTimer=setInterval(function(){admin.article._autoSaveToDraft()},admin.article.AUTOSAVETIME)}}try{if(tab!=="article"&&admin.article.isConfirm&&admin.editors.articleEditor.getContent().replace(/\s/g,"")!==""&&admin.article.content!==admin.editors.articleEditor.getContent()){if(!confirm(Label.editorLeaveLabel)){window.location.hash="#article/article";return}}if(tab==="article"&&admin.article.isConfirm&&admin.editors.articleEditor.getContent().replace(/\s/g,"")!==""&&admin.article.content!==admin.editors.articleEditor.getContent()){return}}catch(e){var $articleContent=$("#articleContent");if($articleContent.length>0){if(tab!=="article"&&admin.article.isConfirm&&$articleContent.val().replace(/\s/g,"")!==""&&admin.article.content!==$articleContent.val()){if(!confirm(Label.editorLeaveLabel)){window.location.hash="#article/article";return}}if(tab==="article"&&admin.article.isConfirm&&$articleContent.val().replace(/\s/g,"")!==""&&admin.article.content!==$articleContent.val()){return}}}if(tab!=="article"&&admin.editors.articleEditor.setContent){admin.article.clear()}admin.article.isConfirm=true;$("#tabs").tabs("setCurrent",tab);$("#loadMsg").text(Label.loadingLabel);if($("#tabsPanel_"+tab).length===1){if($("#tabsPanel_"+tab).html().replace(/\s/g,"")===""){$("#tabsPanel_"+tab).load("admin-"+tab+".do",function(){if(tab==="article"&&admin.article.status.id){admin.register[tab].init.call(admin.register[tab].obj,admin.article.getAndSet)}else{admin.register[tab].init.call(admin.register[tab].obj,tags.page)}if(subTab){$("#tab"+tab.substring(0,1).toUpperCase()+tab.substring(1)).tabs("setCurrent",subTab)}admin.plugin.setCurByHash(tags)})}else{if(tab==="article"&&admin.article.status.id){admin.article.getAndSet()}if(admin.register[tab]&&admin.register[tab].refresh){admin.register[tab].refresh.call(admin.register[tab].obj,tags.page)}if(subTab){$("#tab"+tab.substring(0,1).toUpperCase()+tab.substring(1)).tabs("setCurrent",subTab)}admin.plugin.setCurByHash(tags)}}else{$("#tipMsg").text("Error: No tab! "+Label.reportIssueLabel);$("#loadMsg").text("")}},init:function(){Util.killIE();$("#loadMsg").text(Label.loadingLabel);$("#tabs").tabs();setInterval(function(){if($("#tipMsg").text()!==""){setTimeout(function(){$("#tipMsg").text("")},7000)}},6000);$("#loadMsg").text("")},collapseNav:function(it){var subNav=$(it).next();subNav.slideToggle("normal",function(){if(this.style.display!=="none"){$(it).find(".ico-arrow-down")[0].className="ico-arrow-up"}else{$(it).find(".ico-arrow-up")[0].className="ico-arrow-down"}})},inited:function(){if(Label.userRole!=="adminRole"){for(var i=0;i<this.adTools.length;i++){$("#tabs").tabs("remove",this.adTools[i])}}else{for(var j=0;j<this.tools.length;j++){if("#"+window.location.hash.split("/")[1]===this.tools[j]){$("#tabToolsTitle").click();break}}}this.setCurByHash()}});var admin=new Admin();admin.editors={};var Editor=function(conf){this._defaults={type:"tinyMCE",kind:"",id:"",language:""};conf.type=Label.editorType;this.conf=conf;this._init()};$.extend(Editor.prototype,{_init:function(){this.init()},init:function(){var conf=this.conf;var types=conf.type.split("-");if(types.length===2){conf.codeMirrorLanguage=types[1];conf.type=types[0]}admin.editors[conf.type].init(conf)},getContent:function(){var conf=this.conf;return admin.editors[conf.type].getContent(conf.id)},setContent:function(content){var conf=this.conf;admin.editors[conf.type].setContent(conf.id,content)}});admin.editors.articleEditor={};admin.editors.abstractEditor={};admin.editors.pageEditor={};admin.editors.tinyMCE={init:function(conf){var language=Label.localeString.substring(0,2);if(language==="zh"){language="zh-cn"}if(conf.kind&&conf.kind==="simple"){try{tinyMCE.init({language:language,mode:"exact",elements:conf.id,theme:"advanced",plugins:"media",theme_advanced_buttons1:"bold,italic,underline,strikethrough,|,undo,redo,|,bullist,numlist,|,code",theme_advanced_buttons2:"",theme_advanced_buttons3:"",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",valid_children:"+body[style]"})}catch(e){$("#tipMsg").text("TinyMCE load fail")}}else{try{tinyMCE.init({language:language,mode:"exact",elements:conf.id,theme:"advanced",plugins:"autosave,style,advhr,advimage,advlink,preview,inlinepopups,media,paste,syntaxhl,wordcount",theme_advanced_buttons1:"formatselect,fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,forecolor,|,advhr,blockquote,syntaxhl,",theme_advanced_buttons2:"undo,redo,|,bullist,numlist,outdent,indent,|,justifyleft,justifycenter,justifyright,justifyfull,|,pastetext,pasteword,|,link,unlink,image,iespell,media,|,cleanup,code,preview,",theme_advanced_buttons3:"",theme_advanced_toolbar_location:"top",theme_advanced_toolbar_align:"left",theme_advanced_resizing:true,theme_advanced_statusbar_location:"bottom",extended_valid_elements:"link[type|rel|href|charset],pre[name|class],iframe[src|width|height|name|align],+a[*]",valid_children:"+body[style]",relative_urls:false,remove_script_host:false,oninit:function(){if(typeof(conf.fun)==="function"){conf.fun()}}})}catch(e){$("#tipMsg").text("TinyMCE load fail")}}},getContent:function(id){var content="";try{content=tinyMCE.get(id).getContent()}catch(e){content=$("#"+id).val()}return content},setContent:function(id,content){try{if(tinyMCE.get(id)){tinyMCE.get(id).setContent(content)}else{$("#"+id).val(content)}}catch(e){$("#"+id).val(content)}}};admin.editors.KindEditor={init:function(conf){var language="zh_CN";if("en_US"===Label.localeString){language="en"}if(conf.kind&&conf.kind==="simple"){try{this[conf.id]=KindEditor.create("#"+conf.id,{langType:language,resizeType:0,items:["bold","italic","underline","strikethrough","|","undo","redo","|","insertunorderedlist","insertorderedlist","|","source"]})}catch(e){$("#tipMsg").text("KindEditor load fail")}}else{try{this[conf.id]=KindEditor.create("#"+conf.id,{langType:language,items:["formatblock","fontname","fontsize","|","bold","italic","underline","strikethrough","forecolor","|","link","unlink","image","media","|","pagebreak","emoticons","code","/","undo","redo","|","insertunorderedlist","insertorderedlist","indent","outdent","|","justifyleft","justifycenter","justifyright","justifyfull","|","plainpaste","wordpaste","|","clearhtml","source","preview"],afterCreate:function(){if(typeof(conf.fun)==="function"){conf.fun()}}})}catch(e){$("#tipMsg").text("KindEditor load fail")}}},getContent:function(id){var content="";try{content=this[id].html()}catch(e){content=$("#"+id).val()}return content},setContent:function(id,content){try{this[id].html(content)}catch(e){$("#"+id).val(content)}}};admin.editors.CodeMirror={init:function(conf){var it=this;var previewHTML="<div class='clear'></div>";if(conf.kind!=="simple"){previewHTML="<div class='markdown-preivew'><div class='markdown-help ico-close'></div><div class='clear'></div><div class='markdown-preview-main none'></div><div class='markdown-help-main'>"+Label.markdownHelpLabel+"</div></div><div class='clear'></div>"}$("#"+conf.id).after(previewHTML);if(conf.kind==="simple"){this[conf.id]=CodeMirror.fromTextArea(document.getElementById(conf.id),{mode:"markdown",lineNumbers:true,matchBrackets:true,theme:"default",height:conf.height})}else{it[conf.id+"Timers"]=[];it[conf.id+"IsFirst"]=true;var $preview=$("#"+conf.id).parent().find(".markdown-preivew"),$help=$("#"+conf.id).parent().find(".markdown-preivew").find(".markdown-help");this[conf.id]=CodeMirror.fromTextArea(document.getElementById(conf.id),{mode:"markdown",lineNumbers:true,matchBrackets:true,theme:"default",height:conf.height,onUpdate:function(){var update=function(){if(it[conf.id].getValue()===""){return}$.ajax({url:latkeConfig.servePath+"/console/markdown/2html",type:"POST",cache:false,data:JSON.stringify({markdownText:it[conf.id].getValue()}),success:function(data,textStatus){if(data.sc){if(it[conf.id+"IsFirst"]&&$help.hasClass("ico-close")){$help.click()}it[conf.id+"IsFirst"]=false;$preview.find(".markdown-preview-main").html(data.html)}else{$preview.find(".markdown-preview-main").html(data.msg)}}})};it[conf.id+"Timers"].push(update)}});this._callPreview(conf.id,it[conf.id+"Timers"])}if(conf.kind==="simple"){$("#"+conf.id).next().width("99%")}else{this._bindEvent(conf.id)}if(typeof(conf.fun)==="function"){conf.fun()}},_callPreview:function(id){setInterval(function(){var timers=admin.editors.CodeMirror[id+"Timers"];$(document).queue("myAnimation",[timers[timers.length-1]]);$(document).dequeue("myAnimation");admin.editors.CodeMirror[id+"Timers"]=[]},2000)},_bindEvent:function(id){var $preview=$("#"+id).parent().find(".markdown-preivew");$preview.find(".markdown-help").click(function(){var $it=$(this);if($it.hasClass("ico-help")){$it.removeClass("ico-help").addClass("ico-close");$preview.find(".markdown-preview-main").hide();$preview.find(".markdown-help-main").show()}else{$it.addClass("ico-help").removeClass("ico-close");$preview.find(".markdown-preview-main").show();$preview.find(".markdown-help-main").hide()}})},getContent:function(id){return this[id].getValue()},setContent:function(id,content){this[id].setValue(content)}};var TablePaginate=function(id){this.id=id;this.currentPage=1};$.extend(TablePaginate.prototype,{buildTable:function(colModel,noExpend){var tableData={colModel:colModel,noDataTip:Label.noDataLabel};if(!noExpend){tableData.expendRow={index:"expendRow"}}$("#"+this.id+"Table").table(tableData)},initPagination:function(){var id=this.id;$("#"+id+"Pagination").paginate({bind:function(currentPage,errorMessage){if(errorMessage){$("#tipMsg").text(errorMessage)}else{admin.setHashByPage(currentPage)}},currentPage:1,errorMessage:Label.inputErrorLabel,nextPageText:Label.nextPagePabel,previousPageText:Label.previousPageLabel,goText:Label.gotoLabel,type:"custom",custom:[1],pageCount:1})},initCommentsDialog:function(){var that=this;$("#"+this.id+"Comments").dialog({modal:true,hideFooter:true,close:function(){admin[that.id+"List"].getList(that.currentPage);return true}})},updateTablePagination:function(data,currentPage,pageInfo){currentPage=parseInt(currentPage);if(currentPage>pageInfo.paginationPageCount&&currentPage>1){$("#tipMsg").text(Label.pageLabel+currentPage+Label.notFoundLabel);$("#loadMsg").text("");return}$("#"+this.id+"Table").table("update",{data:[{groupName:"all",groupData:data}]});if(pageInfo.paginationPageCount===0){pageInfo.paginationPageCount=1}$("#"+this.id+"Pagination").paginate("update",{pageCount:pageInfo.paginationPageCount,currentPage:currentPage,custom:pageInfo.paginationPageNums});this.currentPage=currentPage}});admin.article={isConfirm:true,status:{id:undefined,isArticle:undefined,articleHadBeenPublished:undefined},content:"",autoSaveDraftTimer:"",AUTOSAVETIME:1000*60,get:function(id,isArticle){this.status.id=id;this.status.isArticle=isArticle;admin.selectTab("article/article")},getAndSet:function(){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/article/"+admin.article.status.id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#title").val(result.article.articleTitle);admin.article.status.articleHadBeenPublished=result.article.articleHadBeenPublished;admin.editors.articleEditor.setContent(result.article.articleContent);admin.editors.abstractEditor.setContent(result.article.articleAbstract);admin.article.content=admin.editors.articleEditor.getContent();var tags=result.article.articleTags,tagsString="";for(var i=0;i<tags.length;i++){if(0===i){tagsString=tags[i].tagTitle}else{tagsString+=","+tags[i].tagTitle}}$("#tag").val(tagsString);$("#permalink").val(result.article.articlePermalink);$("#viewPwd").val(result.article.articleViewPwd);$("#articleCommentable").prop("checked",result.article.articleCommentable);var signs=result.article.signs;$(".signs button").each(function(i){if(parseInt(result.article.articleSignId)===parseInt(signs[i].oId)){$("#articleSign"+signs[i].oId).addClass("selected")}else{$("#articleSign"+signs[i].oId).removeClass("selected")}});admin.article.setStatus();$("#loadMsg").text("")}})},del:function(id,fromId,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.articleLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/article/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin[fromId+"List"].getList(1)}})}},add:function(articleIsPublished,isAuto){if(admin.article.validate()){var that=this;that._addDisabled();$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var signId="";$(".signs button").each(function(){if(this.className==="selected"){signId=this.id.substr(this.id.length-1,1)}});var articleContent=admin.editors.articleEditor.getContent(),articleAbstract=admin.editors.abstractEditor.getContent();var requestJSONObject={article:{articleTitle:$("#title").val(),articleContent:articleContent,articleAbstract:articleAbstract,articleTags:this.trimUniqueArray($("#tag").val()).toString(),articlePermalink:$("#permalink").val(),articleIsPublished:articleIsPublished,articleSignId:signId,postToCommunity:$("#postToCommunity").prop("checked"),articleCommentable:$("#articleCommentable").prop("checked"),articleViewPwd:$("#viewPwd").val()}};$.ajax({url:latkeConfig.servePath+"/console/article/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);admin.article.status.id=result.oId;return}$("#tipMsg").text(result.msg);if(!result.sc){return}if(articleIsPublished){admin.article.status.id=undefined;admin.selectTab("article/article-list")}else{admin.selectTab("article/draft-list")}admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.add(articleIsPublished)}}})}},update:function(articleIsPublished,isAuto){if(admin.article.validate()){var that=this;that._addDisabled();$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var signId="";$(".signs button").each(function(){if(this.className==="selected"){signId=this.id.substr(this.id.length-1,1)}});var articleContent=admin.editors.articleEditor.getContent(),articleAbstract=admin.editors.abstractEditor.getContent();var requestJSONObject={article:{oId:this.status.id,articleTitle:$("#title").val(),articleContent:articleContent,articleAbstract:articleAbstract,articleTags:this.trimUniqueArray($("#tag").val()).toString(),articlePermalink:$("#permalink").val(),articleIsPublished:articleIsPublished,articleSignId:signId,articleCommentable:$("#articleCommentable").prop("checked"),articleViewPwd:$("#viewPwd").val(),postToCommunity:$("#postToCommunity").prop("checked")}};$.ajax({url:latkeConfig.servePath+"/console/article/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);return}$("#tipMsg").text(result.msg);if(!result.sc){return}if(articleIsPublished){admin.selectTab("article/article-list")}else{admin.selectTab("article/draft-list")}$("#tipMsg").text(Label.updateSuccLabel);admin.article.status.id=undefined;admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.update(articleIsPublished)}}})}},setStatus:function(){if(this.status){if(this.status.isArticle){$("#unSubmitArticle").show();$("#submitArticle").hide()}else{$("#submitArticle").show();$("#unSubmitArticle").hide()}if(this.status.articleHadBeenPublished){$("#postToCommunityPanel").hide()}else{$("#postToCommunityPanel").show()}}else{$("#submitArticle").show();$("#unSubmitArticle").hide();$("#postToCommunityPanel").show()}$("#postToCommunity").attr("checked","checked")},clear:function(){this.status={id:undefined,isArticle:undefined,articleHadBeenPublished:undefined};this.setStatus();$("#title").val("");admin.editors.articleEditor.setContent("");admin.editors.abstractEditor.setContent("");$("#tag").val("");$("#tagCheckboxPanel").hide().find("span").removeClass("selected");$("#permalink").val("");$("#articleCammentable").prop("checked",true);$("#postToCommunity").prop("checked",true);$(".signs button").each(function(i){if(i===0){this.className="selected"}else{this.className=""}});$(".markdown-preview-main").html("")},init:function(fun){$.ajax({url:latkeConfig.servePath+"/console/signs/",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$(".signs button").each(function(i){if(i===result.signs.length){$("#articleSign1").addClass("selected")}else{$("#articleSign"+result.signs[i].oId).tip({content:result.signs[i].signHTML===""?Label.signIsNullLabel:result.signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""),position:"top"})}$(this).click(function(){if(this.className!=="selected"){$(".signs button").each(function(){this.className=""});this.className="selected"}})});$("#loadMsg").text("")}});$.ajax({url:latkeConfig.servePath+"/console/tags",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}if(0>=result.tags.length){return}var tags=[];for(var i=0;i<result.tags.length;i++){tags.push(result.tags[i].tagTitle)}$("#tag").completed({height:160,buttonText:Label.selectLabel,data:tags});$("#loadMsg").text("")}});$("#submitArticle").click(function(){if(admin.article.status.id){admin.article.update(true)}else{admin.article.add(true)}});$("#saveArticle").click(function(){if(admin.article.status.id){admin.article.update(admin.article.status.isArticle)}else{admin.article.add(false)}});admin.editors.articleEditor=new Editor({id:"articleContent",kind:"all",fun:fun,height:500});admin.editors.abstractEditor=new Editor({id:"abstract",kind:"simple",height:200});admin.article.clearDraftTimer();admin.article.autoSaveDraftTimer=setInterval(function(){admin.article._autoSaveToDraft()},admin.article.AUTOSAVETIME)},_autoSaveToDraft:function(){if($("#title").val().replace(/\s/g,"")===""||admin.editors.articleEditor.getContent().replace(/\s/g,"")===""||$("#tag").val().replace(/\s/g,"")===""){return}if(admin.article.status.id){if(admin.article.status.isArticle){admin.article.status.isArticle=false;admin.article.setStatus();admin.article.unPublish(true)}else{admin.article.update(false,true)}}else{admin.article.add(false,true);admin.article.status.isArticle=false}},clearDraftTimer:function(){if(admin.article.autoSaveDraftTimer!==""){window.clearInterval(admin.article.autoSaveDraftTimer);admin.article.autoSaveDraftTimer=""}},validate:function(){var articleContent=admin.editors.articleEditor.getContent();if($("#title").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#title").focus().val("")}else{if(articleContent.replace(/\s/g,"")===""){$("#tipMsg").text(Label.contentEmptyLabel)}else{if($("#tag").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.tagsEmptyLabel);$("#tag").focus().val("")}else{return true}}}return false},unPublish:function(isAuto){var that=this;that._addDisabled();$.ajax({url:latkeConfig.servePath+"/console/article/unpublish/"+admin.article.status.id,type:"PUT",cache:false,success:function(result,textStatus){if(isAuto){$("#tipMsg").text(Label.autoSaveLabel);return}$("#tipMsg").text(result.msg);if(!result.sc){return}admin.selectTab("article/draft-list");admin.article.status.id=undefined;admin.article.isConfirm=false},complete:function(jqXHR,textStatus){that._removeDisabled();$("#loadMsg").text("");if(jqXHR.status===403){$.get("/admin-index.do");that.unPublish()}}})},trimUniqueArray:function(str){str=str.toString();var arr=str.split(",");for(var i=0;i<arr.length;i++){arr[i]=arr[i].replace(/(^\s*)|(\s*$)/g,"");if(arr[i]===""){arr.splice(i,1);i--}}var unique=$.unique(arr);return unique.toString()},prePost:function(){$("#loadMsg").text(Label.loadingLabel);admin.article.content="";if(!admin.editors.articleEditor.getContent){return}var articleContent=admin.editors.articleEditor.getContent();if(window.location.hash==="#article/article"&&articleContent.replace(/\s/g,"")!==""){if(confirm(Label.editorPostLabel)){admin.article.clear()}}$("#tipMsg").text("");$("#loadMsg").text("")},_addDisabled:function(){$("#unSubmitArticle").attr("disabled","disabled");$("#saveArticle").attr("disabled","disabled");$("#submitArticle").attr("disabled","disabled")},_removeDisabled:function(){$("#unSubmitArticle").removeAttr("disabled");$("#saveArticle").removeAttr("disabled");$("#submitArticle").removeAttr("disabled")}};admin.register.article={obj:admin.article,init:admin.article.init,refresh:function(){$("#loadMsg").text("");$("#tipMsg").text("")}};admin.comment={open:function(id,fromId){this.getList(id,fromId);$("#"+fromId+"Comments").dialog("open")},getList:function(onId,fromId){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$("#"+fromId+"Comments").html("");var from="article";if(fromId==="page"){from="page"}$.ajax({url:latkeConfig.servePath+"/console/comments/"+from+"/"+onId,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var comments=result.comments,commentsHTML="";for(var i=0;i<comments.length;i++){var hrefHTML="<a target='_blank' href='"+comments[i].commentURL+"'>",content=comments[i].commentContent,contentHTML=Util.replaceEmString(content);if(comments[i].commentURL==="http://"){hrefHTML="<a target='_blank'>"}commentsHTML+="<div class='comment-title'><span class='left'>"+hrefHTML+comments[i].commentName+"</a>";if(comments[i].commentOriginalCommentName){commentsHTML+="@"+comments[i].commentOriginalCommentName}commentsHTML+="</span><span title='"+Label.removeLabel+"' class='right deleteIcon' onclick=\"admin.comment.del('"+comments[i].oId+"', '"+fromId+"', '"+onId+"')\"></span><span class='right'><a href='mailto:"+comments[i].commentEmail+"'>"+comments[i].commentEmail+"</a>&nbsp;&nbsp;"+$.bowknot.getDate(comments[i].commentTime)+"&nbsp;</span><div class='clear'></div></div><div class='margin12'>"+contentHTML+"</div>"}if(""===commentsHTML){commentsHTML=Label.noCommentLabel}$("#"+fromId+"Comments").html(commentsHTML);$("#loadMsg").text("")}})},del:function(id,fromId,articleId){var isDelete=confirm(Label.confirmRemoveLabel+Label.commentLabel+"?");if(isDelete){$("#loadMsg").text(Label.loadingLabel);var from="article";if(fromId==="page"){from="page"}$.ajax({url:latkeConfig.servePath+"/console/"+from+"/comment/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.comment.getList(articleId,fromId);$("#loadMsg").text("")}})}}};admin.articleList={tablePagination:new TablePaginate("article"),init:function(page){this.tablePagination.buildTable([{text:Label.titleLabel,index:"title",minWidth:110,style:"padding-left: 12px;font-size:14px;"},{text:Label.authorLabel,index:"author",width:150,style:"padding-left: 12px;"},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"},{text:Label.viewLabel,width:60,index:"articleViewCount",style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page)},getList:function(pageNum){var that=this;$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/articles/status/published/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var articles=result.articles,articleData=[];for(var i=0;i<articles.length;i++){articleData[i]={};articleData[i].title="<a href='"+latkeConfig.servePath+articles[i].articlePermalink+"' target='_blank' title='"+articles[i].articleTitle+"' class='no-underline'>"+articles[i].articleTitle+"</a><span class='table-tag'>"+articles[i].articleTags+"</span>";articleData[i].date=$.bowknot.getDate(articles[i].articleCreateTime);articleData[i].comments=articles[i].articleCommentCount;articleData[i].articleViewCount=articles[i].articleViewCount;articleData[i].author=articles[i].authorName;var topClass=articles[i].articlePutTop?Label.cancelPutTopLabel:Label.putTopLabel;articleData[i].expendRow="<a target='_blank' href='"+latkeConfig.servePath+articles[i].articlePermalink+"'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.get('"+articles[i].oId+"', true)\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.del('"+articles[i].oId+"', 'article', '"+articles[i].articleTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.articleList.popTop(this, '"+articles[i].oId+"')\">"+topClass+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+articles[i].oId+"', 'article')\">"+Label.commentLabel+"</a>"}that.tablePagination.updateTablePagination(articleData,pageNum,result.pagination);$("#loadMsg").text("")}})},popTop:function(it,id){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var $it=$(it),ajaxUrl="canceltop",tip=Label.putTopLabel;if($it.html()===Label.putTopLabel){ajaxUrl="puttop";tip=Label.cancelPutTopLabel}$.ajax({url:latkeConfig.servePath+"/console/article/"+ajaxUrl+"/"+id,type:"PUT",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$it.html(tip);$("#loadMsg").text("")}})}};admin.register["article-list"]={obj:admin.articleList,init:admin.articleList.init,refresh:admin.articleList.getList};admin.draftList={tablePagination:new TablePaginate("draft"),init:function(page){this.tablePagination.buildTable([{text:Label.titleLabel,index:"title",minWidth:110,style:"padding-left: 12px;font-size:14px;"},{text:Label.authorLabel,index:"author",width:150,style:"padding-left: 12px;"},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"},{text:Label.viewLabel,width:60,index:"articleViewCount",style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page)},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);var that=this;$.ajax({url:latkeConfig.servePath+"/console/articles/status/unpublished/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var articles=result.articles,articleData=[];for(var i=0;i<articles.length;i++){articleData[i]={};articleData[i].tags=articles[i].articleTags;articleData[i].date=$.bowknot.getDate(articles[i].articleCreateTime);articleData[i].comments=articles[i].articleCommentCount;articleData[i].articleViewCount=articles[i].articleViewCount;articleData[i].author=articles[i].authorName;articleData[i].title="<a class='no-underline' href='"+latkeConfig.servePath+articles[i].articlePermalink+"' target='_blank'>"+articles[i].articleTitle+"</a><span class='table-tag'>"+articles[i].articleTags+"</span>";articleData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.article.get('"+articles[i].oId+"', false);\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.article.del('"+articles[i].oId+"', 'draft', '"+articles[i].articleTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+articles[i].oId+"', 'draft')\">"+Label.commentLabel+"</a>"}that.tablePagination.updateTablePagination(articleData,pageNum,result.pagination);$("#loadMsg").text("")}})}};admin.register["draft-list"]={obj:admin.draftList,init:admin.draftList.init,refresh:admin.draftList.getList};admin.pageList={tablePagination:new TablePaginate("page"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},id:"",type:"link",init:function(page){this.tablePagination.buildTable([{text:"",index:"pageOrder",width:60,style:"padding-left: 12px;font-size:14px;"},{style:"padding-left: 12px;",text:Label.titleLabel,index:"pageTitle",width:300},{style:"padding-left: 12px;",text:Label.permalinkLabel,index:"pagePermalink",minWidth:300},{style:"padding-left: 12px;",text:Label.openMethodLabel,index:"pageTarget",width:120},{style:"padding-left: 12px;",text:Label.typeLabel,index:"pageType",width:80},{text:Label.commentLabel,index:"comments",width:80,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.tablePagination.initCommentsDialog();this.getList(page);var language=Label.localeString.substring(0,2);if(language==="zh"){language="zh-cn"}admin.editors.pageEditor=new Editor({language:language,kind:"all",id:"pageContent"});$(".fn-type").click(function(){var $it=$(this);if($it.hasClass("selected")){return}$(".fn-type").removeClass("selected");$it.addClass("selected");admin.pageList.type=$it.data("type");if(admin.pageList.type==="page"){$("#pagePagePanel").slideDown();if(Label.editorType==="CodeMirror-Markdown"&&admin.editors.pageEditor.getContent()===""){admin.editors.pageEditor.setContent("")}}else{$("#pagePagePanel").slideUp()}})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var that=this;$.ajax({url:latkeConfig.servePath+"/console/pages/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pages=result.pages;var pageData=[];admin.pageList.pageInfo.currentCount=pages.length;admin.pageList.pageInfo.pageCount=result.pagination.paginationPageCount===0?1:result.pagination.paginationPageCount;for(var i=0;i<pages.length;i++){pageData[i]={};if(i===0){if(pages.length===1){pageData[i].pageOrder=""}else{pageData[i].pageOrder='<div class="table-center" style="width:14px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'down\');" class="table-downIcon"></span></div>'}}else{if(i===pages.length-1){pageData[i].pageOrder='<div class="table-center" style="width:14px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> </div>'}else{pageData[i].pageOrder='<div class="table-center" style="width:38px"> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> <span onclick="admin.pageList.changeOrder('+pages[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}pageData[i].pageTitle="<a class='no-underline' href='"+pages[i].pagePermalink+"' target='_blank'>"+pages[i].pageTitle+"</a>";pageData[i].pagePermalink="<a class='no-underline' href='"+pages[i].pagePermalink+"' target='_blank'>"+pages[i].pagePermalink+"</a>";pageData[i].pageTarget=pages[i].pageOpenTarget;pageData[i].pageType=pages[i].pageType;pageData[i].comments=pages[i].pageCommentCount;pageData[i].expendRow="<span><a href='"+pages[i].pagePermalink+"' target='_blank'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.pageList.get('"+pages[i].oId+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.pageList.del('"+pages[i].oId+"', '"+pages[i].pageTitle+"')\">"+Label.removeLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.comment.open('"+pages[i].oId+"', 'page')\">"+Label.commentLabel+"</a></span>"}that.tablePagination.updateTablePagination(pageData,pageNum,result.pagination);$("#loadMsg").text("")}})},get:function(id){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/page/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id=id;$("#pageTitle").val(result.page.pageTitle);$("#pagePermalink").val(result.page.pagePermalink);$("#pageTarget").val(result.page.pageOpenTarget);if(result.page.pageType==="page"){$($(".fn-type").get(1)).click()}else{$($(".fn-type").get(0)).click()}$("#pageCommentable").prop("checked",result.page.pageCommentable);admin.editors.pageEditor.setContent(result.page.pageContent);$("#loadMsg").text("")}})},del:function(id,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.navLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/page/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.pageList.pageInfo.currentPage;if(admin.pageList.pageInfo.currentCount===1&&admin.pageList.pageInfo.pageCount!==1&&admin.pageList.pageInfo.currentPage===admin.pageList.pageInfo.pageCount){admin.pageList.pageInfo.pageCount--;pageNum=admin.pageList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum==hashList[hashList.length-1]){admin.pageList.getList(pageNum)}else{admin.setHashByPage(pageNum)}$("#loadMsg").text("")}})}},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var pageContent=admin.editors.pageEditor.getContent();var pagePermalink=$("#pagePermalink").val().replace(/(^\s*)|(\s*$)/g,"");if(admin.pageList.type==="link"){pagePermalink=Util.proessURL(pagePermalink)}var requestJSONObject={page:{pageTitle:$("#pageTitle").val(),pageContent:pageContent,pagePermalink:pagePermalink,pageCommentable:$("#pageCommentable").prop("checked"),pageType:admin.pageList.type,pageOpenTarget:$("#pageTarget").val()}};$.ajax({url:latkeConfig.servePath+"/console/page/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id="";$("#pagePermalink").val("");$("#pageTitle").val("");$("#pageCommentable").prop("cheked",false);$("#pageTarget").val("_self");$($(".fn-type").get(0)).click();admin.editors.pageEditor.setContent("");if(admin.pageList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.pageList.pageInfo.currentPage===admin.pageList.pageInfo.pageCount){admin.pageList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.pageList.pageInfo.pageCount==hashList[hashList.length-1]){admin.pageList.getList(admin.pageList.pageInfo.pageCount)}else{admin.setHashByPage(admin.pageList.pageInfo.pageCount)}$("#loadMsg").text("")}})}},update:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var pageContent=admin.editors.pageEditor.getContent();var pagePermalink=$("#pagePermalink").val().replace(/(^\s*)|(\s*$)/g,"");if(admin.pageList.type==="link"){pagePermalink=Util.proessURL(pagePermalink)}var requestJSONObject={page:{pageTitle:$("#pageTitle").val(),oId:this.id,pageContent:pageContent,pagePermalink:pagePermalink,pageCommentable:$("#pageCommentable").prop("checked"),pageType:admin.pageList.type,pageOpenTarget:$("#pageTarget").val()}};$.ajax({url:latkeConfig.servePath+"/console/page/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pageList.id="";admin.pageList.getList(admin.pageList.pageInfo.currentPage);$("#pageTitle").val("");$("#pagePermalink").val("");$("#pageCommentable").prop("cheked",false);$("#pageTarget").val("_self");$($(".fn-type").get(0)).click();admin.editors.pageEditor.setContent("");$("#loadMsg").text("")}})}},validate:function(){if($("#pageTitle").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#pageTitle").focus()}else{if(admin.pageList.type==="link"&&$("#pagePermalink").val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.linkEmptyLabel)}else{return true}}return false},submit:function(){if(this.id!==""){this.update()}else{this.add()}},changeOrder:function(id,order,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:id.toString(),direction:status};$.ajax({url:latkeConfig.servePath+"/console/page/order/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);admin.pageList.getList(admin.pageList.pageInfo.currentPage);$("#loadMsg").text("")}})}};admin.register["page-list"]={obj:admin.pageList,init:admin.pageList.init,refresh:admin.pageList.getList};admin.others={init:function(){$("#tabOthers").tabs();$.ajax({url:latkeConfig.servePath+"/console/reply/notification/template",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#replayEmailTemplateTitle").val(result.replyNotificationTemplate.subject);$("#replayEmailTemplateBody").val(result.replyNotificationTemplate.body);$("#loadMsg").text("")}})},removeUnusedTags:function(){$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/tag/unused",type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg)}})},getUnusedTags:function(){$.ajax({url:latkeConfig.servePath+"/console/tag/unused",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var unusedTags=result.unusedTags;if(0===unusedTags.length){return}}})},update:function(){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={replyNotificationTemplate:{subject:$("#replayEmailTemplateTitle").val(),body:$("#replayEmailTemplateBody").val()}};$.ajax({url:latkeConfig.servePath+"/console/reply/notification/template",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);$("#loadMsg").text("")}})}};admin.register.others={obj:admin.others,init:admin.others.init,refresh:function(){admin.clearTip()}};admin.linkList={tablePagination:new TablePaginate("link"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},id:"",init:function(page){this.tablePagination.buildTable([{text:"",index:"linkOrder",width:60},{style:"padding-left: 12px;",text:Label.linkTitleLabel,index:"linkTitle",width:230},{style:"padding-left: 12px;",text:Label.urlLabel,index:"linkAddress",minWidth:180},{style:"padding-left: 12px;",text:Label.linkDescriptionLabel,index:"linkDescription",width:360}]);this.tablePagination.initPagination();this.getList(page);$("#updateLink").dialog({width:700,height:180,modal:true,hideFooter:true})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);if(pageNum===0){pageNum=1}this.pageInfo.currentPage=pageNum;var that=this;$.ajax({url:latkeConfig.servePath+"/console/links/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var links=result.links;var linkData=[];admin.linkList.pageInfo.currentCount=links.length;admin.linkList.pageInfo.pageCount=result.pagination.paginationPageCount===0?1:result.pagination.paginationPageCount;for(var i=0;i<links.length;i++){linkData[i]={};if(i===0){if(links.length===1){linkData[i].linkOrder=""}else{linkData[i].linkOrder='<div class="table-center" style="width:14px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}else{if(i===links.length-1){linkData[i].linkOrder='<div class="table-center" style="width:14px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> </div>'}else{linkData[i].linkOrder='<div class="table-center" style="width:38px"> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'up\');" class="table-upIcon"></span> <span onclick="admin.linkList.changeOrder('+links[i].oId+", "+i+', \'down\');" class="table-downIcon"></span> </div>'}}linkData[i].linkTitle=links[i].linkTitle;linkData[i].linkAddress="<a target='_blank' class='no-underline' href='"+links[i].linkAddress+"'>"+links[i].linkAddress+"</a>";linkData[i].linkDescription=links[i].linkDescription;linkData[i].expendRow="<span><a href='"+links[i].linkAddress+"' target='_blank'>"+Label.viewLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.linkList.get('"+links[i].oId+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.linkList.del('"+links[i].oId+"', '"+links[i].linkTitle+"')\">"+Label.removeLabel+"</a></span>"}that.tablePagination.updateTablePagination(linkData,pageNum,result.pagination);$("#loadMsg").text("")}})},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={link:{linkTitle:$("#linkTitle").val(),linkAddress:$("#linkAddress").val(),linkDescription:$("#linkDescription").val()}};$.ajax({url:latkeConfig.servePath+"/console/link/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#linkTitle").val("");$("#linkAddress").val("");$("#linkDescription").val("");if(admin.linkList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.linkList.pageInfo.currentPage===admin.linkList.pageInfo.pageCount){admin.linkList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.linkList.pageInfo.pageCount!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(admin.linkList.pageInfo.pageCount)}admin.linkList.getList(admin.linkList.pageInfo.pageCount);$("#loadMsg").text("")}})}},get:function(id){$("#loadMsg").text(Label.loadingLabel);$("#updateLink").dialog("open");$.ajax({url:latkeConfig.servePath+"/console/link/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.linkList.id=id;$("#linkTitleUpdate").val(result.link.linkTitle);$("#linkAddressUpdate").val(result.link.linkAddress);$("#linkDescriptionUpdate").val(result.link.linkDescription);$("#loadMsg").text("")}})},update:function(){if(this.validate("Update")){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={link:{linkTitle:$("#linkTitleUpdate").val(),oId:this.id,linkAddress:$("#linkAddressUpdate").val(),linkDescription:$("#linkDescriptionUpdate").val()}};$.ajax({url:latkeConfig.servePath+"/console/link/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#updateLink").dialog("close");$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.linkList.getList(admin.linkList.pageInfo.currentPage);$("#loadMsg").text("")}})}},del:function(id,title){var isDelete=confirm(Label.confirmRemoveLabel+Label.permalinkLabel+'"'+title+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/link/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.linkList.pageInfo.currentPage;if(admin.linkList.pageInfo.currentCount===1&&admin.linkList.pageInfo.pageCount!==1&&admin.linkList.pageInfo.currentPage===admin.linkList.pageInfo.pageCount){admin.linkList.pageInfo.pageCount--;pageNum=admin.linkList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.linkList.getList(pageNum);$("#loadMsg").text("")}})}},validate:function(status){if(!status){status=""}if($("#linkTitle"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.titleEmptyLabel);$("#linkTitle"+status).focus().val("")}else{if($("#linkAddress"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.addressEmptyLabel);$("#linkAddress"+status).focus().val("")}else{if(!/^\w+:\/\//.test($("#linkAddress"+status).val())){$("#tipMsg").text(Label.addressInvalidLabel);$("#linkAddress"+status).focus().val("")}else{return true}}}return false},changeOrder:function(id,order,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:id.toString(),direction:status};$.ajax({url:latkeConfig.servePath+"/console/link/order/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);admin.linkList.getList(admin.linkList.pageInfo.currentPage);$("#loadMsg").text("")}})}};admin.register["link-list"]={obj:admin.linkList,init:admin.linkList.init,refresh:admin.linkList.getList};admin.preference={locale:"",editorType:"",init:function(){$("#tabPreference").tabs();$.ajax({url:latkeConfig.servePath+"/console/preference/",type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var preference=result.preference;$("#metaKeywords").val(preference.metaKeywords),$("#metaDescription").val(preference.metaDescription),$("#blogTitle").val(preference.blogTitle),$("#blogSubtitle").val(preference.blogSubtitle),$("#mostCommentArticleDisplayCount").val(preference.mostCommentArticleDisplayCount);$("#mostViewArticleDisplayCount").val(preference.mostViewArticleDisplayCount),$("#recentCommentDisplayCount").val(preference.recentCommentDisplayCount);$("#mostUsedTagDisplayCount").val(preference.mostUsedTagDisplayCount);$("#articleListDisplayCount").val(preference.articleListDisplayCount);$("#articleListPaginationWindowSize").val(preference.articleListPaginationWindowSize);$("#localeString").val(preference.localeString);$("#timeZoneId").val(preference.timeZoneId);$("#noticeBoard").val(preference.noticeBoard);$("#htmlHead").val(preference.htmlHead);$("#externalRelevantArticlesDisplayCount").val(preference.externalRelevantArticlesDisplayCount);$("#relevantArticlesDisplayCount").val(preference.relevantArticlesDisplayCount);$("#randomArticlesDisplayCount").val(preference.randomArticlesDisplayCount);$("#keyOfSolo").val(preference.keyOfSolo);preference.enableArticleUpdateHint?$("#enableArticleUpdateHint").attr("checked","checked"):$("#enableArticleUpdateHint").removeAttr("checked");preference.allowVisitDraftViaPermalink?$("#allowVisitDraftViaPermalink").attr("checked","checked"):$("allowVisitDraftViaPermalink").removeAttr("checked");admin.preference.locale=preference.localeString;admin.preference.editorType=preference.editorType;$("#skinMain").data("skinDirName",preference.skinDirName);var skins=eval("("+preference.skins+")");var skinsHTML="";for(var i=0;i<skins.length;i++){var selectedClass="";if(skins[i].skinName===preference.skinName&&skins[i].skinDirName===preference.skinDirName){selectedClass+=" selected"}skinsHTML+="<div title='"+skins[i].skinDirName+"' class='left skinItem"+selectedClass+"'><img class='skinPreview' src='"+latkeConfig.staticServePath+"/skins/"+skins[i].skinDirName+"/preview.png'/><div>"+skins[i].skinName+"</div></div>"}$("#skinMain").append(skinsHTML+"<div class='clear'></div>");$(".skinItem").click(function(){$(".skinItem").removeClass("selected");$(this).addClass("selected");$("#skinMain").data("skinDirName",this.title)});var signs=eval("("+preference.signs+")");for(var j=1;j<signs.length;j++){$("#preferenceSign"+j).val(signs[j].signHTML);$("#preferenceSignButton"+j).tip({content:signs[j].signHTML===""?Label.signIsNullLabel:signs[j].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""),position:"bottom"})}$("#articleListDisplay").val(preference.articleListStyle);$("#editorType").val(preference.editorType);$("#feedOutputMode").val(preference.feedOutputMode);$("#feedOutputCnt").val(preference.feedOutputCnt);preference.commentable?$("#commentable").attr("checked","checked"):$("commentable").removeAttr("checked");$("#loadMsg").text("")}})},validate:function(){if(!/^\d+$/.test($("#mostUsedTagDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexTagDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostUsedTagDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#recentCommentDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexRecentCommentDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#recentCommentDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#mostCommentArticleDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexMostCommentArticleDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostCommentArticleDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#mostViewArticleDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.indexMostViewArticleDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#mostViewArticleDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#articleListDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.pageSizeLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#articleListDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#articleListPaginationWindowSize").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.windowSizeLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#articleListPaginationWindowSize").focus();return false}else{if(!/^\d+$/.test($("#randomArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.randomArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#randomArticlesDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#relevantArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.relevantArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#relevantArticlesDisplayCount").focus();return false}else{if(!/^\d+$/.test($("#externalRelevantArticlesDisplayCount").val())){$("#tipMsg").text("["+Label.paramSettingsLabel+" - "+Label.externalRelevantArticlesDisplayCntLabel+"] "+Label.nonNegativeIntegerOnlyLabel);$("#externalRelevantArticlesDisplayCount").focus();return false}}}}}}}}}return true},update:function(){if(!admin.preference.validate()){return}$("#tipMsg").text("");$("#loadMsg").text(Label.loadingLabel);var signs=[{oId:0,signHTML:""},{oId:1,signHTML:$("#preferenceSign1").val()},{oId:2,signHTML:$("#preferenceSign2").val()},{oId:3,signHTML:$("#preferenceSign3").val()}];var requestJSONObject={preference:{metaKeywords:$("#metaKeywords").val(),metaDescription:$("#metaDescription").val(),blogTitle:$("#blogTitle").val(),blogSubtitle:$("#blogSubtitle").val(),mostCommentArticleDisplayCount:$("#mostCommentArticleDisplayCount").val(),mostViewArticleDisplayCount:$("#mostViewArticleDisplayCount").val(),recentCommentDisplayCount:$("#recentCommentDisplayCount").val(),mostUsedTagDisplayCount:$("#mostUsedTagDisplayCount").val(),articleListDisplayCount:$("#articleListDisplayCount").val(),articleListPaginationWindowSize:$("#articleListPaginationWindowSize").val(),skinDirName:$("#skinMain").data("skinDirName"),localeString:$("#localeString").val(),timeZoneId:$("#timeZoneId").val(),noticeBoard:$("#noticeBoard").val(),htmlHead:$("#htmlHead").val(),externalRelevantArticlesDisplayCount:$("#externalRelevantArticlesDisplayCount").val(),relevantArticlesDisplayCount:$("#relevantArticlesDisplayCount").val(),randomArticlesDisplayCount:$("#randomArticlesDisplayCount").val(),enableArticleUpdateHint:$("#enableArticleUpdateHint").prop("checked"),signs:signs,keyOfSolo:$("#keyOfSolo").val(),allowVisitDraftViaPermalink:$("#allowVisitDraftViaPermalink").prop("checked"),articleListStyle:$("#articleListDisplay").val(),editorType:$("#editorType").val(),feedOutputMode:$("#feedOutputMode").val(),feedOutputCnt:$("#feedOutputCnt").val(),commentable:$("#commentable").prop("checked")}};$.ajax({url:latkeConfig.servePath+"/console/preference/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}if($("#localeString").val()!==admin.preference.locale||$("#editorType").val()!==admin.preference.editorType){window.location.reload()}for(var i=1;i<signs.length;i++){if($("#articleSign"+signs[i].oId).length===1){$("#articleSign"+signs[i].oId).tip("option","content",signs[i].signHTML===""?Label.signIsNullLabel:signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""))}$("#preferenceSignButton"+signs[i].oId).tip("option","content",signs[i].signHTML===""?Label.signIsNullLabel:signs[i].signHTML.replace(/\n/g,"").replace(/<script.*<\/script>/ig,""))}$("#loadMsg").text("")}})}};admin.register.preference={obj:admin.preference,init:admin.preference.init,refresh:function(){admin.clearTip()}};admin.pluginList={tablePagination:new TablePaginate("plugin"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},init:function(page){this.tablePagination.buildTable([{style:"padding-left: 12px;",text:Label.pluginNameLabel,index:"name",width:230},{style:"padding-left: 12px;",text:Label.statusLabel,index:"status",minWidth:180},{style:"padding-left: 12px;",text:Label.authorLabel,index:"author",width:200},{style:"padding-left: 12px;",text:Label.versionLabel,index:"version",width:120}]);this.tablePagination.initPagination();$("#pluginSetting").dialog({width:700,height:180,modal:true,hideFooter:true});this.getList(page)},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var that=this;$.ajax({url:latkeConfig.servePath+"/console/plugins/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.pluginList.pageInfo.currentPage=pageNum;var datas=result.plugins;for(var i=0;i<datas.length;i++){datas[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.pluginList.changeStatus('"+datas[i].oId+"', '"+datas[i].status+"')\">";if(datas[i].status==="ENABLED"){datas[i].status=Label.enabledLabel;datas[i].expendRow+=Label.disableLabel}else{datas[i].status=Label.disabledLabel;datas[i].expendRow+=Label.enableLabel}datas[i].expendRow+="</a> ";if(datas[i].setting!="{}"){datas[i].expendRow+="<a href='javascript:void(0)' onclick=\"admin.pluginList.toSetting('"+datas[i].oId+"')\"> "+Label.settingLabel+" </a> "}}that.tablePagination.updateTablePagination(result.plugins,pageNum,result.pagination);$("#loadMsg").text("")}})},toSetting:function(pluginId){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={oId:pluginId};$.ajax({url:latkeConfig.servePath+"/console/plugin/toSetting",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);$("#pluginSetting").html(result);$("#pluginSetting").dialog("open");$("#loadMsg").text("")}})},changeStatus:function(pluginId,status){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");if(status==="ENABLED"){status="DISABLED"}else{status="ENABLED"}var requestJSONObject={oId:pluginId,status:status};$.ajax({url:latkeConfig.servePath+"/console/plugin/status/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#loadMsg").text("");window.location.reload()}})}};admin.register["plugin-list"]={obj:admin.pluginList,init:admin.pluginList.init,refresh:function(){admin.claerTip()}};admin.userList={tablePagination:new TablePaginate("user"),pageInfo:{currentCount:1,pageCount:1,currentPage:1},userInfo:{oId:"",userRole:""},init:function(page){this.tablePagination.buildTable([{style:"padding-left: 12px;",text:Label.commentNameLabel,index:"userName",width:230},{style:"padding-left: 12px;",text:Label.commentEmailLabel,index:"userEmail",minWidth:180},{style:"padding-left: 12px;",text:Label.roleLabel,index:"isAdmin",width:120}]);this.tablePagination.initPagination();this.getList(page);$("#userUpdate").dialog({width:700,height:230,modal:true,hideFooter:true})},getList:function(pageNum){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");this.pageInfo.currentPage=pageNum;var that=this;$.ajax({url:latkeConfig.servePath+"/console/users/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var users=result.users;var userData=[];admin.userList.pageInfo.currentCount=users.length;admin.userList.pageInfo.pageCount=result.pagination.paginationPageCount;if(users.length<1){$("#tipMsg").text("No user "+Label.reportIssueLabel);$("#loadMsg").text("");return}for(var i=0;i<users.length;i++){userData[i]={};userData[i].userName=users[i].userName;userData[i].userEmail=users[i].userEmail;if("adminRole"===users[i].userRole){userData[i].isAdmin="&nbsp;"+Label.administratorLabel;userData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.userList.get('"+users[i].oId+"', '"+users[i].userRole+"')\">"+Label.updateLabel+"</a>"}else{userData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.userList.get('"+users[i].oId+"', '"+users[i].userRole+"')\">"+Label.updateLabel+"</a> <a href='javascript:void(0)' onclick=\"admin.userList.del('"+users[i].oId+"', '"+users[i].userName+"')\">"+Label.removeLabel+"</a><a href='javascript:void(0)' onclick=\"admin.userList.changeRole('"+users[i].oId+"')\">"+Label.changeRoleLabel+"</a>";if("defaultRole"===users[i].userRole){userData[i].isAdmin=Label.commonUserLabel}else{userData[i].isAdmin=Label.visitorUserLabel}}that.tablePagination.updateTablePagination(userData,pageNum,result.pagination);$("#loadMsg").text("")}}})},add:function(){if(this.validate()){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var requestJSONObject={userName:$("#userName").val(),userEmail:$("#userEmail").val(),userURL:$("#userURL").val(),userPassword:$("#userPassword").val()};$.ajax({url:latkeConfig.servePath+"/console/user/",type:"POST",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}$("#userName").val("");$("#userEmail").val("");$("#userURL").val("");$("#userPassword").val("");if(admin.userList.pageInfo.currentCount===Label.PAGE_SIZE&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount++}var hashList=window.location.hash.split("/");if(admin.userList.pageInfo.pageCount!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(admin.userList.pageInfo.pageCount)}admin.userList.getList(admin.userList.pageInfo.pageCount);$("#loadMsg").text("")}})}},get:function(id,userRole){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$("#userUpdate").dialog("open");$.ajax({url:latkeConfig.servePath+"/console/user/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var $userEmailUpdate=$("#userEmailUpdate");$("#userNameUpdate").val(result.user.userName).data("userInfo",{oId:id,userRole:userRole});$userEmailUpdate.val(result.user.userEmail);if("adminRole"===userRole){$userEmailUpdate.attr("disabled","disabled")}else{$userEmailUpdate.removeAttr("disabled")}$("#userURLUpdate").val(result.user.userURL);$("#userPasswordUpdate").val(result.user.userPassword);$("#loadMsg").text("")}})},update:function(){if(this.validate("Update")){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");var userInfo=$("#userNameUpdate").data("userInfo");var requestJSONObject={userName:$("#userNameUpdate").val(),oId:userInfo.oId,userEmail:$("#userEmailUpdate").val(),userURL:$("#userURLUpdate").val(),userRole:userInfo.userRole,userPassword:$("#userPasswordUpdate").val()};$.ajax({url:latkeConfig.servePath+"/console/user/",type:"PUT",cache:false,data:JSON.stringify(requestJSONObject),success:function(result,textStatus){$("#userUpdate").dialog("close");$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.userList.getList(admin.userList.pageInfo.currentPage);$("#loadMsg").text("")}})}},del:function(id,userName){var isDelete=confirm(Label.confirmRemoveLabel+Label.userLabel+'"'+userName+'"?');if(isDelete){$("#loadMsg").text(Label.loadingLabel);$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/user/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.userList.pageInfo.currentPage;if(admin.userList.pageInfo.currentCount===1&&admin.userList.pageInfo.pageCount!==1&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount--;pageNum=admin.userList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.userList.getList(pageNum);$("#loadMsg").text("")}})}},changeRole:function(id){$("#tipMsg").text("");$.ajax({url:latkeConfig.servePath+"/console/changeRole/"+id,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}var pageNum=admin.userList.pageInfo.currentPage;if(admin.userList.pageInfo.currentCount===1&&admin.userList.pageInfo.pageCount!==1&&admin.userList.pageInfo.currentPage===admin.userList.pageInfo.pageCount){admin.userList.pageInfo.pageCount--;pageNum=admin.userList.pageInfo.pageCount}var hashList=window.location.hash.split("/");if(pageNum!==parseInt(hashList[hashList.length-1])){admin.setHashByPage(pageNum)}admin.userList.getList(pageNum);$("#loadMsg").text("")}})},validate:function(status){if(!status){status=""}var userName=$("#userName"+status).val().replace(/(^\s*)|(\s*$)/g,"");if(2>userName.length||userName.length>20){$("#tipMsg").text(Label.nameTooLongLabel);$("#userName"+status).focus()}else{if($("#userEmail"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.mailCannotEmptyLabel);$("#userEmail"+status).focus()}else{if(!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($("#userEmail"+status).val())){$("#tipMsg").text(Label.mailInvalidLabel);$("#userEmail"+status).focus()}else{if($("#userPassword"+status).val().replace(/\s/g,"")===""){$("#tipMsg").text(Label.passwordEmptyLabel);$("#userPassword"+status).focus()}else{return true}}}}return false}};admin.register["user-list"]={obj:admin.userList,init:admin.userList.init,refresh:function(){admin.clearTip()}};admin.commentList={tablePagination:new TablePaginate("comment"),pageInfo:{currentPage:1},init:function(page){this.tablePagination.buildTable([{text:Label.commentContentLabel,index:"content",minWidth:300,style:"padding-left: 12px;"},{text:Label.authorLabel,index:"title",width:230,style:"padding-left: 12px;"},{text:Label.createDateLabel,index:"date",width:90,style:"padding-left: 12px;"}]);this.tablePagination.initPagination();this.getList(page)},getList:function(pageNum){var that=this;$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/comments/"+pageNum+"/"+Label.PAGE_SIZE+"/"+Label.WINDOW_SIZE,type:"GET",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}that.pageInfo.currentPage=pageNum;var comments=result.comments,commentsData=[];for(var i=0;i<comments.length;i++){var type="Article";if(comments[i].type==="pageComment"){type="Page"}commentsData[i]={};commentsData[i].content=Util.replaceEmString(comments[i].commentContent)+"<span class='table-tag'> on &nbsp;&nbsp;</span><a href='"+latkeConfig.servePath+comments[i].commentSharpURL+"' target='_blank'>"+comments[i].commentTitle+"</a>";commentsData[i].expendRow="<a href='javascript:void(0)' onclick=\"admin.commentList.del('"+comments[i].oId+"', '"+type+"')\">"+Label.removeLabel+"</a>";commentsData[i].title="<img class='small-head' src='"+comments[i].commentThumbnailURL+"'/>";if("http://"===comments[i].commentURL){commentsData[i].title+=comments[i].commentName}else{commentsData[i].title+="<a href='"+comments[i].commentURL+"' target='_blank' class='no-underline'>"+comments[i].commentName+"</a>"}commentsData[i].title+="<br/><a href='mailto:"+comments[i].commentEmail+"'>"+comments[i].commentEmail+"</a>";commentsData[i].date=$.bowknot.getDate(comments[i].commentTime)}that.tablePagination.updateTablePagination(commentsData,pageNum,result.pagination);$("#loadMsg").text("")}})},del:function(id,type){if(confirm(Label.confirmRemoveLabel+Label.commentLabel+"?")){$("#loadMsg").text(Label.loadingLabel);$.ajax({url:latkeConfig.servePath+"/console/"+type.toLowerCase()+"/comment/"+id,type:"DELETE",cache:false,success:function(result,textStatus){$("#tipMsg").text(result.msg);if(!result.sc){$("#loadMsg").text("");return}admin.commentList.getList(admin.commentList.pageInfo.currentPage);$("#loadMsg").text("")}})}}};admin.register["comment-list"]={obj:admin.commentList,init:admin.commentList.init,refresh:admin.commentList.getList};var plugins={};admin.plugin={plugins:[],add:function(data){data.isInit=false;data.hash=data.path.replace("/","#")+"/"+data.id;this.plugins.push(data);var pathList=this._analysePath(data.path);if(data.index&&pathList.length<2){this._addNew(data,pathList)}},setCurByHash:function(tags){var pluginList=this.plugins;for(var i=0;i<pluginList.length;i++){var data=pluginList[i];var pathList=this._analysePath(data.path),isCurrentPlugin=false;if(data.index&&window.location.hash.indexOf(data.hash)>-1){isCurrentPlugin=true}else{if(data.path.replace("/","#")===window.location.hash||(window.location.hash==="#main"&&data.path.indexOf("/main/panel")>-1)){isCurrentPlugin=true}}if(isCurrentPlugin){if(data.isInit){if(plugins[data.id].refresh){plugins[data.id].refresh(tags.page)}}else{if(!data.index){this._addToExist(data,pathList)}else{if(pathList.length===2){this._addNew(data,pathList)}}plugins[data.id].init(tags.page);data.isInit=true}}}},_analysePath:function(path){var paths=path.split("/");paths.splice(0,1);return paths},_addNew:function(data,pathList){if(pathList.length===2){data.target=$("#tabPreference li").get(data.index-1);$("#tabPreference").tabs("add",data);return}else{if(pathList[0]===""){data.target=$("#tabs>ul>li").get(data.index-1)}else{if(pathList[0]==="article"){data.target=$("#tabArticleMgt>li").get(data.index-1)}else{if(pathList[0]==="tools"){admin.tools.push("#"+data.id);data.target=$("#tabTools>li").get(data.index-1)}}}}if(!data.target){alert("data.index is error!")}$("#tabs").tabs("add",data)},_addToExist:function(data,pathList){switch(pathList[0]){case"main":$("#mainPanel"+pathList[1].charAt(5)).append(data.content);break;case"tools":case"article":if(pathList.length===2){$("#tabsPanel_"+pathList[1]).append(data.content)}else{$("#tabPreferencePanel_"+pathList[2]).append(data.content)}break;case"comment-list":$("#tabsPanel_comment-list").append(data.content);break}}};admin.main={};admin.register.main={obj:admin.main,init:function(){admin.clearTip()},refresh:function(){admin.clearTip()}};admin.about={init:function(){$.ajax({url:"http://rhythm.b3log.org/version/solo/latest/"+Label.version,type:"GET",cache:false,dataType:"jsonp",success:function(data,textStatus){var version=data.soloVersion;if(version===Label.version){$("#aboutLatest").text(Label.upToDateLabel)}else{$("#aboutLatest").html(Label.outOfDateLabel+"<a href='"+data.soloDownload+"'>"+version+"</a>")}},complete:function(XHR,TS){admin.clearTip()}})}};admin.register.about={obj:admin.about,init:admin.about.init,refresh:function(){admin.clearTip()}};
\ No newline at end of file
/*
* Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Util={error:function(){$("#tipMsg").text("Error: "+arguments[0]+" File: "+arguments[1]+"\nLine: "+arguments[2]+" please report this issue on https://github.com/b3log/b3log-solo/issues/new");$("#loadMsg").text("")},killIE:function(){if($.browser.msie){if($.browser.version==="6.0"||$.browser.version==="7.0"){window.location=latkeConfig.servePath+"/kill-browser.html";return}if(window.external&&window.external.twGetRunPath){var path=external.twGetRunPath();if(path&&path.toLowerCase().indexOf("360se")>-1&&window.location.href.indexOf("admin-index")>-1){window.location=latkeConfig.servePath+"/kill-browser.html";return}}}},replaceEmString:function(str){var commentSplited=str.split("[em");if(commentSplited.length===1){return str}str=commentSplited[0];for(var j=1;j<commentSplited.length;j++){var key=commentSplited[j].substr(0,2);str+="<img src='"+latkeConfig.staticServePath+"/skins/"+Label.skinDirName+"/images/emotions/em"+key+".png' alt='"+Label["em"+key+"Label"]+"' title='"+Label["em"+key+"Label"]+"'/>"+commentSplited[j].substr(3)}return str},proessURL:function(url){if(!/^\w+:\/\//.test(url)){url="http://"+url}return url},switchMobile:function(skin){Cookie.createCookie("btouch_switch_toggle",skin,365);setTimeout(function(){location.reload()},1250)},setTopBar:function(){var $top=$("#top");if($top.length===1){var $showTop=$("#showTop");$showTop.click(function(){$top.slideDown();$showTop.hide()});$("#hideTop").click(function(){$top.slideUp();$showTop.show()})}},goTop:function(){var acceleration=acceleration||0.1;var y=$(window).scrollTop();var speed=1+acceleration;window.scrollTo(0,Math.floor(y/speed));if(y>0){var invokeFunction="Util.goTop("+acceleration+")";window.setTimeout(invokeFunction,16)}},goBottom:function(bottom){if(!bottom){bottom=0}window.scrollTo(0,$("body").height()-$(window).height()-bottom)},init:function(){Util.killIE();Util.setTopBar()},clearCache:function(all){var data="";if(all==="all"){data='{"all": "all", "URI": ""}'}else{data='{"all": "all", "URI": "'+window.location.pathname+'"}'}$.ajax({type:"POST",url:latkeConfig.servePath+"/clear-cache.do",cache:false,contentType:"application/json",data:data,success:function(result){window.location.reload()}})},replaceSideEm:function(comments){for(var i=0;i<comments.length;i++){var $comment=$(comments[i]);$comment.html(Util.replaceEmString($comment.html()))}},buildTags:function(id){id=id||"tags";var classes=["tags1","tags2","tags3","tags4","tags5"],bList=$("#"+id+" b").get();var max=parseInt($("#"+id+" b").last().text());var distance=Math.ceil(max/classes.length);for(var i=0;i<bList.length;i++){var num=parseInt(bList[i].innerHTML);for(var j=0;j<classes.length;j++){if(num>j*distance&&num<=(j+1)*distance){bList[i].parentNode.className=classes[j];break}}}$("#"+id).html($("#"+id+" li").get().sort(function(a,b){var valA=$(a).find("span").text().toLowerCase();var valB=$(b).find("span").text().toLowerCase();return valA.localeCompare(valB)}))},toDate:function(time,format){var dateTime=new Date(time);var o={"M+":dateTime.getMonth()+1,"d+":dateTime.getDate(),"H+":dateTime.getHours(),"m+":dateTime.getMinutes(),"s+":dateTime.getSeconds(),"q+":Math.floor((dateTime.getMonth()+3)/3),S:dateTime.getMilliseconds()};if(/(y+)/.test(format)){format=format.replace(RegExp.$1,(dateTime.getFullYear()+"").substr(4-RegExp.$1.length))}for(var k in o){if(new RegExp("("+k+")").test(format)){format=format.replace(RegExp.$1,RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length))}}return format}};if(!Cookie){var Cookie={readCookie:function(name){var nameEQ=name+"=";var ca=document.cookie.split(";");for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==" "){c=c.substring(1,c.length)}if(c.indexOf(nameEQ)==0){return decodeURIComponent(c.substring(nameEQ.length,c.length))}}return""},eraseCookie:function(name){this.createCookie(name,"",-1)},createCookie:function(name,value,days){var expires="";if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));expires="; expires="+date.toGMTString()}document.cookie=name+"="+encodeURIComponent(value)+expires+"; path=/"}}}; var Util={error:function(){$("#tipMsg").text("Error: "+arguments[0]+" File: "+arguments[1]+"\nLine: "+arguments[2]+" please report this issue on https://github.com/b3log/b3log-solo/issues/new");$("#loadMsg").text("")},killIE:function(){if($.browser.msie){if($.browser.version==="6.0"||$.browser.version==="7.0"){window.location=latkeConfig.servePath+"/kill-browser.html";return}if(window.external&&window.external.twGetRunPath){var path=external.twGetRunPath();if(path&&path.toLowerCase().indexOf("360se")>-1&&window.location.href.indexOf("admin-index")>-1){window.location=latkeConfig.servePath+"/kill-browser.html";return}}}},replaceEmString:function(str){var commentSplited=str.split("[em");if(commentSplited.length===1){return str}str=commentSplited[0];for(var j=1;j<commentSplited.length;j++){var key=commentSplited[j].substr(0,2);str+="<img src='"+latkeConfig.staticServePath+"/skins/"+Label.skinDirName+"/images/emotions/em"+key+".png' alt='"+Label["em"+key+"Label"]+"' title='"+Label["em"+key+"Label"]+"'/>"+commentSplited[j].substr(3)}return str},proessURL:function(url){if(!/^\w+:\/\//.test(url)){url="http://"+url}return url},switchMobile:function(skin){Cookie.createCookie("btouch_switch_toggle",skin,365);setTimeout(function(){location.reload()},1250)},setTopBar:function(){var $top=$("#top");if($top.length===1){var $showTop=$("#showTop");$showTop.click(function(){$top.slideDown();$showTop.hide()});$("#hideTop").click(function(){$top.slideUp();$showTop.show()})}},goTop:function(){var acceleration=acceleration||0.1;var y=$(window).scrollTop();var speed=1+acceleration;window.scrollTo(0,Math.floor(y/speed));if(y>0){var invokeFunction="Util.goTop("+acceleration+")";window.setTimeout(invokeFunction,16)}},goBottom:function(bottom){if(!bottom){bottom=0}window.scrollTo(0,$("body").height()-$(window).height()-bottom)},init:function(){Util.killIE();Util.setTopBar()},clearCache:function(all){var data="";if(all==="all"){data='{"all": "all", "URI": ""}'}else{data='{"all": "all", "URI": "'+window.location.pathname+'"}'}$.ajax({type:"POST",url:latkeConfig.servePath+"/clear-cache.do",cache:false,contentType:"application/json",data:data,success:function(result){window.location.reload()}})},replaceSideEm:function(comments){for(var i=0;i<comments.length;i++){var $comment=$(comments[i]);$comment.html(Util.replaceEmString($comment.html()))}},buildTags:function(id){id=id||"tags";var classes=["tags1","tags2","tags3","tags4","tags5"],bList=$("#"+id+" b").get();var max=parseInt($("#"+id+" b").last().text());var distance=Math.ceil(max/classes.length);for(var i=0;i<bList.length;i++){var num=parseInt(bList[i].innerHTML);for(var j=0;j<classes.length;j++){if(num>j*distance&&num<=(j+1)*distance){bList[i].parentNode.className=classes[j];break}}}$("#"+id).html($("#"+id+" li").get().sort(function(a,b){var valA=$(a).find("span").text().toLowerCase();var valB=$(b).find("span").text().toLowerCase();return valA.localeCompare(valB)}))},toDate:function(time,format){var dateTime=new Date(time);var o={"M+":dateTime.getMonth()+1,"d+":dateTime.getDate(),"H+":dateTime.getHours(),"m+":dateTime.getMinutes(),"s+":dateTime.getSeconds(),"q+":Math.floor((dateTime.getMonth()+3)/3),S:dateTime.getMilliseconds()};if(/(y+)/.test(format)){format=format.replace(RegExp.$1,(dateTime.getFullYear()+"").substr(4-RegExp.$1.length))}for(var k in o){if(new RegExp("("+k+")").test(format)){format=format.replace(RegExp.$1,RegExp.$1.length==1?o[k]:("00"+o[k]).substr((""+o[k]).length))}}return format}};if(!Cookie){var Cookie={readCookie:function(name){var nameEQ=name+"=";var ca=document.cookie.split(";");for(var i=0;i<ca.length;i++){var c=ca[i];while(c.charAt(0)==" "){c=c.substring(1,c.length)}if(c.indexOf(nameEQ)==0){return decodeURIComponent(c.substring(nameEQ.length,c.length))}}return""},eraseCookie:function(name){this.createCookie(name,"",-1)},createCookie:function(name,value,days){var expires="";if(days){var date=new Date();date.setTime(date.getTime()+(days*24*60*60*1000));expires="; expires="+date.toGMTString()}document.cookie=name+"="+encodeURIComponent(value)+expires+"; path=/"}}};
\ No newline at end of file
/*
* Copyright (c) 2009, 2010, 2011, 2012, 2013, B3log Team
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var Page=function(tips){this.currentCommentId="";this.tips=tips};$.extend(Page.prototype,{insertEmotions:function(name){var _it=this;if(name===undefined){name=""}$("#emotions"+name+" span").click(function(){var $comment=$("#comment"+name);var endPosition=_it._getCursorEndPosition($comment[0]);var key="["+this.className+"]",textValue=$comment[0].value;textValue=textValue.substring(0,endPosition)+key+textValue.substring(endPosition,textValue.length);$("#comment"+name).val(textValue);if($.browser.msie){endPosition-=textValue.split("\n").length-1;var oR=$comment[0].createTextRange();oR.collapse(true);oR.moveStart("character",endPosition+6);oR.select()}else{$comment[0].setSelectionRange(endPosition+6,endPosition+6)}})},_getCursorEndPosition:function(textarea){textarea.focus();if(textarea.setSelectionRange){return textarea.selectionEnd}else{if(document.selection){var i=0,oS=document.selection.createRange(),oR=document.body.createTextRange();oR.moveToElementText(textarea);oS.getBookmark();for(i=0;oR.compareEndPoints("StartToStart",oS)<0&&oS.moveStart("character",-1)!==0;i++){if(textarea.value.charAt(i)=="\n"){i++}}return i}}},validateComment:function(state){var commentName=$("#commentName"+state).val().replace(/(^\s*)|(\s*$)/g,""),commenterContent=$("#comment"+state).val().replace(/(^\s*)|(\s*$)/g,"");if(2>commentName.length||commentName.length>20){$("#commentErrorTip"+state).html(this.tips.nameTooLongLabel);$("#commentName"+state).focus()}else{if($("#commentEmail"+state).val().replace(/\s/g,"")===""){$("#commentErrorTip"+state).html(this.tips.mailCannotEmptyLabel);$("#commentEmail"+state).focus()}else{if(!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($("#commentEmail"+state).val())){$("#commentErrorTip"+state).html(this.tips.mailInvalidLabel);$("#commentEmail"+state).focus()}else{if(2>commenterContent.length||commenterContent.length>500){$("#commentErrorTip"+state).html(this.tips.commentContentCannotEmptyLabel);$("#comment"+state).focus()}else{if(!$("#admin").data("login")&&$("#commentValidate"+state).val().replace(/\s/g,"")===""){$("#commentErrorTip"+state).html(this.tips.captchaCannotEmptyLabel);$("#commentValidate"+state).focus()}else{return true}}}}}$("#commentErrorTip"+state).show();return false},replaceCommentsEm:function(selector){var $commentContents=$(selector);for(var i=0;i<$commentContents.length;i++){var str=$commentContents[i].innerHTML;$commentContents[i].innerHTML=Util.replaceEmString(str)}},_initSyntaxHighlighter:function(languages){for(var i=0;i<languages.length;i++){switch(languages[i]){case"groovy":languages[i]="groovy "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushGroovy.js";break;case"java":languages[i]="java "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJava.js";break;case"php":languages[i]="php "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPhp.js";break;case"scala":languages[i]="scala "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushScala.js";break;case"sql":languages[i]="sql "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushSql.js";break;case"applescript":languages[i]="applescript "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushAppleScript.js";break;case"as3":case"actionscript3":languages[i]="actionscript3 as3 "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushAS3.js";break;case"bash":case"shell":languages[i]="bash shell "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushBash.js";break;case"coldfusion":case"cf":languages[i]="coldfusion cf "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushColdFusion.js";break;case"c#":case"c-sharp":case"csharp":languages[i]="c# c-sharp csharp "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCSharp.js";break;case"cpp":case"c":languages[i]="cpp c "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCpp.js";break;case"css":languages[i]="css "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCss.js";break;case"delphi":case"pascal":languages[i]="delphi pascal "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushDelphi.js";break;case"diff":case"patch":case"pas":languages[i]="diff patch pas "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushDiff.js";break;case"erl":case"erlang":languages[i]="erl erlang "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushErlang.js";break;case"js":case"jscript":case"javascript":languages[i]="js jscript javascript "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJScript.js";break;case"jfx":case"javafx":languages[i]="jfx javafx "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJavaFX.js";break;case"perl":case"pl":languages[i]="perl pl "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPerl.js";break;case"plain":case"text":languages[i]="text plain "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPlain.js";break;case"ps":case"powershell":languages[i]="ps powershell "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPowerShell.js";break;case"py":case"python":languages[i]="py python "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPython.js";break;case"rails":case"ror":case"ruby":case"rb":languages[i]="ruby rails ror rb "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushRuby.js";break;case"sass":case"scss":languages[i]="sass scss "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushSass.js";break;case"vb":case"vbnet":languages[i]="vb vbnet "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushVb.js";break;case"xml":case"xhtml":case"xslt":case"html":languages[i]="xml xhtml xslt html "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushXml.js";break;default:break}}SyntaxHighlighter.autoloader.apply(null,languages);SyntaxHighlighter.config.stripBrs=true;SyntaxHighlighter.all()},_loadSyntaxHighlighter:function(SHTheme){var cssName=SHTheme?SHTheme:"shCoreEclipse",that=this;if(document.createStyleSheet){document.createStyleSheet(latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/styles/"+cssName+".css")}else{$("head").append($("<link rel='stylesheet' href='"+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/styles/"+cssName+".css' type='text/css' charset='utf-8' />"))}$.ajax({url:latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shCore.js",dataType:"script",cache:true,success:function(){var languages=[],isScrip=false;$(".article-body pre").each(function(){var name=this.className.split(";")[0];var language=name.substr(7,name.length-1);if(this.className.indexOf("html-script: true")>-1&&(language!=="xml"&&language!=="xhtml"&&language!=="xslt"&&language!="html")){isScrip=true}languages.push(language)});if(isScrip){$.ajax({url:latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushXml.js",dataType:"script",cache:true,success:function(){that._initSyntaxHighlighter(languages)}})}else{that._initSyntaxHighlighter(languages)}}})},parseLanguage:function(obj){var isPrettify=false,isSH=false;$(".article-body pre").each(function(){if(this.className.indexOf("brush")>-1){isSH=true}if(this.className.indexOf("prettyprint")>-1){isPrettify=true}});if(isSH){this._loadSyntaxHighlighter(obj?(obj.SHTheme?obj.SHTheme:undefined):undefined)}if(isPrettify){if(document.createStyleSheet){document.createStyleSheet(latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.css")}else{$("head").append($("<link rel='stylesheet' href='"+latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.css'>"))}$.ajax({url:latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.js",dataType:"script",cache:true,success:function(){prettyPrint()}})}},load:function(obj){var that=this;if($("#admin").data("login")){$("#commentValidate").parent().parent().hide()}that.insertEmotions();that.parseLanguage(obj?(obj.language?obj.language:undefined):undefined);$("#commentValidate").keypress(function(event){if(event.keyCode===13){that.submitComment()}});$("#comment").keypress(function(event){if(event.keyCode===13&&event.ctrlKey){that.submitComment()}});$("#captcha").click(function(){$(this).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())});var $top=$("#top #admin");if($top.length===1){if($top.find("a").length>2){Cookie.createCookie("commentName",$top.find("span").text(),365);Cookie.createCookie("commentURL",window.location.host,365)}}$("#commentEmail").val(Cookie.readCookie("commentEmail"));$("#commentURL").val(Cookie.readCookie("commentURL"));$("#commentName").val(Cookie.readCookie("commentName"));try{JSON}catch(e){document.write('<script src="'+latkeConfig.staticServePath+'/js/lib/json2.js"><\/script>')}},loadRandomArticles:function(headTitle){var randomArticles1Label=this.tips.randomArticles1Label;$.ajax({url:latkeConfig.servePath+"/get-random-articles.do",type:"POST",success:function(result,textStatus){var randomArticles=result.randomArticles;if(!randomArticles||0===randomArticles.length){$("#randomArticles").remove();return}var listHtml="";for(var i=0;i<randomArticles.length;i++){var article=randomArticles[i];var title=article.articleTitle;var randomArticleLiHtml="<li><a rel='nofollow' title='"+title+"' href='"+latkeConfig.servePath+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=randomArticleLiHtml}var titleHTML=headTitle?headTitle:"<h4>"+randomArticles1Label+"</h4>";var randomArticleListHtml=titleHTML+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#randomArticles").append(randomArticleListHtml)}})},loadRelevantArticles:function(id,headTitle){$.ajax({url:latkeConfig.servePath+"/article/id/"+id+"/relevant/articles",type:"GET",success:function(data,textStatus){var articles=data.relevantArticles;if(!articles||0===articles.length){$("#relevantArticles").remove();return}var listHtml="";for(var i=0;i<articles.length;i++){var article=articles[i];var title=article.articleTitle;var articleLiHtml="<li><a rel='nofollow' title='"+title+"' href='"+latkeConfig.servePath+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=articleLiHtml}var relevantArticleListHtml=headTitle+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#relevantArticles").append(relevantArticleListHtml)},error:function(){$("#relevantArticles").remove()}})},loadExternalRelevantArticles:function(tags,headTitle){var tips=this.tips;try{$.ajax({url:"http://rhythm.b3log.org:80/get-articles-by-tags.do?tags="+tags+"&blogHost="+tips.blogHost+"&paginationPageSize="+tips.externalRelevantArticlesDisplayCount,type:"GET",cache:true,dataType:"jsonp",error:function(){$("#externalRelevantArticles").remove()},success:function(data,textStatus){var articles=data.articles;if(!articles||0===articles.length){$("#externalRelevantArticles").remove();return}var listHtml="";for(var i=0;i<articles.length;i++){var article=articles[i];var title=article.articleTitle;var articleLiHtml="<li><a rel='nofollow' title='"+title+"' target='_blank' href='"+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=articleLiHtml}var titleHTML=headTitle?headTitle:"<h4>"+tips.externalRelevantArticles1Label+"</h4>";var randomArticleListHtml=titleHTML+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#externalRelevantArticles").append(randomArticleListHtml)}})}catch(e){}},submitComment:function(commentId,state){if(!state){state=""}var that=this,tips=this.tips,type="article";if(tips.externalRelevantArticlesDisplayCount===undefined){type="page"}if(this.validateComment(state)){$("#submitCommentButton"+state).attr("disabled","disabled");$("#commentErrorTip"+state).show().html(this.tips.loadingLabel);var requestJSONObject={oId:tips.oId,commentContent:$("#comment"+state).val().replace(/(^\s*)|(\s*$)/g,""),commentEmail:$("#commentEmail"+state).val(),commentURL:Util.proessURL($("#commentURL"+state).val().replace(/(^\s*)|(\s*$)/g,"")),commentName:$("#commentName"+state).val().replace(/(^\s*)|(\s*$)/g,""),captcha:$("#commentValidate"+state).val()};if(state==="Reply"){requestJSONObject.commentOriginalCommentId=commentId}$.ajax({type:"POST",url:latkeConfig.servePath+"/add-"+type+"-comment.do",cache:false,contentType:"application/json",data:JSON.stringify(requestJSONObject),success:function(result){if(!result.sc){$("#commentErrorTip"+state).html(result.msg);$("#commentValidate"+state).val("").focus();$("#submitCommentButton"+state).removeAttr("disabled");$("#captcha"+state).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random());return}result.replyNameHTML="";if($("#commentURL"+state).val().replace(/\s/g,"")===""){result.replyNameHTML="<a>"+$("#commentName"+state).val()+"</a>"}else{result.replyNameHTML='<a href="'+Util.proessURL($("#commentURL"+state).val())+'" target="_blank">'+$("#commentName"+state).val()+"</a>"}that.addCommentAjax(addComment(result,state),state);$("#submitCommentButton"+state).removeAttr("disabled");$("#captcha"+state).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())}});Cookie.createCookie("commentName",requestJSONObject.commentName,365);Cookie.createCookie("commentEmail",requestJSONObject.commentEmail,365);Cookie.createCookie("commentURL",$("#commentURL"+state).val().replace(/(^\s*)|(\s*$)/g,""),365)}},addReplyForm:function(id,commentFormHTML,endHTML){var that=this;if(id===this.currentCommentId){if(Cookie.readCookie("commentName")===""){$("#commentNameReply").focus()}else{$("#commentReply").focus()}return}else{$("#replyForm").remove();endHTML=endHTML?endHTML:"";if(endHTML==="</div>"){$("#"+id).append(commentFormHTML+$("#commentForm").html()+endHTML)}else{$("#"+id).append(commentFormHTML+$("#commentForm").html()+"</table>"+endHTML)}$("#replyForm input, #replyForm textarea").each(function(){this.id=this.id+"Reply"});$("#commentNameReply").val(Cookie.readCookie("commentName"));$("#commentEmailReply").val(Cookie.readCookie("commentEmail"));var $label=$("#replyForm #commentURLLabel");if($label.length===1){$label.attr("id","commentURLLabelReply")}$("#commentURLReply").val(Cookie.readCookie("commentURL"));$("#replyForm #emotions").attr("id","emotionsReply");this.insertEmotions("Reply");$("#commentReply").unbind().keypress(function(event){if(event.keyCode===13&&event.ctrlKey){that.submitComment(id,"Reply");event.preventDefault()}});$("#commentValidateReply").unbind().keypress(function(event){if(event.keyCode===13){that.submitComment(id,"Reply");event.preventDefault()}});$("#replyForm #captcha").attr("id","captchaReply").attr("src",latkeConfig.servePath+"/captcha.do?"+new Date().getTime()).click(function(){$(this).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())});$("#replyForm #commentErrorTip").attr("id","commentErrorTipReply").html("").hide();$("#replyForm #submitCommentButton").attr("id","submitCommentButtonReply");$("#replyForm #submitCommentButtonReply").unbind("click").removeAttr("onclick").click(function(){that.submitComment(id,"Reply")});if(Cookie.readCookie("commentName")===""){$("#commentNameReply").focus()}else{$("#commentReply").focus()}}this.currentCommentId=id},hideComment:function(id){$("#commentRef"+id).hide()},showComment:function(it,id,top,parentTag){var positionTop=parseInt($(it).position().top);if(parentTag){positionTop=parseInt($(it).parents(parentTag).position().top)}if($("#commentRef"+id).length>0){$("#commentRef"+id).show().css("top",(positionTop+top)+"px")}else{var $refComment=$("#"+id).clone();$refComment.addClass("comment-body-ref").attr("id","commentRef"+id);$refComment.find("#replyForm").remove();$("#comments").append($refComment);$("#commentRef"+id).css("top",(positionTop+top)+"px")}},addCommentAjax:function(commentHTML,state){if($("#comments").children().length>0){$($("#comments").children()[0]).before(commentHTML)}else{$("#comments").html(commentHTML)}if(state===""){$("#commentErrorTip").html("").hide();$("#comment").val("");$("#commentValidate").val("");$("#captcha").attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())}else{$("#replyForm").remove()}window.location.hash="#comments"}}); var Page=function(tips){this.currentCommentId="";this.tips=tips};$.extend(Page.prototype,{insertEmotions:function(name){var _it=this;if(name===undefined){name=""}$("#emotions"+name+" span").click(function(){var $comment=$("#comment"+name);var endPosition=_it._getCursorEndPosition($comment[0]);var key="["+this.className+"]",textValue=$comment[0].value;textValue=textValue.substring(0,endPosition)+key+textValue.substring(endPosition,textValue.length);$("#comment"+name).val(textValue);if($.browser.msie){endPosition-=textValue.split("\n").length-1;var oR=$comment[0].createTextRange();oR.collapse(true);oR.moveStart("character",endPosition+6);oR.select()}else{$comment[0].setSelectionRange(endPosition+6,endPosition+6)}})},_getCursorEndPosition:function(textarea){textarea.focus();if(textarea.setSelectionRange){return textarea.selectionEnd}else{if(document.selection){var i=0,oS=document.selection.createRange(),oR=document.body.createTextRange();oR.moveToElementText(textarea);oS.getBookmark();for(i=0;oR.compareEndPoints("StartToStart",oS)<0&&oS.moveStart("character",-1)!==0;i++){if(textarea.value.charAt(i)=="\n"){i++}}return i}}},validateComment:function(state){var commentName=$("#commentName"+state).val().replace(/(^\s*)|(\s*$)/g,""),commenterContent=$("#comment"+state).val().replace(/(^\s*)|(\s*$)/g,"");if(2>commentName.length||commentName.length>20){$("#commentErrorTip"+state).html(this.tips.nameTooLongLabel);$("#commentName"+state).focus()}else{if($("#commentEmail"+state).val().replace(/\s/g,"")===""){$("#commentErrorTip"+state).html(this.tips.mailCannotEmptyLabel);$("#commentEmail"+state).focus()}else{if(!/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($("#commentEmail"+state).val())){$("#commentErrorTip"+state).html(this.tips.mailInvalidLabel);$("#commentEmail"+state).focus()}else{if(2>commenterContent.length||commenterContent.length>500){$("#commentErrorTip"+state).html(this.tips.commentContentCannotEmptyLabel);$("#comment"+state).focus()}else{if(!$("#admin").data("login")&&$("#commentValidate"+state).val().replace(/\s/g,"")===""){$("#commentErrorTip"+state).html(this.tips.captchaCannotEmptyLabel);$("#commentValidate"+state).focus()}else{return true}}}}}$("#commentErrorTip"+state).show();return false},replaceCommentsEm:function(selector){var $commentContents=$(selector);for(var i=0;i<$commentContents.length;i++){var str=$commentContents[i].innerHTML;$commentContents[i].innerHTML=Util.replaceEmString(str)}},_initSyntaxHighlighter:function(languages){for(var i=0;i<languages.length;i++){switch(languages[i]){case"groovy":languages[i]="groovy "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushGroovy.js";break;case"java":languages[i]="java "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJava.js";break;case"php":languages[i]="php "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPhp.js";break;case"scala":languages[i]="scala "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushScala.js";break;case"sql":languages[i]="sql "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushSql.js";break;case"applescript":languages[i]="applescript "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushAppleScript.js";break;case"as3":case"actionscript3":languages[i]="actionscript3 as3 "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushAS3.js";break;case"bash":case"shell":languages[i]="bash shell "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushBash.js";break;case"coldfusion":case"cf":languages[i]="coldfusion cf "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushColdFusion.js";break;case"c#":case"c-sharp":case"csharp":languages[i]="c# c-sharp csharp "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCSharp.js";break;case"cpp":case"c":languages[i]="cpp c "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCpp.js";break;case"css":languages[i]="css "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushCss.js";break;case"delphi":case"pascal":languages[i]="delphi pascal "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushDelphi.js";break;case"diff":case"patch":case"pas":languages[i]="diff patch pas "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushDiff.js";break;case"erl":case"erlang":languages[i]="erl erlang "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushErlang.js";break;case"js":case"jscript":case"javascript":languages[i]="js jscript javascript "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJScript.js";break;case"jfx":case"javafx":languages[i]="jfx javafx "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushJavaFX.js";break;case"perl":case"pl":languages[i]="perl pl "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPerl.js";break;case"plain":case"text":languages[i]="text plain "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPlain.js";break;case"ps":case"powershell":languages[i]="ps powershell "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPowerShell.js";break;case"py":case"python":languages[i]="py python "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushPython.js";break;case"rails":case"ror":case"ruby":case"rb":languages[i]="ruby rails ror rb "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushRuby.js";break;case"sass":case"scss":languages[i]="sass scss "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushSass.js";break;case"vb":case"vbnet":languages[i]="vb vbnet "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushVb.js";break;case"xml":case"xhtml":case"xslt":case"html":languages[i]="xml xhtml xslt html "+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushXml.js";break;default:break}}SyntaxHighlighter.autoloader.apply(null,languages);SyntaxHighlighter.config.stripBrs=true;SyntaxHighlighter.all()},_loadSyntaxHighlighter:function(SHTheme){var cssName=SHTheme?SHTheme:"shCoreEclipse",that=this;if(document.createStyleSheet){document.createStyleSheet(latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/styles/"+cssName+".css")}else{$("head").append($("<link rel='stylesheet' href='"+latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/styles/"+cssName+".css' type='text/css' charset='utf-8' />"))}$.ajax({url:latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shCore.js",dataType:"script",cache:true,success:function(){var languages=[],isScrip=false;$(".article-body pre").each(function(){var name=this.className.split(";")[0];var language=name.substr(7,name.length-1);if(this.className.indexOf("html-script: true")>-1&&(language!=="xml"&&language!=="xhtml"&&language!=="xslt"&&language!="html")){isScrip=true}languages.push(language)});if(isScrip){$.ajax({url:latkeConfig.staticServePath+"/js/lib/SyntaxHighlighter/scripts/shBrushXml.js",dataType:"script",cache:true,success:function(){that._initSyntaxHighlighter(languages)}})}else{that._initSyntaxHighlighter(languages)}}})},parseLanguage:function(obj){var isPrettify=false,isSH=false;$(".article-body pre").each(function(){if(this.className.indexOf("brush")>-1){isSH=true}if(this.className.indexOf("prettyprint")>-1){isPrettify=true}});if(isSH){this._loadSyntaxHighlighter(obj?(obj.SHTheme?obj.SHTheme:undefined):undefined)}if(isPrettify){if(document.createStyleSheet){document.createStyleSheet(latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.css")}else{$("head").append($("<link rel='stylesheet' href='"+latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.css'>"))}$.ajax({url:latkeConfig.staticServePath+"/js/lib/google-code-prettify/prettify.js",dataType:"script",cache:true,success:function(){prettyPrint()}})}},load:function(obj){var that=this;if($("#admin").data("login")){$("#commentValidate").parent().parent().hide()}that.insertEmotions();that.parseLanguage(obj?(obj.language?obj.language:undefined):undefined);$("#commentValidate").keypress(function(event){if(event.keyCode===13){that.submitComment()}});$("#comment").keypress(function(event){if(event.keyCode===13&&event.ctrlKey){that.submitComment()}});$("#captcha").click(function(){$(this).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())});var $top=$("#top #admin");if($top.length===1){if($top.find("a").length>2){Cookie.createCookie("commentName",$top.find("span").text(),365);Cookie.createCookie("commentURL",window.location.host,365)}}$("#commentEmail").val(Cookie.readCookie("commentEmail"));$("#commentURL").val(Cookie.readCookie("commentURL"));$("#commentName").val(Cookie.readCookie("commentName"));try{JSON}catch(e){document.write('<script src="'+latkeConfig.staticServePath+'/js/lib/json2.js"><\/script>')}},loadRandomArticles:function(headTitle){var randomArticles1Label=this.tips.randomArticles1Label;$.ajax({url:latkeConfig.servePath+"/get-random-articles.do",type:"POST",success:function(result,textStatus){var randomArticles=result.randomArticles;if(!randomArticles||0===randomArticles.length){$("#randomArticles").remove();return}var listHtml="";for(var i=0;i<randomArticles.length;i++){var article=randomArticles[i];var title=article.articleTitle;var randomArticleLiHtml="<li><a rel='nofollow' title='"+title+"' href='"+latkeConfig.servePath+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=randomArticleLiHtml}var titleHTML=headTitle?headTitle:"<h4>"+randomArticles1Label+"</h4>";var randomArticleListHtml=titleHTML+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#randomArticles").append(randomArticleListHtml)}})},loadRelevantArticles:function(id,headTitle){$.ajax({url:latkeConfig.servePath+"/article/id/"+id+"/relevant/articles",type:"GET",success:function(data,textStatus){var articles=data.relevantArticles;if(!articles||0===articles.length){$("#relevantArticles").remove();return}var listHtml="";for(var i=0;i<articles.length;i++){var article=articles[i];var title=article.articleTitle;var articleLiHtml="<li><a rel='nofollow' title='"+title+"' href='"+latkeConfig.servePath+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=articleLiHtml}var relevantArticleListHtml=headTitle+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#relevantArticles").append(relevantArticleListHtml)},error:function(){$("#relevantArticles").remove()}})},loadExternalRelevantArticles:function(tags,headTitle){var tips=this.tips;try{$.ajax({url:"http://rhythm.b3log.org:80/get-articles-by-tags.do?tags="+tags+"&blogHost="+tips.blogHost+"&paginationPageSize="+tips.externalRelevantArticlesDisplayCount,type:"GET",cache:true,dataType:"jsonp",error:function(){$("#externalRelevantArticles").remove()},success:function(data,textStatus){var articles=data.articles;if(!articles||0===articles.length){$("#externalRelevantArticles").remove();return}var listHtml="";for(var i=0;i<articles.length;i++){var article=articles[i];var title=article.articleTitle;var articleLiHtml="<li><a rel='nofollow' title='"+title+"' target='_blank' href='"+article.articlePermalink+"'>"+title+"</a></li>";listHtml+=articleLiHtml}var titleHTML=headTitle?headTitle:"<h4>"+tips.externalRelevantArticles1Label+"</h4>";var randomArticleListHtml=titleHTML+"<ul class='marginLeft12'>"+listHtml+"</ul>";$("#externalRelevantArticles").append(randomArticleListHtml)}})}catch(e){}},submitComment:function(commentId,state){if(!state){state=""}var that=this,tips=this.tips,type="article";if(tips.externalRelevantArticlesDisplayCount===undefined){type="page"}if(this.validateComment(state)){$("#submitCommentButton"+state).attr("disabled","disabled");$("#commentErrorTip"+state).show().html(this.tips.loadingLabel);var requestJSONObject={oId:tips.oId,commentContent:$("#comment"+state).val().replace(/(^\s*)|(\s*$)/g,""),commentEmail:$("#commentEmail"+state).val(),commentURL:Util.proessURL($("#commentURL"+state).val().replace(/(^\s*)|(\s*$)/g,"")),commentName:$("#commentName"+state).val().replace(/(^\s*)|(\s*$)/g,""),captcha:$("#commentValidate"+state).val()};if(state==="Reply"){requestJSONObject.commentOriginalCommentId=commentId}$.ajax({type:"POST",url:latkeConfig.servePath+"/add-"+type+"-comment.do",cache:false,contentType:"application/json",data:JSON.stringify(requestJSONObject),success:function(result){if(!result.sc){$("#commentErrorTip"+state).html(result.msg);$("#commentValidate"+state).val("").focus();$("#submitCommentButton"+state).removeAttr("disabled");$("#captcha"+state).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random());return}result.replyNameHTML="";if($("#commentURL"+state).val().replace(/\s/g,"")===""){result.replyNameHTML="<a>"+$("#commentName"+state).val()+"</a>"}else{result.replyNameHTML='<a href="'+Util.proessURL($("#commentURL"+state).val())+'" target="_blank">'+$("#commentName"+state).val()+"</a>"}that.addCommentAjax(addComment(result,state),state);$("#submitCommentButton"+state).removeAttr("disabled");$("#captcha"+state).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())}});Cookie.createCookie("commentName",requestJSONObject.commentName,365);Cookie.createCookie("commentEmail",requestJSONObject.commentEmail,365);Cookie.createCookie("commentURL",$("#commentURL"+state).val().replace(/(^\s*)|(\s*$)/g,""),365)}},addReplyForm:function(id,commentFormHTML,endHTML){var that=this;if(id===this.currentCommentId){if(Cookie.readCookie("commentName")===""){$("#commentNameReply").focus()}else{$("#commentReply").focus()}return}else{$("#replyForm").remove();endHTML=endHTML?endHTML:"";if(endHTML==="</div>"){$("#"+id).append(commentFormHTML+$("#commentForm").html()+endHTML)}else{$("#"+id).append(commentFormHTML+$("#commentForm").html()+"</table>"+endHTML)}$("#replyForm input, #replyForm textarea").each(function(){this.id=this.id+"Reply"});$("#commentNameReply").val(Cookie.readCookie("commentName"));$("#commentEmailReply").val(Cookie.readCookie("commentEmail"));var $label=$("#replyForm #commentURLLabel");if($label.length===1){$label.attr("id","commentURLLabelReply")}$("#commentURLReply").val(Cookie.readCookie("commentURL"));$("#replyForm #emotions").attr("id","emotionsReply");this.insertEmotions("Reply");$("#commentReply").unbind().keypress(function(event){if(event.keyCode===13&&event.ctrlKey){that.submitComment(id,"Reply");event.preventDefault()}});$("#commentValidateReply").unbind().keypress(function(event){if(event.keyCode===13){that.submitComment(id,"Reply");event.preventDefault()}});$("#replyForm #captcha").attr("id","captchaReply").attr("src",latkeConfig.servePath+"/captcha.do?"+new Date().getTime()).click(function(){$(this).attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())});$("#replyForm #commentErrorTip").attr("id","commentErrorTipReply").html("").hide();$("#replyForm #submitCommentButton").attr("id","submitCommentButtonReply");$("#replyForm #submitCommentButtonReply").unbind("click").removeAttr("onclick").click(function(){that.submitComment(id,"Reply")});if(Cookie.readCookie("commentName")===""){$("#commentNameReply").focus()}else{$("#commentReply").focus()}}this.currentCommentId=id},hideComment:function(id){$("#commentRef"+id).hide()},showComment:function(it,id,top,parentTag){var positionTop=parseInt($(it).position().top);if(parentTag){positionTop=parseInt($(it).parents(parentTag).position().top)}if($("#commentRef"+id).length>0){$("#commentRef"+id).show().css("top",(positionTop+top)+"px")}else{var $refComment=$("#"+id).clone();$refComment.addClass("comment-body-ref").attr("id","commentRef"+id);$refComment.find("#replyForm").remove();$("#comments").append($refComment);$("#commentRef"+id).css("top",(positionTop+top)+"px")}},addCommentAjax:function(commentHTML,state){if($("#comments").children().length>0){$($("#comments").children()[0]).before(commentHTML)}else{$("#comments").html(commentHTML)}if(state===""){$("#commentErrorTip").html("").hide();$("#comment").val("");$("#commentValidate").val("");$("#captcha").attr("src",latkeConfig.servePath+"/captcha.do?code="+Math.random())}else{$("#replyForm").remove()}window.location.hash="#comments"}});
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment