﻿var popupBackgroundSelector = ".backgroundPopup";
var popupContentSelector = ".popupContent";
var ESC_CODE_KEY = 27;
var ENTER_CODE_KEY = 13;
var closePopupButtonSelector = ".closeemo";
var focusedInputSelector = null;
var formAnt;
//var validAnt;
var webMethodsAddress = "WebMethods.aspx/";
var emoEnum = { "lol": 1, "nice": 2, "fury": 3, "blue": 4 };
var numArticlesAdded = 0;
var maxNumArticlesAdded = 5;
//reCaptcha
var recaptchaElementId = "captcha";
var recaptchaPublicKey = "6Lce8QgAAAAAABI1T9bsMT01tLsOS6k-TaltqjNs";
var recaptchaTheme = "clean";
var imgAddress = "i/";
var articleIconsAddress = "i/articleicons/";
var categoryIconsAddress = "i/categoryicons/";

//		Валидаторы

var formValidators = [];
formValidators["addArticle"] =
[
{
	field: ".articleForm .linkControl",
	validators:
	[
	{
		type: "length",
		min: 4,
		max: 255
	},
	{
		type: "url",
		message: "Пожалуйста, проверьте написание адреса.",
		regex: new RegExp("^((([hH][tT][tT][pP][sS]?|[fF][tT][pP])\\:\\/\\/)?([\\w\\.\\-]+(\\:[\\w\\.\\&%\\$\\-]+)*@)?((([^\\s\\(\\)\\<\\>\\\\\\\"\\.\\[\\]\\,@;:]+)(\\.[^\\s\\(\\)\\<\\>\\\\\\\"\\.\\[\\]\\,@;:]+)*(\\.[a-zA-Z]{2,4}))|((([01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}([01]?\\d{1,2}|2[0-4]\\d|25[0-5])))(\\b\\:(6553[0-5]|655[0-2]\\d|65[0-4]\\d{2}|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)\\b)?((\\/[^\\/][\\w\\.\\,\\?\\'\\\\\\/\\+&%\\$#\\=~_\\@-]*)*[^\\.\\,\\?\\\"\\'\\(\\)\\[\\]!;<>{}\\s\\x7F-\\xFF])?)$") //источник - http://regexlib.com/REDetails.aspx?regexp_id=1121
	}
	]
},
{
	field: ".articleForm .previewControl",
	validators:
	[
	{
		type: "length",
		min: 5,
		max: 255
	}
	]
}
];

$(document).ready(function() {
	formAnt = new FormAnt({ validate: formValidators });

	var locationHash = location.hash.replace(/^#/, "");
	var query = ParseHash(locationHash);
	if (query["link"] && query["aid"]) {
		ShowArticle(query["aid"], query["link"]);
	}

	Recaptcha.create(recaptchaPublicKey, recaptchaElementId, {
		theme: recaptchaTheme,
		tabindex: 0,
		lang: "ru"
	});

	$(document).keypress(function(e) {
		if (e.keyCode == ENTER_CODE_KEY) {
			if (focusedInputSelector != null) {
				$(focusedInputSelector).trigger("enterPressed");
			}
		}
	});

	$(".link").live("click", function() {
		ShowArticle(GetIdFromClass($(this), "id_"), $(this).attr("href"));
		return false;
	});

	$(".addarticle").click(function() {
		EditArticle();
		//return false;
	});

	$(".addlink").click(function() {
		$(".emoIdControl").val(GetEmoIdOfArticle($(this).parent()));
		AddArticle();
		return false;
	});

	$(".articleIcon").click(function() {
		$(".iconIdControl").val(GetIdFromClass($(this), "id_"));
		$(".selectedIcon").removeClass("selectedIcon").addClass("articleIcon");
		$(this).removeClass("articleIcon").addClass("selectedIcon");
	});

	$(".showsubs").click(function() {
		ShowCategoryArticles($(this));
		return false;
	});

	$(".randomemo").click(function() {
		GetRandomArticle($(this));
	});


});

function GetLink(link, width, height) {
	return "innerIFrame.htm" +
		   "#link=" + link +
		   "&width=" + (width - 8) +
		   "&height=" + (height - 23);
}

function OpenPopup(selector) {
	centerPopup(popupBackgroundSelector, selector);
	loadPopup(popupBackgroundSelector, selector);

	//нажата кнопка закрытия
	$(closePopupButtonSelector).click(function() {
		if ($(this).attr("alt") != "close") {
			VoteForArticle($(this));
		}
		ClosePopup(selector);
		$(closePopupButtonSelector).unbind();
	});

	//клик на фоне
	$(popupBackgroundSelector).click(function() {
		ClosePopup(selector);
		$(popupBackgroundSelector).unbind();
	});

	//нажат ESC
	$(document).keypress(function(e) {
		if (e.keyCode == ESC_CODE_KEY) {
			if (popupStatus == 1) {
				ClosePopup(selector);
			}
		}
	});
}

function ClosePopup(selector) {
	location.hash = "";
	disablePopup(popupBackgroundSelector, selector);
}

function ShowArticle(articleId, link) {
	var popupWindowSelector = ".showArticleWindow";

	var clearedLink = ClearHashLink(link);

	location.hash = "aid=" + articleId + "&" + "link=" + clearedLink;

	OpenPopup(popupWindowSelector);

	var jPopupContent = $(popupWindowSelector + " " + popupContentSelector);
	jPopupContent.empty().append(
		$("<iframe/>").attr({
			src: GetLink(clearedLink, jPopupContent.width(), jPopupContent.height()),
			frameborder: "0",
			width: "100%",
			height: "100%"
		})
	);
}

function EditArticle() {
	if (numArticlesAdded > maxNumArticlesAdded) {
		$(".captchaTR").show();
	}
	OpenPopup(".addArticleWindow");
}

function AddArticle() {
	if (!formAnt.Validate("addArticle")) return false;

	var article = formAnt.GetObject("article");

	if (numArticlesAdded <= maxNumArticlesAdded) {
		article.challenge = "";
		article.response = "";
	}
	else {
		article.challenge = Recaptcha.get_challenge();
		article.response = Recaptcha.get_response();
	}

	sendJson(webMethodsAddress + "AddArticle", article, OnAddArticleSuccess, OnAddArticleFailure, true, { debugMode: false });

	ClosePopup(".addArticleWindow");
}
function OnAddArticleSuccess(d, o) {
	numArticlesAdded++;
}
function OnAddArticleFailure(d, e, o) {
}

function GetEmoIdOfArticle(jEl) {
	var classNames = jEl.getClassNames();

	for (var i in classNames) {
		if (classNames[i].indexOf("article") >= 0) {
			return GetFromEnum(classNames[i].replace("article", ""), emoEnum);
		}
	}
}

function VoteForArticle(jEl) {
	var vote = {};
	vote.articleId = ParseHash(location.hash.replace(/^#/, ""))["aid"] || 0;
	vote.emoId = GetEmoIdOfArticle(jEl);

	sendJson(webMethodsAddress + "VoteForArticle", vote, OnVoteForArticleSuccess, OnVoteForArticleFailure, true, { debugMode: false });
}
function OnVoteForArticleSuccess(d, o) {
}
function OnVoteForArticleFailure(d, e, o) {
}

function GetRandomArticle(jEl) {
	var random = {};
	random.emoId = GetEmoIdOfArticle(jEl);

	sendJson(webMethodsAddress + "GetRandomArticle", random, OnGetRandomArticleSuccess, OnGetRandomArticleFailure, true, { debugMode: false });
}
function OnGetRandomArticleSuccess(d, o) {
	var article = d[0];
	ShowArticle(article.id, article.link);
}
function OnGetRandomArticleFailure(d, e, o) {
}

function ShowCategoryArticles(jEl) {
	var category = {};
	category.categoryId = GetIdFromClass(jEl.parent().parent(), "category_");

	//убрать, если была раскрыта
	if (jEl.parent().parent().next().is(".shownCategory")) {
		var jCategory = jEl.parent().parent().next();
		jCategory.remove();

		for (var p in emoEnum) {
			RemoveCategoryArticles(emoEnum[p], category.categoryId);
		}

		jEl.parent().parent().find(".arrow").attr("src", imgAddress + "arrowdown.png");

		return;
	}

	sendJson(webMethodsAddress + "GetCategoryArticles", category, OnGetCategoryArticlesSuccess, OnGetCategoryArticlesFailure, true, { categoryId: category.categoryId, debugMode: false });
}
function OnGetCategoryArticlesSuccess(d, o) {

	var jEl = $(".leftcol .category_" + o.categoryId);
	var jCategory = $("<div>").addClass("shownCategory").css({ "backgroundImage": "url(" + categoryIconsAddress + o.categoryId + ".jpg)" });
	jEl.after(jCategory);
	jEl.find(".arrow").attr("src", imgAddress + "arrowup.png");

	for (var p in emoEnum) {
		RenderCategoryArticles(p, emoEnum[p], o.categoryId, d[emoEnum[p] - 1]);
	}
}
function OnGetCategoryArticlesFailure(d, e, o) {
}

function RenderCategoryArticles(emo, emoIndex, categoryId, articles) {
	var jEl = $("<div>").addClass("allArticles").addClass(emo);

	for (var i = 0; i < articles.length; i++) {
		var article = articles[i];
		
		var jImg = $("<img/>").addClass("articleicon").attr({ width: "25", height: "25", src: articleIconsAddress + article.iconId + ".png" });

		var jA = $("<a>").addClass("link id_" + article.id).attr("href", "#" + article.link).text(article.preview);

		var jSpan = $("<span>").addClass("articlename");
		jSpan.append(jImg);
		jSpan.append(jA);

		var jDiv = $("<div>").addClass(emo + " allarticle category_" + categoryId);
		jDiv.append(jSpan);

		jEl.append(jDiv);
	}

	$(".articlesblock:eq(" + (emoIndex - 1) + ") .category_" + categoryId).after(jEl);
}

function RemoveCategoryArticles(emoIndex, categoryId) {
	var jEl = $(".articlesblock:eq(" + (emoIndex - 1) + ") .category_" + categoryId).next();
	jEl.remove();
}