(function($)
{	
	// constructor
	function v1Poll(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			_resultContainer = _root.find('.v1-poll-result-container'),
			_questionElem = _root.find('.v1-poll-question'),
			_answerElem = _root.find('.v1-poll-answers'),
			_requestUrl = "/scrum/poll_vote.php",
			_opts = {
				poll_id: 0,
				debug: false
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
//		$.extend(_self, {
//		});
	
		// Private methods -----------------------------------------------------------------
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					alert(str);
				} 
				catch (e) {
					alert("debug: " + str);
				}
			}
		};
			
		// generic binding function
		
		function bind(name, fn)
		{
			if ($.isFunction(fn) == false)
				return;
				
			$(_self).bind(name, fn);
		};
		
		function showPollAnswers()
		{
			_resultContainer.hide();
			_answerElem.show();
		};
		
		function answerPoll(){
            var response_id = _answerElem.find('input[name=poll]:checked').val();
			if (typeof(response_id) == "undefined") {
				alert("Please select an option.");
			}
			else {
				showPollResults(response_id);
			}
			
			return false;
		};
		
		function showPollResults(response_id){
			var submitData = "poll_id=" + _opts.poll_id;
			
			if (typeof(response_id) != "undefined") {
				submitData += "&response_id="+response_id;
			}
			
            $.ajax({
            	url: _requestUrl,
                cache: false,
                data: submitData,
                error: function(xhr, status, exception) {
            		doRequestError(status, exception);
            	},
                success: function(responseHtml) {
            		var isValidResponse = responseHtml.indexOf("poll-results") != -1;
					if(isValidResponse == true) {
	            		_answerElem.hide();
						_resultContainer.html(responseHtml);
						_resultContainer.fadeIn();
						if (userHasVoted() == true) {
							showThanks();
						} else {
							showAnswersLink();
						}
					} else {
						doRequestError("error", "invalid response");
					}
                }
            });
			
			return false;
		};
		
		function showPollResultsOld(submitAnswer){
			//submitAnswer is false if the user clicks the "view results" link
			
            // make ajax request to vote and retrieve results
            var response_id = _answerElem.find('input[name=poll]:checked').val();
            if (!response_id || submitAnswer == false) response_id = '';
			debug("response_id: " + response_id);


            $.ajax({
            	url: requestUrl,
                cache: false,
                data: "poll_id="+_opts.poll_id+"&response_id="+response_id,
                error: function(xhr, status, exception) {
            		doRequestError(status, exception);
            	},
                success: function(responseHtml) {
            		var isValidResponse = responseHtml.indexOf("poll-results") != -1;
					//alert("isValidResponse: " + isValidResponse);
					if(isValidResponse == true) {
	            		_answerElem.hide();
						_resultContainer.html(responseHtml);
						_resultContainer.fadeIn();
						if (userHasVoted() == true) {
							showThanks();
						} else {
							showAnswersLink();
						}
					} else {
						doRequestError("error", "invalid response");
					}
                }
            });
			
			return false;
		};
		
		function doRequestError(status, exception) {
			var errorHtml = "<div class='v1-poll-error'><p><b>Sorry...</b><br/>We're experiencing technical difficulties. Please try again later.</p></div>";
			errorHtml += '<span style="display:none;">status: ' + status + '; exception: ' + exception + '</span>';
			_questionElem.hide();
			_answerElem.hide();
    		_resultContainer.html(errorHtml);
			_resultContainer.fadeIn();
		};
		
		function showAnswersLink(){
			var linkHtml = '<div class="arrow" style="margin:7px 0 0 10px;"><a href="#" class="pollVoteNowLink">Vote Now</a></div>';
			_resultContainer.append(linkHtml);
			_root.find(".pollVoteNowLink").click(function(){
				showPollAnswers();
				return false;
			});
		};
		
		function showThanks(){
			var thanksHtml= '<p class="thanks" style="margin:7px 0 0 10px;">Thanks for voting!</p>';
			_resultContainer.append(thanksHtml);
		};
		
//		function enableButton(){
//			$(".v1-pollVoteButton", _root).removeClass("buttonInactive");
//			$(".v1-pollVoteButton", _root).click(showPollResults);
//		};
		
		function userHasVoted(){
			var hasVoted = false;
			
            var polls = $.cookie('polls');
            if (polls) {
				var pollsVoted = polls.split('|');
			
                $.each(pollsVoted, function(key, value) {
                    if (value == _opts.poll_id) {
						hasVoted = true;
					}
                });
            }
			return hasVoted;
		};
	
		function init()
		{
			if (_opts.poll_id == -1) _requestUrl = "/assets/js/v1/fake_poll_response.html";
			
            // see if user has already voted	
            if (userHasVoted() == true) {
                showPollResults();
            } else {
                //_answerElem.find("input").click(enableButton);
				
                _root.find(".v1-pollVoteButton").click(answerPoll);
			
                _root.find(".v1-pollShowResultsLink").click(showPollResults);
				
                showPollAnswers();
            }
		};
	
		// Initialization ------------------------------------------------------------------
		init();
	};
	
	// jQuery plugin implementation
	$.fn.v1Poll = function(conf)
	{
		var opts = { };
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new v1Poll($(this), opts);
		});
		
		return this;
	};
})(jQuery);

