/*
 * jQuery NBC.com poll
 *
 * @name jquery.nbc.poll.js
 * @copyright (c) 2009 NBC.com
 * @author Justin Anderson
 * @version 0.2.2
 *
 *
 * @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
 *
 * @todo:	add site service for abv etc.	
 *
 */

(function($){
	$.fn.poll = function(d,o){
		return this.each(function(){
			new $poll(this,d,o);
		});
	};
	
	var defaults = {
		siteId:				null,
		pollId:				null,
		pollColor:		'666666',
		animate: 			true,
		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&',
		bypassResults:false,
		callback:			null,
		reloadAds:		true,
		results:			false,
		debug:				false
	}

	$.poll = function(e,d,o){
		this.options  	= $.extend({},defaults, o || {});		
		this.container 	= e;
		this.poll 			= {};
		this.poll.siteId 		= this.options.siteId || (typeof showId !== undefined?showId:null);
		
		this.init(d);
	}
	
	$poll = $.poll;	
	
	$poll.fn = $poll.prototype = {
		poll: '0.2.2'
	};
	
	$poll.fn.extend = $.extend;
	
	$poll.fn.extend({
		init: function(d){
			this.debug('Init poll'); //debug
			$(this.container).append(this.showLoader('Loading Poll...'));
			d.search(/\.xml|\.php/gi) != -1 ? this.xmlPoll(d) : this.staticPoll(d);
			return false;
		},
		xmlPoll: function(d){
			var self = this;
			$.get(d,function(data){
				self.buildPoll(data);
			});
		},
		buildPoll: function(data){
			var self = this;
			this.poll.pollColor 	= $('pollColor',data).text();
			this.poll.siteId 			= $('siteId',data).text();
			this.poll.showDir			= $('showDir',data).text();
			this.poll.campaignId	= $('campaignId',data).text();
			this.poll.pollId			= $('pollId',data).text();
			this.poll.question		=	$('question',data).text();
			this.poll.po = [];
			
			this.pollId = this.options.pollId || this.poll.pollId;
			
			$("option",data).each(function(i){
				self.poll.po.push($(this).text());
			});
			
			if(this.options.results){
				this.getResults();
				return false;
			}
			
			var output = '<div class="poll_container"><p>'+this.poll.question+'</p><div class="poll-content"><form name="poll" class="pollForm" action="'+this.options.postTo+'" method="post" onsubmit="return false;"><ul><input type="hidden" name="siteId" value="'+this.poll.siteId+'" /><input type="hidden" name="campaignId" value="'+this.poll.campaignId+'" /><input type="hidden" name="pollId" value="'+this.poll.pollId+'" />';
			$(this.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.container).find('.ajax-loader').remove();
			output += '</ul><button type="submit" name="submitPoll" class="submitPoll">Submit</button></form></div></div>';
			$(this.container).append(output);
			$(this.container).find('form').submit(function(){
				self.submitPoll(this);
			});
		},
		staticPoll: function(o){
			var self = this;
			var wrap = $('<div class="poll-content">');
			$(this.container).children('form').wrap(wrap);
			var xml = this.toXML(o);

			this.poll.question = $('q',xml).text();
			this.poll.po = [];
			this.debug(this.options.pollId);
			this.debug(this.poll); // debug
			
			this.poll.pollId = this.options.pollId || $(this.container).find('input[name=pollId]').val();
				
			$(this.container).prepend('<p>'+$('q',xml).text()+'</p>');
					
			var output = '<ul>';
			$('o',xml).each(function(i){
				self.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>';
			
			if(this.options.results){
				this.getResults();
				return false;
			}
			
			$(this.container).find('.ajax-loader').remove();			
			$(this.container).find('form').append(output);
			$(this.container).find('form').submit(function(){
				self.submitPoll(this);
			});
		},
		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(form){
			if(this.options.reloadAds)
				this.reloadAds();
				
			var self = this;
			this.debug($(form).serialize());
			this.form = $(form);
			this.debug(this.poll);
			//this.pollId = this.poll.pollId || this.form.find('input[name=pollId]').val();

			if(this.valButton(this.form.find('input[name=vote]'))){
				this.debug('passed');
				$(this.container).html(this.showLoader('Posting Poll...'));
				$.ajax({
					type: 		"POST",
					url: 			self.options.postTo,
					data: 		$(form).serialize(),
					success: 	function(data){
						self.getResults();
					},
					error: 		self.errorHandler
				});
				
			} else {
				alert('Error: Select option');
				this.debug('Error: Select option');
			}
		},
		getResults: function(){
			this.debug('getResults');
			if(this.options.bypassResults){
				this.callback(this.options.callback);
				return false;
			}
			
			var self = this;
			$(this.container).html(this.showLoader('Retrieving Results...'));
			this.ra = [];
			$.getJSON(this.options.getJSON+"pollId="+this.poll.pollId+"&type=json",function(data){
				var output = '<p>'+self.poll.question+'</p>';
				output += '<ul>';											
				$.each(data, function(j){
					self.ra[data[j]['vote']] = data[j]['percent'];											
				});	
				self.debug(self.options.animate);
				self.debug(self.poll);
				$(self.poll.po).each(function(i,value){
					output += '<li>'+value+'</li>';
					output += '<li class="result-bar"><span class="percent">'+(self.ra[i] !== undefined ? self.ra[i] : "0")+' %</span><span id="bar_'+i+'" class="bar_wrap"><span class="bar" style="'+(self.options.animate ? '': 'width:'+(self.ra[i] !== undefined ? self.ra[i] : "0")+'%;')+'background: #'+(self.poll.pollColor ? self.poll.pollColor :self.options.pollColor)+';"></span></span></li>';
				});
				output += '</ul>';
				self.debug(self.ra);
				if(self.options.transition == 'fade'){
					$(self.container).fadeOut(self.options.transition,function(){
						$(self.container).html(output);
						if(self.options.animate)
								self.animate();
						$(self.container).fadeIn(self.options.transition);
						self.callback(self.options.callback);
					});						
				} else {
					$(self.container).html(output);
				}					
			});					
		},
		callback: function(callback){
			this.debug('Callback: '+callback);
			if(callback != null)
			try{
				var cb = window[callback];			 
				cb();
				return false;
			}catch(e){
				this.debug("Error: "+e);
			}
		},
		animate: function(){
			this.debug('animate');
			var self = this;
			$(this.container).find('.bar').each(function(i){
				$(this).css('width','0%').animate({
					width: (self.ra[i] !== undefined ? self.ra[i] : "0")+'%'}, 'slow');
			});
		},
		valButton: function(r){
			var cnt = -1;
			for (var i=r.length-1; i > -1; i--) {
				if (r[i].checked) {cnt = i; i = -1;}
			}
			if (cnt > -1)
				return true
			else
				return false;
		},
		showLoader: function(string){
			return '<div class="ajax-loader"><img src="'+this.options.loadingImage+'" class="loading-gif" alt="'+string+'" />'+string+'</div>';
		},
		reloadAds: function(){
			this.debug('reloadAds');
			try{
				s.t();
				if($('iframe.#ad728x90').length > 0)
					this.debug('refresh 728');
					window.ad728x90.location.reload();
				if($('iframe.#ad300x250').length > 0)	
					this.debug('refresh 300');
					window.ad300x250.location.reload();
			}catch(e){}			
		},
		error: function(msg){
			this.debug(msg);
		},
		debug: function(s){
			if(this.options.debug == true){
				if(window.console && window.console.log && !$.browser.msie)
					console.log(s);
				else
					alert(s);
			}
		}
	});

})(jQuery);
