﻿if (!window.ContestModule) {
	window.ContestModule = {
		_evalScripts: function(moduleContainerId) {
			var moduleConainer = $(moduleContainerId);
			if (moduleConainer)
				$A(moduleConainer.getElementsByTagName("SCRIPT")).each(function(script) { eval(script.innerHTML); });
		},
		clearMarkupReferences: function(markupReferences) {
			markupReferences.each(function(element) {
				if (element)
					element.removeAttribute("id");
			});
		},
		registerAsyncHandler: function(moduleContainerId) {
			Sys.WebForms.PageRequestManager.getInstance().add_endRequest(
				function() { ContestModule._evalScripts(moduleContainerId); }
			);
		},
		initModule: function(moduleContainerId) {
			var module = $(moduleContainerId);
			if (module) {
				module.parentNode.className = null;
				module.parentNode.parentNode.className = null;
			}
		}
	}
	window.ContestDetail = Class.create();
	ContestDetail.prototype = {
		initialize: function(contestData, name) {
			this.elements = {};
			Object.extend(this, contestData);
			this.name = name;
		},
		_initElementMarkup: function(element) {
			var numbersData = element.numbersData;
			var votingData = element.votingData;
			var creatorData = element.creatorData;
			if (numbersData) {
				ContestVoitingHelper.initVotingStats(this, numbersData.numberOfViewsContainer, numbersData.numberOfViews, this.initElementNumberOfViews);
				ContestVoitingHelper.initVotingStats(this, numbersData.numberOfCommentsContainer, numbersData.numberOfComments, this.initElementNumberOfComments);
				ContestModule.clearMarkupReferences([numbersData.numberOfViewsContainer, numbersData.numberOfCommentsContainer]);
			}
			element.votingMarkup = ContestVoitingHelper.initVotingMarkup(this, votingData);
			if (creatorData) {
				creatorData.link.innerHTML = creatorData.link.href.toLowerCase() == this.selfProfileUrl.toLowerCase() ? this.selfCreatorTitle : creatorData.name;
				ContestModule.clearMarkupReferences([creatorData.link]);
			}
		},
		_initContestSubmissionsElements: function() {
			var elems = this.contestSubmissionsData;
			if (elems) {
				var footerVisible = this._initSortOrderElements(elems);
				footerVisible |= this._initNumbersElementsData(elems);
				elems.container[this.numberOfElements > 0 ? "show" : "hide"]();
				if (elems.voteOnceContainer)
					elems.voteOnceContainer[this.state == "OpenedForVoting" && this.voteType == "GainRating" && this.canUserVote == "Ok" ? "show" : "hide"]();
				if (elems.footerContainer)
					elems.footerContainer[footerVisible ? "show" : "hide"]();
				ContestModule.clearMarkupReferences([elems.container, elems.voteOnceContainer, elems.footerContainer]);
			}
		},
		_initNumbersElementsData: function(elems) {
			var numElems = elems.numberElementsData;
			if (numElems) {
				var visible = !this._isRandom && numElems.pageSize > 0;
				$A(numElems.mainContainers).invoke(visible ? "show" : "hide");
				if (visible) {
					$A(numElems.startIndexContainers).each(function(item) {
						item.innerHTML = numElems.startIndex + 1;
					} .bind(this));
					$A(numElems.endIndexContainers).each(function(item) {
						item.innerHTML = numElems.startIndex + numElems.pageSize;
					} .bind(this));
					var numberOfElements = this.numberOfElements - (this.state == "Closed" && this.numberOfElements > 0 && !!this.winnerElement ? 1 : 0);
					$A(numElems.numberOfElementsContainers).each(function(item) {
						item.innerHTML = numberOfElements;
					} .bind(this));
				}
				ContestModule.clearMarkupReferences([numElems.mainContainers, numElems.startIndexContainers, numElems.endIndexContainers].flatten());
				return visible;
			}
			return false;
		},
		_initSortOrderElements: function(elems) {
			var sortElems = elems.sortElementsData;
			if (sortElems && sortElems.views) {
				var sortOrderView;
				$H(sortElems.views).values().invoke("hide");
				if (this.state == 'Closed' && !this.hideVotingStats)
					sortOrderView = sortElems.views.mostPopularDefault;
				else
					sortOrderView = sortElems.views.randomDefault;
				sortOrderView.show();
				ContestModule.clearMarkupReferences($H(sortElems.views).values());
				if (sortElems.pagerViews && sortElems.moreEntriesViews) {
					var randomLink = sortOrderView.descendants().find(function(element) {
						return element.tagName.toLowerCase() == "a" && element.innerHTML == sortElems.randomTitle;
					} .bind(this));
					this._isRandom = !!randomLink && randomLink.hasClassName("selected");
					sortElems.pagerViews.invoke(this._isRandom ? "hide" : "show");
					sortElems.moreEntriesViews.invoke(this._isRandom && this._pagersExist(sortElems) ? "show" : "hide");
					ContestModule.clearMarkupReferences([sortElems.pagerViews, sortElems.moreEntriesViews].flatten());
					return sortElems.pagerViews[0].visible() || sortElems.moreEntriesViews[0].visible();
				}
			}
			return false;
		},
		_pagersExist: function(sortElems) {
			if (!sortElems.pagerViews) return false;
			return sortElems.pagerViews.find(function(view) {
				return view.descendants().find(function(element) { return element.tagName.toLowerCase() == "a"; });
			});
		},
		_voteComplete: function(ucid, userVote, voteResult) {
			if (typeof voteResult == "string") {
				window.location.href = voteResult;
				return;
			}
			if (voteResult == 0) {
				var element = this.elements[ucid];
				if (this.voteType == "GainRating") {
					this.canUserVote = "UserAlreadyHasVoted";
					$H(this.elements).values().each(function(item) { item.votingData.serverData.canUserVote = "UserAlreadyHasVoted"; });
					if (this.contestSubmissionsData && this.contestSubmissionsData.voteOnceContainer)
						this.contestSubmissionsData.voteOnceContainer.hide();
				}
				if (element.votingData.serverData.userVote == 0) {
					this.numberOfVotes++;
					if (element.numbersData)
						element.numbersData[this.voteType == "Thumb" ? "thumbUpDownVoteCount" : "thumbUp"]++;
				}
				element.votingData.serverData.userVote = userVote;
				this.initMarkup();
			} else if (this.votingMessages) {
				alert(this.votingMessages.voteError);
			}
		},
		_initStateMarkup: function() {
			if (this.stateMarkup) {
				for (var state in this.stateMarkup) {
					var markup = this.stateMarkup[state];
					if (state != this.state) {
						markup[0].addClassName("altTextColor");
						if (markup[2])
							markup[2].addClassName("altTextColor");
					}
					if (markup[1] && this.closeDates[state])
						markup[1].innerHTML = "(" + (state == this.state ? (this.closesText + " ") : "") + this.closeDates[state] + ")";
					ContestModule.clearMarkupReferences(markup);
				}
			}
		},
		initMarkup: function() {
			if (this.state == "OpenedForVoting" && !!roadBlocker && roadBlocker.userIsBlocked() && this.canUserVote != "UserAlreadyHasVoted") {
				this.canUserVote = "Ok";
				$H(this.elements).values().each(function(item) { item.votingData.serverData.canUserVote = "Ok"; });
			}
			this._initStateMarkup();
			if (this.winnerElement)
				this._initElementMarkup(this.winnerElement);
			this._initContestSubmissionsElements();
			$H(this.elements).values().each(function(element) {
				this._initElementMarkup(element);
			} .bind(this));
		},
		_showAgreementCases: function(stateSwitch) {
			var args = $A(arguments);
			args.shift();
			for (var i = 0; i < args.length; i += 2) {
				if (this._showAgreementCase(stateSwitch, args[i] + args[i + 1]) == 0)
					this._showAgreementCase(stateSwitch, args[i] + 'Default');
			}
		},
		_showAgreementCase: function(stateSwitch, cssCase) {
			var result = 0;
			stateSwitch.descendants().each(function(d) {
				if (d.hasClassName(cssCase)) {
					d.show();
					result++;
				}
			});
			return result;
		},
		initAgreementMarkup: function() {
			var info = this.agreementInfo;
			if (!info) return;
			if (info.stateSwitchElement) {
				this._showAgreementCases(info.stateSwitchElement,
					"stateCase", this.state,
					"contestTypeCase", this.type,
					"voteTypeCase", this.voteType);
			}
			if (info.overlayPanelLink && info.agreementRequired)
				info.overlayPanelLink.show();

			ContestModule.clearMarkupReferences([info.stateSwitchElement, info.overlayPanelLink]);
		}
	}
	window.ContestItem = Class.create();
	ContestItem.prototype = {
		initialize: function(contestData) {
			Object.extend(this, contestData);
		},
		_voteComplete: function(ucid, userVote, voteResult) {
			if (typeof voteResult == "string") {
				window.location.href = voteResult;
				return;
			}
			if (voteResult == 0) {
				if (this.voteType == "GainRating")
					this.votingData.serverData.canUserVote = "UserAlreadyHasVoted";
				this.votingData.serverData.userVote = userVote;
				this.initMarkup();
			} else if (this.votingMessages) {
				alert(this.votingMessages.voteError);
			}
		},
		initMarkup: function() {
			if (this.state == "OpenedForVoting" && !!roadBlocker && roadBlocker.userIsBlocked() && this.votingData.serverData.canUserVote != "UserAlreadyHasVoted")
				this.votingData.serverData.canUserVote = "Ok";
			ContestVoitingHelper.initVotingMarkup(this, this.votingData, true);
		}
	}
	window.ContestVotingAction = Class.create();
	ContestVotingAction.prototype = {
		_voteInProgress: false,
		initialize: function(actionUrl, contestUcid, ucid, voteType, callback) {
			if (!ContestVotingAction._inited) {
				ContestVotingAction.registerClass("ContestVotingAction", Sys.Net.WebServiceProxy);
				ContestVotingAction._inited = true;
			}
			ContestVotingAction.initializeBase(this);
			this._timeout = 0;
			this._actionUrl = actionUrl;
			this._contestUcid = contestUcid;
			this._ucid = ucid;
			this._voteType = voteType;
			this.callback = callback;
		},
		vote: function(userVote) {
			if (!this._voteInProgress) {
				this._voteInProgress = true;
				var request = { contestUcid: this._contestUcid, contestElementUcid: this._ucid, userVote: userVote, voteType: this._voteType, redirectPath: window.location.href };
				this._invoke(this._actionUrl, "Vote", false, request, this._voteComplete.bind(this, request), this._voteError.bind(this), null);
			}
		},
		_voteComplete: function(request, response) {
			this._voteInProgress = false;
			if (typeof (this.callback) == "function")
				this.callback(request.contestElementUcid, request.userVote, response);
		},
		_voteError: function(error) {
			this._voteInProgress = false;
			alert(error._message);
		}
	}

	window.ContestVotingBase = Class.create();
	window.ContestVotingBase.prototype = {
		initialize: function() { },
		baseInitialize: function(parent, votingData, controlElements) {
			Object.extend(this, controlElements);
			Object.extend(this, votingData.serverData);
			this._parent = parent;
			this._votingData = votingData;
			this._messages = parent.votingMessages;
			this._voteCallback = parent._voteComplete.bind(parent);
			this._progressElement = votingData.progressElement;
			if (this._progressElement)
				this._progressElement._showProgressTimeout = null;
		},
		_showProgress: function() {
			if (this._progressElement)
				this._progressElement._showProgressTimeout = setTimeout(this._asyncShowProgress.bind(this), 500);
		},
		_asyncShowProgress: function() {
			if (!this._progressElement._showProgressTimeout)
				return;
			this.controlContainer.hide();
			this._progressElement.show();
		},
		_hideProgress: function() {
			if (this._progressElement) {
				if (this._progressElement._showProgressTimeout) {
					clearTimeout(this._progressElement._showProgressTimeout);
					this._progressElement._showProgressTimeout = null;
				}
				this._progressElement.hide();
			}
		}
	};

	window.ContestVotingResults = Class.create();
	window.ContestVotingResults.prototype = Object.extend(new ContestVotingBase(), {
		initialize: function(parent, votingData) {
			this.baseInitialize(parent, votingData, votingData.votingResultsElements);
		},
		initMarkup: function() {
			ContestVoitingHelper.initVotingStats(this._parent, this.totalVotes, this._parent.voteType == "Thumb" ? this.thumbUpDownVoteCount : this.thumbUp, this._parent.initElementNumberOfVotes);
			this.controlContainer[!this._parent.hideVotingStats ? "show" : "hide"]();
			if (this.controlContainer.visible())
				this.votingRatio.innerHTML = (this._parent.voteType == "Thumb" ? this.thumbUpDown :
					(this._parent.numberOfVotes > 0 ? Math.floor((this.thumbUp / this._parent.numberOfVotes) * 100) : 0)) + "%";
			return this;
		}
	});

	window.GainContestVoting = Class.create();
	GainContestVoting.prototype = Object.extend(new ContestVotingBase(), {
		initialize: function(parent, votingData) {
			this.baseInitialize(parent, votingData, votingData.gainControlElements);
			this._checked = false;
		},
		initMarkup: function() {
			this.controlContainer.className = "contestVotingPnl";
			this.controlContainer.show();
			this._hideProgress();
			this._checked = this.userVote > 0;
			this._enableVoting(this.canUserVote == "Ok");
			return this;
		},
		_enableVoting: function(enabled) {
			this[enabled ? "_enable" : "_disable"]();
		},
		_disable: function() {
			this.btnGainVote.onclick = null;
			this.btnGainVote.hide();
			this.controlContainer.removeClassName("contestGainUnchecked");
			this.controlContainer.addClassName(this._checked ? "contestGainCheckedDisabled" : "contestGainDisabled");
			this.chbGainVote.onmouseover = null;
			this.chbGainVote.onmouseout = null;
			this.chbGainVote.onclick = null;
			if (this._checked && this._messages) {
				this.messageContainer.show();
				this.messageContainer.innerHTML = this._messages.voteSubmitted;
			} else
				this.messageContainer.hide();
		},
		_enable: function() {
			function checkOver(isOver) {
				if (!this._checked)
					this.controlContainer[isOver ? "addClassName" : "removeClassName"]("contestGainUncheckedOver");
			}
			this.controlContainer.removeClassName(this._checked ? "contestGainCheckedDisabled" : "contestGainDisabled");
			this.controlContainer.addClassName("contestGainUnchecked");
			this.chbGainVote.onmouseover = checkOver.bind(this, true);
			this.chbGainVote.onmouseout = checkOver.bind(this, false);
			this.chbGainVote.onclick = function() {
				if (this._checked) {
					this._checked = false;
					this.btnGainVote.onclick = null;
					this.btnGainVote.hide();
					this.messageContainer.hide();
					this.controlContainer.removeClassName("contestGainChecked");
					this.controlContainer.addClassName("contestGainUnchecked");
					this._enableNeighbors(true);
				} else {
					this._enableNeighbors(false);
					this._checked = true;
					if (this._messages) {
						this.messageContainer.show();
						this.messageContainer.innerHTML = this._messages.voteOneCarefully;
					}
					this.btnGainVote.show();
					this.btnGainVote.onclick = function() {
						if (this.canUserVote == "Ok" && this._checked) {
							this._showProgress();
							new ContestVotingAction(this._parent.voteUrl, this._parent.ucid, this.ucid, "GainRating", this._voteCallback).vote(1);
						}
					} .bind(this);
					this.controlContainer.removeClassName("contestGainUnchecked");
					this.controlContainer.addClassName("contestGainChecked");
				}
			} .bind(this);
		},
		_enableNeighbors: function(enabled) {
			$H(this._parent.elements).values().each(function(e) {
				var vm = e.votingMarkup;
				if (vm && vm != this && vm._enableVoting)
					vm._enableVoting(enabled);
			} .bind(this));
		}
	});

	window.ThumbContestVoting = Class.create();
	ThumbContestVoting.prototype = Object.extend(new ContestVotingBase(), {
		initialize: function(parent, votingData) {
			this.baseInitialize(parent, votingData, votingData.thumbControlElements);
			this._btnCssStates = [];
		},
		initMarkup: function() {
			this._hideProgress();
			if (this.canUserVote != "Ok") {
				this.controlContainer.hide();
				this._resetBtnEvents(this.btnThumbUp);
				this._resetBtnEvents(this.btnThumbDown);
			} else {
				this.controlContainer.show();
				if (this._messages) {
					if (this.userVote > 0)
						this.messageContainer.innerHTML = this._messages.alreadyThumbUpVoted;
					else if (this.userVote < 0)
						this.messageContainer.innerHTML = this._messages.alreadyThumbDownVoted;
					else
						this.messageContainer.innerHTML = this._messages.defaultThumbUpDown;
				}

				this.controlContainer.className = "contestVotingPnl";
				this._initThumbBtn(this.btnThumbUp, 1, "contestVotingThumbUp");
				this._initThumbBtn(this.btnThumbDown, -1, "contestVotingThumbDown");
			}
			return this;
		},
		_resetBtnEvents: function(thumbBtn) {
			thumbBtn.onclick = thumbBtn.onmouseout = thumbBtn.onmouseover = null;
		},
		_initThumbBtn: function(btn, vote, cssPref) {
			var overCss = cssPref + "Over";
			var voteCss = this.userVote == vote ? (cssPref + "Voted") : "";
			function onover(isOver) {
				//				this.controlContainer[isOver ? "removeClassName" : "addClassName"](voteCss);
				//				this.controlContainer[isOver ? "addClassName" : "removeClassName"](overCss);
				this._changeBtnCssState(isOver ? overCss : voteCss, isOver ? voteCss : overCss);
			}
			function onclick() {
				if( roadBlocker.userIsBlocked() ) {
					roadBlocker.actionIfNeeded();
					return;
				}
				if (this.canUserVote == "Ok") {
					this._showProgress();
					new ContestVotingAction(this._parent.voteUrl, this._parent.ucid, this.ucid, "Thumb", this._voteCallback).vote(vote);
				}
			}
			this.controlContainer.addClassName(voteCss);
			if (this.userVote != vote) {
				var container = this.controlContainer;
				btn.onmouseout = onover.bind(this, false);
				btn.onmouseover = onover.bind(this, true);
				btn.onclick = onclick.bind(this);
			} else
				this._resetBtnEvents(btn);
		},
		//To exclude icons blinking under IE for the normal voting state. Decoment the code above to see this defect.
		_changeBtnCssState: function(addCss, removeCss) {
			function chageCss() {
				this._btnCssStates.each(function(i) { this.controlContainer[i.method](i.css); } .bind(this));
				this._btnCssStates.length = 0;
			}
			var hasCalled = this._btnCssStates.length > 0;
			this._btnCssStates.push({ css: addCss, method: "addClassName" });
			this._btnCssStates.push({ css: removeCss, method: "removeClassName" });
			if (!hasCalled)
				setTimeout(chageCss.bind(this), 0);
		}
	});

	window.ContestVoitingHelper = {
		initVotingMarkup: function(parent, votingData, showMessageForDisabledGain) {
			if (!parent.voteUrl || !votingData)
				return null;

			function createMarkup() {
				switch (parent.state) {
					case "OpenedForVoting":
						var msg = null;
						if (votingData.serverData.canUserVote == "UserIsAuthorOfContent") {
							msg = this._showMsg(parent, votingData,
								parent.type == "Profile" ? "ownProfileSubmission" : "ownContentSubmission");
						}
						else if (showMessageForDisabledGain &&
							parent.voteType == "GainRating" &&
							votingData.serverData.canUserVote == "UserAlreadyHasVoted" &&
							votingData.serverData.userVote == 0) {
							msg = this._showMsg(parent, votingData, "alreadyGainVoted");
						}
						return msg
							? msg
							: (parent.voteType == "Thumb"
								? new ThumbContestVoting(parent, votingData)
								: new GainContestVoting(parent, votingData)).initMarkup();
					case "OpenedForSubmitting":
						return this._showMsg(parent, votingData, "votingHasNotBegun");
					case "Closed":
						if (votingData.votingResultsElements)
							return new ContestVotingResults(parent, votingData).initMarkup();
						else
							return this._showMsg(parent, votingData, parent.isWinner ? "isWinner" : "isOver");
				}
				return null;
			}

			var result = createMarkup.bind(this)();

			ContestModule.clearMarkupReferences([
				$H(votingData.thumbControlElements).values(),
				$H(votingData.gainControlElements).values(),
				votingData.messageElement,
				votingData.progressElement,
				$H(votingData.votingResultsElements).values()].flatten());

			return result;
		},
		initVotingStats: function(parent, statsContainer, stats, initFunc) {
			if (!statsContainer)
				return;
			statsContainer[!parent.hideVotingStats ? "show" : "hide"]();
			if (statsContainer.visible() && typeof (initFunc) == "function")
				initFunc(statsContainer, stats);
		},
		_showMsg: function(parent, votingData, msg) {
			if (votingData.messageElement && parent.votingMessages) {
				votingData.messageElement.show();
				votingData.messageElement.innerHTML = parent.votingMessages[msg];
				return votingData.messageElement;
			}
			return null;
		}
	};
}

// [AtlasScript]

if (typeof (Sys) != "undefined")
	Sys.Application.notifyScriptLoaded();

// [/AtlasScript]
