



var dPoll = {
	 // Sends messages to console when true

	// Sends messages to console
	"debug" : function(str) {
		// if (window.console && console.log) { console.log(str); }
	},


	// Setup poll, stores in data() for cases of multiple polls per page
	"ini" : function(pollId, pollUri, multiVote, custom) {
		this.debug("--- dPoll:ini");

		// Create settings object from arguments
		var settings = {
			pollCssId : "#"+pollId,
			pollUri   : pollUri,
			multiVote : multiVote,
			pollId    : pollId
		}
		
		// Add in any custom settings
		$.extend(settings, custom);

		// Store settings unique to poll ID (unique per page load)	
		$("body").data(pollId, settings);


		// Check cookie for poll, unique to poll URI so it follows around the site
		var historyCookie = readCookie(pollUri);
		if (historyCookie && !multiVote) {
			this.debug("cookie for "+pollUri+" exists, just display results");
			this.getResults(settings);
		} else {
			// Display the form if not displaying graphcs on load. This avoid DOM flicker.
			$(settings.pollCssId+" .poll-options").show(); 
		}	
	},
	

	
	// Get results for selected poll
	"getResults": function(settings) {
		this.debug("--- getResults");

		// Call REST to get results for poll
		$.ajax({
			url: "/content/system/modules/com.dispatch.polling/rest/results?poll="+settings.pollUri,
			dataType: "json",
	  		success: function(data){
	  			dPoll.handleResults(data,settings.pollId);
			}
		});	
	},	
	
	
	// Handle poll vote submit
	"submitPoll": function(submit) {
		this.debug("--- submitPoll");
		
		var pollId    = $(submit).parents("form").attr("id");
		var settings  = $("body").data(pollId);
		var voteValue = $(settings.pollCssId+" .poll-options input:checked").val();
	
		this.debug(settings.pollCssId+" .poll-options input:checked");
		this.debug($(settings.pollCssId+" .poll-options input:checked"));
		this.debug("voting for "+voteValue);
	
		if (!settings.multiVote) {
			this.debug("setting cookie as "+settings.pollUri);
			createCookie(settings.pollUri,"voted",1);
		}
		
		
		$.ajax({
			url: "/content/system/modules/com.dispatch.polling/rest/vote?poll="+settings.pollUri+"&choice="+voteValue,
			dataType: "json",
	  		success: function(data){
	  			dPoll.handleResults(data,pollId);
			}
		});
		
	},
	
	
	// Success function for REST calls. Displays results or handles custom settings.
	"handleResults" : function(json, pollId) {
		this.debug("--- handleResults");
		
		var settings = $("body").data(pollId); // Get settings
		
		if (!settings.hideResults) {
    			this.displayResults(json, settings);
    		} else {
    			this.hiddenResults(settings);
    		}	
	},	
	
	
	// If custom hide is set, don't display graphs and show defined message
	"hiddenResults" : function(settings) {
		this.debug("--- hideResults");
		
		$(settings.pollCssId).find(".poll-detail").html('<div class="poll-message">'+settings.hideResults+'</div>');
	},
	
	
	// Display results, uses JSON load from submitPoll() or getResults()
	"displayResults" : function(json, settings) {
		this.debug("--- displayResults");
		
		var pollElement = $(settings.pollCssId);
			
		if (json["result"] == "error") {
			this.debug("ERROR");
			
			pollElement.find(".poll-detail").html('<div class="poll-error">'+json["message"]+'</div>');
		} else {
			this.debug("Displaying results graphs");
			
			
			
			// Go through data and round percentage. Look at custom settings for rounding rules.
			if (!settings.roundToDecimal) {	settings.roundToDecimal = 0; }

			$.each(json["choices"], function(k, pollData) { 
				//alert(index + ': ' + value); 
				pollData.percent = Math.round(pollData.percent*Math.pow(10,settings.roundToDecimal))/Math.pow(10,settings.roundToDecimal);
				  
				json["choices"][k] = pollData;  
			});
			
			this.debug(json);

			
			// Build template, apply template to poll data			
			var resultTmpl = '<li><div class="graph-container"><div class="graph"></div></div><div class="option-name">{{= text}}</div><div class="option-votes">{{= percent}}%</div></li>';
			$.template("pollResultRow", resultTmpl);		
		
			pollElement.find(".poll-detail").html('<ul class="poll-results"></ul>');
		
			$.tmpl("pollResultRow", json["choices"]).appendTo(pollElement.find("ul")); // Loops through JSON and out to template
			
			// If there is a 'withResults' string, append it to the container div here (inside of poll-message) MP 20111031
			if (settings.withResults) {
				$(settings.pollCssId).find(".poll-detail").append('<div class="poll-message">'+settings.withResults+'</div>');
			}
			
			// Animates graphcs from left to right
			var rows = pollElement.find(".graph");
			for (a=0; a < rows.length; a++) {
				var i_percent = json["choices"][a]["percent"];
				if (i_percent >= 100) { i_percent = 99; }
				
				var graph      = $(rows[a]);
				var graphWidth = i_percent+"%";
				
				graph.animate({paddingLeft:graphWidth},"slow"); 
			}
		}			
	}
		
	
} // END class
