/*
 * jQuery NBC.com poll
 *
 * @name jquery.nbc.poll.js
 * @copyright (c) 2009 NBC.com
 * @author Justin Anderson
 * @version 0.2.0
 *
 *
 * @example $('.poll_body').poll('poll.xml');
 * @desc	set destination of poll container and source file
 * @example $('.poll_body').poll('poll.xml',{loadingImage: 'ajax-loader.gif'});
 * @desc	change setting location of ajax loading graphic
 *
 *	
 *
 */

(function($){						
	$.fn.poll = function(o){
		return this.each(function(){
			new $poll(this,o);
		});
	};
	
	var defaults = {
		pollColor:		'666666',
		animate: 			true,//false,
		transition: 	'fade',
		delay: 				3000,
		loadingImage: '/assets/images/ajax-loader.gif',
		postTo:				'/app/polls/spc/bin/pollSubmitWeb_ajax.php',
		getJSON:			'/app/polls/spc/services/?method=getResultsByPollId',
		debug:				false
	};
	
	$.poll = function(e,o){
		this.options = $.extend({}, defaults, o || {});
		this.po = {};
		$this = e;
		poll.po = [];
		
		this.init(o);
	}
	
	var poll = this || {};
	var $poll = $.poll;
		
	$poll.fn = $poll.prototype = {
		poll: '0.2.0',
		//po:		[]	,
		ra:		[],
		container: ''
	};
	
	var proto = $poll.prototype;
	
	$poll.fn.extend = $poll.extend = $.extend;
	
	$poll.fn.extend({
		init: function(o){
		$($this).append(this.showLoader('Loading Poll...'));
		o.search(/\.xml|\.php/gi) != -1 ? this.xmlPoll(o) : this.staticPoll(o);
		//$($this).find('button').live('click',this.submitPoll);
		
		},
		xmlPoll: function(o){
			$.get(o,this.buildPoll);
		},
		buildPoll: function(data){
			
			poll.pollColor 	= $('pollColor',data).text();
			poll.siteId 		= $('siteId',data).text();
			poll.showDir		= $('showDir',data).text();
			poll.campaignId	= $('campaignId',data).text();
			poll.pollId			= $('pollId',data).text();
			poll.question		=	$('question',data).text();
			
			$("option",data).each(function(i){
				poll.po.push($(this).text());
			});
			proto.debug(proto);
			
			var output = '<div class="poll_container"><p>'+poll.question+'</p><div class="poll-content"><form name="poll" class="pollForm" action="'+defaults.postTo+'" method="post" onsubmit="return false;"><ul><input type="hidden" name="siteId" value="'+poll.siteId+'" /><input type="hidden" name="campaignId" value="'+poll.campaignId+'" /><input type="hidden" name="pollId" value="'+poll.pollId+'" />';
			$(poll.po).each(function(i,value){
				output += '<li><input type="radio" name="vote" class="vote" id="vote_'+i+'" value="'+i+'"><label for="vote_'+i+'" /> '+value+'</li>';
			});
			$($this).find('.ajax-loader').remove();
			output += '</ul><button type="submit" name="submitPoll" class="submitPoll">Submit</button></form></div></div>';
			$($this).append(output);
			$($this).find('button').click(proto.submitPoll);
		},
		staticPoll: function(o){
			var wrap = $('<div class="poll-content">');
			$($this).children('form').wrap(wrap);
			var xml = this.toXML(o);
			$($this).prepend('<p>'+$('q',xml).text()+'</p>');
			var output = '<ul>';
			$('o',xml).each(function(i){
				poll.po.push($(this).text());
				output += '<li><input type="radio" name="vote" class="vote" id="vote_'+i+'" value="'+i+'"><label for="vote_'+i+'" /> '+$(this).text()+'</li>';
			});
			output += '</ul><button type="submit" name="submitPoll" class="submitPoll">Submit</button>';
			$($this).find('.ajax-loader').remove();			
			$($this).find('form').append(output);
			$($this).find('button').click(this.submitPoll);
		},
		toXML: function(string){
			try {
				xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
				xmlDoc.async="false";
				xmlDoc.loadXML(string);
			return xmlDoc;
			}	catch(e) {
				parser=new DOMParser();
				xmlDoc=parser.parseFromString(string,"text/xml");
				return xmlDoc;
			}
		},
		submitPoll: function(){
			proto.debug(this);
			var form = $(this).parents('form');
			var ra = [];
			var parent = $(this).parents('.poll-content');
			proto.container = parent;
			proto.pollId = form.find('input[name=pollId]').val();
			if(proto.valButton(form.find('input[name=vote]'))){
				var serialize = form.serialize();
				$(proto.container).html(proto.showLoader('Posting Poll...'));
				$.ajax({
					type: 		"POST",
					url: 			defaults.postTo,
					data: 		serialize,
					success: 	proto.getResults,
					error: 		proto.errorHandler
				});
			} else {
				alert('Error: Select option')
			}
		},
		getResults: function(results){
			$(proto.container).html(proto.showLoader('Retrieving Results...'));
			var ra = $poll.prototype.ra;
			$.getJSON(defaults.getJSON+"&pollId="+proto.pollId+"&type=json",function(data){
				var output = '<ul>';											
				$.each(data, function(j){
					ra[data[j]['vote']] = data[j]['percent'];											
				});				
				$(poll.po).each(function(i,value){
					output += '<li>'+value+'</li>';
					//output += '<li><span class="percent">'+(ra[i] != null ? ra[i] : 0)+' %</span><span id="bar_'+i+'" class="bar_wrap"><span class="bar" style="'+(defaults.animatePoll ? '': 'width:'+(ra[i] != null ? ra[i] : 0)+'%;')+'"></span></span></li>';
					output += '<li><span class="percent">'+(ra[i] != null ? ra[i] : 0)+' %</span><span id="bar_'+i+'" class="bar_wrap"><span class="bar" style="'+(defaults.animate ? '': 'width:'+ra[i]+'%;')+'background: #'+(poll.pollColor != '' ? poll.pollColor : defaults.pollColor)+';"></span></span></li>';
				});
				output += '</ul>';
				if(defaults.transition == 'fade'){
					$(proto.container).fadeOut(defaults.transition,function(){
						$(proto.container).html(output);
						if(defaults.animate)
								proto.animate();
						$(proto.container).fadeIn(defaults.transition);
					});						
				} else {
					$(proto.container).html(output);
				}					
			});					
		},
		errorHandler: function(msg){
			$poll.prototype.debug(msg.statusText);
		},
		animate: function(){
			$(proto.container).find('.bar').each(function(i){
				$(this).css('width','0%').animate({
					width: proto.ra[i]+'%'}, 'slow');
			});
		},
		valButton: function(r){
			var cnt = -1;
			for (var i=this.length-1; i > -1; i--) {
				if (this[i].checked) {cnt = i; i = -1;}
			}
			if (cnt > -1)
				return true
			else
				return false;
		},
		showLoader: function(string){
			return '<div class="ajax-loader"><img src="'+defaults.loadingImage+'" class="loading-gif" alt="'+string+'" />'+string+'</div>';
		},
		debug: function(e){
			if(window.console && window.console.log && defaults.debug)
			console.log(e)
		},
		valButton: function(el) {
			var cnt = -1;
			for (var i=el.length-1; i > -1; i--) {
				if (el[i].checked) {cnt = i; i = -1;}
			}
			if (cnt > -1)
				return true
			else
				return false;
		}
	});
	
	$poll.extend({
		defaults: function(d){
			return $.extend(defaults, d || {});
		}		
	});
		
})(jQuery);