;(function(window){
if (window.BVotedUser)
	return true;

	window.voteGetID = function() {
		return 'vote' + new Date().getTime();
	}


	var lastWaitElement = null;
	window.VCLinkCloseWait = function(el)
	{
		if (el && !BX.type.isElementNode(el))
			el = null;
		el = el || this;

		if (BX.type.isElementNode(el))
		{
			el.setAttribute("href", el.getAttribute("rel"));
			BX.removeClass(el, 'vc-load');
		}
	}
	window.VCLinkShowWait = function(el)
	{
		if (el && !BX.type.isElementNode(el))
			el = null;
		el = el || this;

		if (BX.type.isElementNode(el))
		{
			BX.defer(function(){el.setAttribute("rel", el.getAttribute("href")), el.setAttribute("href", "javascript:void(0);");})();
			BX.addClass(el, 'vc-load');
		}
	}

	top.SetVoteAjaxPostTmp = function (text)
	{
		top.voteAjaxPostTmp = text;
	}

	top.SetVoteAjaxFormTmp = function (node)
	{
		top.voteAjaxFormTmp = node;
	}

	top.VoteAjaxResponse = function(response, postform)
	{
		if (top.voteAjaxFormTmp == null)
			return;
		var
			result = top.voteAjaxPostTmp,
			postform = top.voteAjaxFormTmp;
		top.voteAjaxFormTmp = null;

		if (typeof result == 'undefined') {
			BX.reload();
			return;
		}
		var ob = BX.processHTML(result, false);
		var res = postform.parentNode;
		MPFbuttonCloseWait();
		res.innerHTML = ob.HTML;
		if (ob.HTML.indexOf("vote-note-error") < 0)
			BX.removeClass(res, "vote-container-form");
		BX.ajax.processScripts(ob.SCRIPT);
		return false;
	}

	window.voteSendForm = function(form){
		top.SetVoteAjaxFormTmp(form);
		form.appendChild(BX.create("input", {props : {type : "hidden", name : 'AJAX_POST', value : "Y"}}));
		setTimeout(function() {BX.ajax.submit(form, function(response) {});}, 50);
	};

	window.voteGetForm = function (link, VOTE_ID) {
		var href = link.getAttribute('href');

		BX.adjust(link, {"attrs" : {"href" : "javascript:void(0);"}});

		VCLinkShowWait(link);

		BX.ajax({
			url: href.replace(/.AJAX_RESULT=Y/g,'').
				replace(/.AJAX_POST=Y/g,'').
				replace(/.sessid=[^&]*/g, '').
				replace(/.VOTE_ID=([\d]+)/,''),
			method: 'POST',
			data: {
				'VOTE_ID' : VOTE_ID,
				'AJAX_POST' : 'Y',
				'sessid': BX.bitrix_sessid()
			},
			onsuccess: function(data){
				BX.addClass(link.parentNode, "vote-container-form");
				VCLinkCloseWait(link);
				BX.adjust(link.parentNode, {"html" : data});
				window['BVote' + VOTE_ID] = null;
			},
			onfailure: function(data){}
		});
		return false;
	}

	window.voteGetResult = function (controller, uid, link) {
		var res = BX.findParent(controller, {"className" : "vote-container"});
		VCLinkShowWait(link);
		var answer = BX.findChildren(controller, {"tagName" : "SPAN", "className" : "answer-sidebar"}, true);
		for (var ii in answer)
		{
			BX.adjust(answer[ii], {"style" : {"opacity" : "1"}});
		}

		BX.addCustomEvent(
			controller,
			'OnBeforeChangeData',
			function(){
				VCLinkCloseWait(link);
			}
		);


		BX.addCustomEvent(
			controller,
			'OnAfterChangeData',
			function(){
				var res = BX.findParent(controller, {"className" : "vote-container"});
				BX.removeClass(res, "vote-container-form");
				BX.hide(link);
			}
		);

		window['BVote' + uid].checker.lastVote = 0;
		window['BVote' + uid].checker.check(true);

		return false;
	}

	window.BVoteChecker = function(params)
	{
		if (!params["url"] || !params["CID"] || !params["controller"])
			return false;

		this.CID = params["CID"];
		this.voteId = params["voteId"];
		this.url = params["url"];
		this.controller = params["controller"];
		this.period = [2, 5, 10, 30];
		this.lastVote = (!!params["startCheck"] ? parseInt(params["startCheck"]/60) : false);
		if (!!this.lastVote)
			this.check();

		return this;
	}

	window.BVoteChecker.prototype.check = function(now) {
		var time = (now === true ? 0 : false);
		if (now !== true) {
			for (var i in this.period) {
				if (this.lastVote <= this.period[i]) {
					time = this.period[i];
					break;
				}
			}
		}

		if (time !== false)
			setTimeout(BX.proxy(function(){this.send()}, this), time * 60 * 1000);
	}

	window.BVoteChecker.prototype.send = function(){
		BX.ajax({
			url: this.url,
			method: 'POST',
			dataType: 'json',
			data: {
				'VOTE_ID' : this.voteId,
				'AJAX_RESULT' : 'Y',
				'view_result' : 'Y',
				'sessid': BX.bitrix_sessid()
			},
			onsuccess: BX.proxy(function(data){this.start(data);}, this),
			onfailure: function(data){}
		});
	}
	window.BVoteChecker.prototype.start = function(data){
		this.lastVote = parseInt(data["LAST_VOTE"]/60);
		this.changeData(data);
		this.check();
	}
	window.BVoteChecker.prototype.changeData = function(data){
		data = data["QUESTIONS"];
		BX.onCustomEvent(this.controller, 'OnBeforeChangeData');
		for (var q in data)
		{
			var question = BX.findChild(this.controller, {"tagName" : "LI", "attr" : {"id" : "question" + q}}, true);
			if (!!question) {
				for (var i in data[q]) {
					var answer = BX.findChild(question, {"tagName" : "LI", "attr" : {"id" : ("answer" + i)}}, true);

					if (!!answer)
					{
						var res = BX.findChild(answer, {"tagName" : "SPAN", "className" : "answer-users"}, true);
						BX.adjust(res.firstChild, {
							"attrs" : {"id" : "", "rel" : data[q][i]["USERS"]},
							"style" : {"opacity" : "1"},
							"html" : data[q][i]["COUNTER"]});

						BX.adjust(BX.findChild(answer, {"tagName" : "SPAN", "className" : "answer-percent"}, true), {
							"style" : {"opacity" : "1"},
							"html" : parseInt(data[q][i]["PERCENT"]) + '%'});

						BX.adjust(BX.findChild(answer, {"tagName" : "SPAN", "className" : "answer-indicator"}, true),
							{"style" : {"display" : "block", "width" : parseInt(data[q][i]["BAR_PERCENT"]) + '%'}});

					}
				}
			}
		}
		BX.onCustomEvent(this.controller, 'OnAfterChangeData');
	}

	window.BVotedUser = function(params)
	{
		this.CID = params["CID"];
		this.url = params["url"];
		this.urlTemplate = params["urlTemplate"];
		this.nameTemplate = params["nameTemplate"];
		this.dateTemplate = params["dateTemplate"];
		this.data = {};
		this.popup = null;
		this.controller = params["controller"];
		this.startCheck = (!!params["startCheck"] ? parseInt(params["startCheck"]) : false);
		this.voteId = params["voteId"];

		var res = BX.findChildren(this.controller, {"tagName" : "SPAN", "className" : "answer-users"}, true);
		for (var ii in res)
		{
			BX.bind(res[ii].firstChild, "click", BX.proxy(function(){this.get()}, this));
		}

		this.checker = new BVoteChecker(params);
	}

	window.BVotedUser.prototype.getID = function() {
		return 'vote' + new Date().getTime();
	}

	window.BVotedUser.prototype.make = function(data)
	{
		var
			node = BX.create("SPAN", {
					props : {className : "bx-ilike-popup"},
					children : [
						BX.create("SPAN", {
							props : {className: "bx-ilike-bottom_scroll"}
						})
					]
				}
			),
			res = BX.create("SPAN", {
				props : {className : "bx-ilike-wrap-block"},
				children : [
					node
				]
			});
		for (var i in data.items)
		{
			node.appendChild(
				BX.create("A", {
					props: {href:data.items[i]['URL'], target: "_blank", className: "bx-ilike-popup-img"},
					text: "",
					children: [
						BX.create("SPAN", {
								props: {className: "bx-ilike-popup-avatar"},
								html : data.items[i]['PHOTO']
							}
						),
						BX.create("SPAN", {
								props: {className: "bx-ilike-popup-name"},
								html : data.items[i]['FULL_NAME']
							}
						)
					]
				})
			);
		}

		var res1 = (this.popup && this.popup.contentContainer ? this.popup.contentContainer : BX('popup-window-content-bx-vote-popup-cont-' + this.CID));
		if (!!res1)
		{
			try{
				res1.removeChild(res1.firstChild);
			} catch(e) {}
			res1.appendChild(res);
		}
//		this.popup.setAngle({position:'bottom'});
		this.adjustWindow();
	}

	window.BVotedUser.prototype.show = function()
	{
		if (this.popup != null)
			this.popup.close();

		this.popup = new BX.PopupWindow('bx-vote-popup-cont-' + this.CID, this.node, {
			lightShadow : true,
			offsetTop: -2,
			offsetLeft: 3,
			autoHide: true,
			closeByEsc: true,
			bindOptions: {position: "top"},
			events : {
				onPopupClose : function() { this.destroy() },
				onPopupDestroy : BX.proxy(function() { this.popup = null; }, this)
			},
			content : BX.create("SPAN", { props: {className: "bx-ilike-wait"}})
		});

		this.popup.show();

		this.popup.setAngle({position:'bottom'});

		this.adjustWindow();
	}

	window.BVotedUser.prototype.adjustWindow = function()
	{
		if (this.popup != null)
		{
			this.popup.bindOptions.forceBindPosition = true;
			this.popup.adjustPosition();
			this.popup.bindOptions.forceBindPosition = false;
		}
	}

	window.BVotedUser.prototype.get = function()
	{
		this.node = BX.proxy_context;
		if (!this.node)
			return false;
		if (!this.node.getAttribute("id"))
			this.node.setAttribute("id", this.getID());
		if (!this.node.getAttribute("rel"))
			return false;

		this.show();

		if (!this.data[this.node.getAttribute("id")]) {
			BX.ajax({
				url: "/bitrix/components/bitrix/voting.current/templates/.userfield/users.php",
				method: 'POST',
				dataType: 'json',
				data: {
					'ID' : this.node.getAttribute("rel"),
					'request_id' : this.node.getAttribute("id"),
					'URL_TEMPLATE' : this.urlTemplate,
					'NAME_TEMPLATE' : this.nameTemplate,
					'DATE_TEMPLATE' : this.dateTemplate,
					'sessid': BX.bitrix_sessid()
				},
				onsuccess: BX.proxy(function(data){this.data[this.node.getAttribute("id")] = data; this.make(data);}, this),
				onfailure: function(data){}
			});
		}
		else
		{
			this.make(this.data[this.node.getAttribute("id")]);
		}
	}
})(window);