MTVNI.polls = {
  init: function() {
	  this.getParams().requestId = 0;
	  this.getParams().polls = [];
	  Cogix.initialize({
		  serverName: this.getParams().host,
		  debugElement: this.getParams().debug
		});
	},
  selectAnswer: function(pollid, value, toggleSelect) {
		this.getParams().polls[pollid] = value;
		this.getParams().selectComplete(value);
	},
  tallyAnswer: function(pollid) {
	  this.tally(pollid, this.getParams().polls[pollid]);
	},
  tally: function(pollid, value) {	
	  var tmp = pollid.split("!");
	  try {
		jQuery("#answer").val(value);
		Cogix.submitVote(
				tmp[0],
				{
					pollid: tmp[1],
					pollFormId: this.getParams().container,
					redirectUrl: null,
					returnResults: true,
					onSuccess: function(results) {
						MTVNI.polls.tallyCompleted({ "pollid": pollid, "results": results });
					},
					onError: function(code,message) {
						MTVNI.polls.pollError(code, message);
					}
				}
			);
	  } catch(e) {
		alert(e.message);
	  };
	},
  setCallback: function(callback) { this.getParams().callback = callback; },
  getCallback: function() { return this.getParams().callback; },
  tallyCompleted: function(o) {
	  try {
	    switch(this.getParams().tally.onComplete) {
	      case "loadResultsAfterTally":
	    	this.setCallback(this.getParams().tally.callback);
	        this.getResults(o.pollid);
	        break;
	    };
	  } catch(e) {
		alert(e.message);
	  };
	},
  pollError: function(code, message) {
		alert(message);
	},
  getResults: function(pollid) {
		var tmp = pollid.split("!");
		Cogix.getResults(
				  tmp[0],
				  {
				    pollid: tmp[1],
				    cacheSeconds: 10,
				    onSuccess: function(results) { 
				      MTVNI.polls.getResultsCompleted(results);
				  	},
				    onError: function(code, message) { 
				  	  MTVNI.polls.pollError(code, message);
				  	}
				  }
				);
	},
  getResultsCompleted: function(o) {
	  var callback = this.getCallback();
	  if (callback) callback(o);
	  this.setCallback(null);
	}
};
