﻿RemoteVote = function()
{

	var _containers = ["#inp_recaptchaVote_image", "#inp_recaptchaVote"];

	//inp_recaptchaVote_image
	//inp_recaptchaVote

	var _obj;
	var _callback;
	return {
		init : function(obj, callback)
		{
			_obj = obj;
			_callback = callback;
			for(var i = 0; i < _containers.length; i++)
			{
				$(_containers[i]).hide();
			}

			$el("likeSubmit").onclick = function(){
				RemoteVote.vote();
				return false;
			};

			$el("recaptchaVoteRefresh").onclick = function()
			{
				recaptcha("recaptchaVoteImage");
			}

			replaceRecaptchaSubmits($el("inp_recaptchaVote_image"));
		},
		showSecurity : function()
		{
		},
		vote : function()
		{
			var url = "/" + _obj.region + "/" + _obj.section + "/Vote";

			if(!$('#recaptchaVote').is(':visible'))
			{
				for(var i = 0; i < _containers.length; i++)
				{
					$(_containers[i]).show();
				}
				$("#recaptchaVote").attr("value", "");
				recaptcha("recaptchaVoteImage");
				$("#recaptchaVote").focus();
				return;
			}

			var errors = validate("Vote");

			if(errors.length == 0)
			{

				var options = {
					dataType: 'xml',
					beforeSend: function(xhrObj){
						waitMessage($so("TextRemoteWaitMessage"));
					},
					data: { XRequestType: "application/remote-form" },
					success: function(data)
					{
						RemoteVote.submitDone(data);
					},
					complete: function(data)
					{
						killWaitMessage();
					}
				};
				$('#voteForm').ajaxSubmit(options);
			}
			else
			{
				showErrors(errors);
			}

		},
		submitDone : function(data)
		{
			var root;
			var i;
			var c;
			var status = "failure";
			var errors = [];
			var stageError;

			root = data.documentElement;

			status = xmlAttributeValue(root, "status");

			if(status == "success")
			{
				var count = xmlAttributeValue(root, "count");

				if(_callback != null)
				{
					_callback({count:count});
				}

				// destroy the form and show success
				RemoteVote.showSuccess(count);
				return;
			}

			// reload the security image
			recaptcha("recaptchaVoteImage");

			for (i = 0; i < root.childNodes.length; i++)
			{
				c = root.childNodes.item(i);
				if (c.nodeType == 1)
				{
					if(c.nodeName == "error")
					{
						stageError = xmlAttributeValue(c, "id");
						errors[errors.length] = { id: stageError, message: c.firstChild.nodeValue, fromStringtable: false};
					}
				}
			}

			if(errors.length > 0)
			{
				recaptcha("recaptchaVoteImage");
				$("#recaptchaVote").attr("value", "");
				showErrors(errors);
				$("#recaptchaVote").focus();
			}

		},
		showSuccess: function(count)
		{
			for(var i = 0; i < _containers.length; i++)
			{
				$(_containers[i]).hide();
			}
			$("#voteCount").html("<span>" + count + "</span>");
			// IE6 hack fix
			$("#voteCount").show();
		}
	}
}();

