/*
 * jQuery NBC.com trivia
 *
 * @name jquery.nbc.trivia.js
 * @copyright (c) 2009 NBC.com
 * @author Justin Anderson
 * @version 0.1.0
 *
 *
 *
 *	
 *
 */

(function($){						
	$.fn.trivia = function(o){
		return this.each(function(){
			new $trivia(this,o);
		});
	};
	
	var defaults = {
		list:		'num',
		debug:	true
	};
	
	$.trivia = function(e,o){
		this.options = $.extend({}, defaults, o || {});
		
		this.$this = $this = e;
		this.$doc  =  $doc = o;
		this.init(o);
		
		$($this).addClass('trivia-container');
	}

	var $trivia = $.trivia;
		
	$trivia.fn = $trivia.prototype = {
		trivia: 			'0.2.0',
		alpha:				['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'],
		triviaObj:		{},
		correct:			0,
		incorrect:		0,
		loadOrder:		[],
		totalSlides:	0,
		currentItem:	0,
		count:				0,
		int:					0
	};
	
	$trivia.fn.extend = $trivia.extend = $.extend;
	
	$trivia.fn.extend({
		init: function(o){
		o.search(/\.xml|\.php/gi) != -1 ? this.xmlTrivia(o) : this.staticTrivia(o);
		},
		xmlTrivia: function(o){
			$.get(o,this.buildTrivia);
		},
		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;
			}
		},
		staticTrivia: function(string){
			var xml = this.toXML(string);
			
			this.buildTrivia(xml);
		},
		buildTrivia: function(data){
			var proto = $trivia.prototype;
			proto.questions = [];
			proto.message		= [];
			
			proto.totalSlides = $('slide',data).length;
				$('correct',data).children().each(function(i){
				proto.message[this.nodeName] = $(this).text();
			});
				
			$('slide',data).each(function(i){
				var obj = {};
				obj.question 	= $('question',this).text();
				obj.answer		= parseInt($('question',this).attr('answer'))-1;
				obj.opt				= [];
				
				$('option',this).each(function(j){
					obj.opt.push($(this).text());
				});
			proto.questions.push(obj);
			});
			proto.debug(proto); // DEBUG
			proto.unique();
		},
		buildQuestion: function(question){
			var q = question;
			currentItem = q;
			this.debug('currentItem '+currentItem); // DEBUG
			var answer = this.questions[q].answer;
			
			var output = '<p>'+this.questions[q].question+'</p><form action="#" method="post" enctype="text/plain">';
			var answers=this.questions[q].opt;
			
			for(var i=0;i<answers.length;i++){
				id = defaults.list == 'num'? i+1 : alpha[i];
				output += '<p><label for="option_'+i+'">'+id+')</label> <input type="radio" name="option" id="option_'+i+'" value="'+i+'" />'+answers[i]+'</p>';
			}
			output+='</form><div class="trivia-msg"></div>';
			$($this).html(output);
			this.int++;
			
			this.debug(answer); // DEBUG
			$($this).find('input:radio').click(function(){																	
				var proto = $trivia.prototype;
				proto.debug(proto.questions[proto.currentItem]); // DEBUG
				$($this).find('input:radio').attr('disabled',true);
				choice = ($(this).val());

				if(answer == choice){
					proto.correct++;
					$($this).find('.trivia-msg').html('<p>Correct: <a href="javascript:void(0);" class="next">Next</a></p>');						
					proto.int ++;
				}else{
					//proto.debug(proto.questions[answer].question);
					id = defaults.list == 'num'? answer+1 : proto.alpha[answer];
					$($this).find('.trivia-msg').html('<p>Incorrect: the correct answer is <span class="corrrect-answer">'+id+') '+proto.questions[q].opt[answer]+'</span> <a href="javascript:void(0);" class="next">Next</a></p>');					
				}
				$($this).find('.next').click(proto.getNext);
			});
		},
		getNext: function(){
			var proto = $trivia.prototype;
			proto.correct;
			proto.debug(proto);
			var getNext = proto.count+1;
			if(getNext < parseInt(proto.totalSlides-1)){
				proto.count++;
				proto.buildQuestion(proto.loadOrder[getNext]);
			}else{
				var percent = (proto.correct/proto.totalSlides)*100;
				var msg = '';
				if(percent > 0 && percent <= 30)
					msg = proto.message['c30'];
				else if(percent > 30 && percent <= 50)
					msg = proto.message['c50'];
				else if(percent > 50 && percent <= 75)
					msg = proto.message['c75'];
				else if(percent > 75)
					msg = proto.message['c100']
		
					$($this).html('<p>You got '+proto.correct+' correct.</p><p>'+msg+'</p><a href="javascript:void(0);" class="playagain">Play Again</a>');					
					$($this).find('.playagain').click(proto.reloadTrivia);
			}
			
			proto.reloadAds();		
		},
		reloadTrivia: function(){
			var proto = $trivia.prototype;
			
			proto.correct= 0,
			proto.incorrect=0,
			proto.loadOrder=[0],
			proto.totalSlides=0,
			proto.currentItem=0,
			proto.count=0,
			proto.int=0
			
			proto.staticTrivia($doc);
		},
		unique: function(){
			var exist = false;
			var int		= 0;
			
			for (i=0;int<this.totalSlides;int++){
				exist=false
				var rand = this.genRandom(parseInt(this.totalSlides-1));
				for (j=0;j<this.totalSlides;j++){
					if (this.loadOrder[j] == rand){
						exist=true
						break
					}
				}
				if (exist){
					int--
				} else {
					this.loadOrder[int]=rand
				}
			}
			this.buildQuestion(this.loadOrder[0]);
		},
		showLoader: function(msg){
			
		},
		genRandom: function(Max){
			return Math.round(Math.random()*Max);
		},
		reloadAds: function(){
			$trivia.prototype.debug('Call reloadAds ***************');
			
			s.t();
			if($('iframe.#ad728x90').length > 0)
				window.ad728x90.location.reload();
			if($('iframe.#ad300x250').length > 0)	
				window.ad300x250.location.reload();
		},
		debug: function(e){
			if(window.console && window.console.log && defaults.debug)
			console.log(e)
		}
	});
	
	$trivia.extend({
		defaults: function(d){
			return $.extend(defaults, d || {});
		}		
	});
	
		
})(jQuery);
