var Quiz = function() {
	this.__construct = function () {
		this.s = {
			"form":$('#quiz'),
			"status":1,
			"next":$('#next'),
			"list":$('#responses'),
			"status_1":$('#number_1')[0],
			"status_2":$('#number_2')[0],
			"total": 0,
			"old_status":null,
			"divs": [],
			"list_divs": []
		};
		
		var _this = this;
		this.animating = false;
		
		this.s.next.bind('click',{_this:_this}, _this._onNextClick);
		$('a#retake').bind('click',{_this:_this}, _this._onRetakeClick);
		
		this.s.expands = $("td > a");
		this.s.expands.each(function(a) {
			$(this).bind('click',{_this:_this}, _this._onExpandClick);
		});
	
		this.s.list.find("a").each(function(a) {
			$(this).bind('click',{_this:_this}, _this._onEditClick);
		});

	}
	
	this._onExpandClick = function (o) {
		var _this = o.data._this,
			el = $(this);
		
		if(_this.animating) 
		{
			return false;
		} else {
			_this.animating = true;
		}
		
					
		_this.s.expands.each(function() {
			var td = $(this.parentNode.parentNode).next('tr').find('td'), a=$(this);
			if(td.hasClass('open')) {
				td.find('div').each(function() {
					if(!$(this).hasClass('hidden')) {
						$(this).slideUp(500, function() {
							a.removeClass('open');
							td.removeClass('open');
							td.addClass('close');
						});
					}
				});
			}
		});

		var oTd = $(this.parentNode.parentNode).next('tr').find('td'),
			oChildren = oTd.find('div'),
			origState = $(this).hasClass('open') ? 'open' : 'close';

		if(origState=='close') {
			oChildren.each(function() {
				if(!$(this).hasClass('hidden')) {
					oTd.addClass('open');
					oTd.removeClass('close');
					$(this).slideDown(500, function() {
						el.addClass('open');
						_this.animating = false;
					});
				}
			});
		} else {
			setTimeout(function() {
				_this.animating = false;
			}, 500, _this);
		}
		
		return false;
	}
	
	this._onRetakeClick = function(o) {
		var _this = o.data._this;

		var inputs = $('#quiz input'),
			selects = $('#quiz select option'),
			old_s = _this.s;
			
		inputs.each(function() {
			inp = $(this);
			if( inp.attr('type')!='text' ) {
				inp.attr('checked', '');
				inp.removeClass('checked');
			} else {
				inp.attr('value', '');
			}
		});
		
		selects.each(function() {
			$(this).attr('selected', '');
		});
			
		_this.s = {
			"form":old_s.form,
			"status":1,
			"next":old_s.next,
			"list":old_s.list,
			"status_1":old_s.status_1,
			"status_2":old_s.status_2,
			"total": 0,
			"old_status":null,
			"divs": [],
			"list_divs": [],
			"expands" : old_s.expands
		};
		_this.animating = false;
	
		$('#results_table').find("div").each(function(i) {
			$(this).addClass('hidden').css( {display: 'none'} );
			$(this).parent('td').removeClass('open');
			$(this).parent('td').addClass('close');

		});
			
		_this.s.expands.each(function() {
			$(this).removeClass('open');
		});
	
		for(var i=1; i<=11; i++) {
			$('#'+i).css( {display: 'none'} );	
		}
		
		_this.s.status_2.innerHTML = _this.s.status-1;
		_this.s.status_1.innerHTML = _this.s.status;
		_this.s.next.html('Next Question');
	
		_this.s.list.find("li").each(function(i) {
			$(this).addClass('hidden').css( {opacity: '0'} );
		});
		$('#1').css( { 'opacity':'1','display':'block' } );

		_this.toggleResults();
		
		$('#results span').each(function() {
			$(this).css( {'width':'0px'} );							 
		});
		
		$('#total').addClass('hidden');
		$('#total').html(' ');
		
		return false;
	}
	
	
	this.toggleResults = function (o) {
		if($('div#questionaire').hasClass('hidden')) {
			$('div#results').slideUp(500,function() {
				$('div#results').addClass('hidden');
				$('div#questionaire').removeClass('hidden');
				$('div#questionaire').slideDown(500,function() {
					$('a#retake').addClass('hidden');
				});
			});
		} else {
			var _this = o.data._this,
				params = _this.s.form.serializeArray();
				
			$('div#questionaire').slideUp(500,function() {
				$('div#questionaire').addClass('hidden');
				$('div#results').removeClass('hidden');
				$('div#results').slideDown(500,function() {
					$('a#retake').removeClass('hidden');
	
					$.getJSON("http://www.brainsparklearning.com/projects/clearspring-widget/?ajaxed=1&page=score.ajax&callback=?", params, _this._onAjaxDone );
					
					jQuery.each(params, function(i, field){
						if( field.value.replace(/ /,' ')!='' && field.name=='q_11_email') {
							$.getJSON("http://www.brainsparklearning.com/projects/clearspring-widget/proxy.php?callback=?", params);
						}
					});
					
				});
			});
		}
		
	}
	
	this._onAjaxDone = function (data) {
		
		if(data['mes']!=' ') {
			$('#total').css( {opacity: 0} );
			$('#total').removeClass('hidden');
			$('#total').html(data['mes']);
			$('#total').animate( {opacity: '1'} );
		} 

		for (key in data) {
			switch(data[key]) {
				case 'strong':
					ret = '254px';
					level='strong';
					break;
				case 'moderate':
					ret = '169px';
					level = 'moderate';
					break;
				case 'weak':
					ret = '84px';
					level = 'weak';
					break;
			}
			if($('#'+ key)){
				$('#'+ key+'_'+level).removeClass('hidden');
				$('#'+ key).animate({ 'width': ret });
			}
		}

	}
		
	this._onNextClick = function (el) {
		var _this = el.data._this,
			q = $('div#'+_this.s.status),
			input = $(q).find('input'),
			selects = $(q).find('select'),
			res = $('div#res_'+_this.s.status),
			li = res.parent('li'),
			val = '', inp, flag=false;
		
		if(_this.animating)
		{ 
			return false; 
		} else 
		{
			_this.animating =true;
		}
		
		input.each(function() {
			inp = $(this);
			if(inp.attr('type')=='radio' || inp.attr('type')=='checkbox' ) {
				if(inp.attr('checked')) {
					val = (val=='') ? inp.attr('title') : val+', '+ inp.attr('title');
					inp.addClass('checked');
				} else {
					inp.removeClass('checked');
				}
			} else {
				val = (inp.attr('value')=='') ? '<em>no email</em>' : inp.attr('value') ;
				if(inp.attr('value')!='' && !inp.attr('value').match(/^[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)*\@[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+(?:\.[^\x00-\x20()<>@,;:\\".[\]\x7f-\xff]+)+$/)) {
					alert('Ooops! Something seems to be wrong with your email address.');
					flag = true;
				}
			}
		});
		
		if(flag) {
			return false;
		}

		selects.each(function() {
			val = $(this).val();
			if( val == '13') { val = '13 and up'; }
		});
		
		if(val=='' || val==null) {
			alert('Ooops! Your must select an answer.');
			_this.animating = false;
			return false;
		}
		
		res.css('opacity', '1');
		res.find('span').css('opacity', '1');
		li.css('opacity', '.5');
	
		li.removeClass('hidden');
		li.animate({ opacity: 1 }, 500);

		var span = li.find('span')[0];
		span.innerHTML = val;
				
		if(_this.s.status==11) {
			_this.toggleResults(el);
			_this.animating = false;
			return false;
		} else if( _this.s.status==10 || _this.s.total==10 ) {
			_this.s.next.html('See Results');
		} else {
			_this.s.next.html('Next Question');
		}
		
		if(_this.s.old_status!=null) {
			q.slideUp(500, function() {
				_this.s.status = _this.s.old_status;
				_this.s.status_2.innerHTML = _this.s.status-1;
				_this.s.status_1.innerHTML = _this.s.status;
				 $('div#'+_this.s.status).slideDown(500);
				_this.s.old_status=null;
				_this.animating = false;
			} );
		} else {
			q.slideUp(500, function() {
				// Make sure all questions are closed
				var num = _this.s.status+1,
					sib = $('div#'+num);
				for(var i = _this.s.status; i>0; i--) {
					$('#'+i).css('display','none');
				}
				sib.slideDown(500);
				_this.s.status_2.innerHTML = _this.s.status;
				_this.s.status++;
				_this.s.status_1.innerHTML = _this.s.status;
				_this.animating = false;
			} );
			_this.s.total++;
		}
		
		return false;
	}
	
	this._onEditClick = function (o) {
		var _this = o.data._this,
			res_id = $(this).next(),
			id = res_id.attr('id').substring(4),
			cur_q = $('div#'+_this.s.status), inp;
			
		if(id != _this.s.status) {
			
			 $('div#res_'+_this.s.status).css('opacity', '1');
			 $('div#res_'+_this.s.status).find('span').css('opacity', '1');

			_this.s.old_status = _this.s.total+1;
			_this.s.status = id;
			_this.s.next.html('Done Editing');
			_this.animating = true;
	
			cur_q.slideUp(500, function() {
				$('div#'+id).slideDown(500, function() {
					_this.animating = false;
					$(this).find('input').each(function() {
						inp = $(this);
						if(inp.hasClass('checked')) {
							inp.attr('checked', 'checked');
						}
					});
				});
			});
			
			res_id.css('opacity', '.5');
			//res_id.addClass('editting');
			if(res_id.find('span').hasClass('block')) {
				res_id.find('span').css('opacity', '.5');
			}

			_this.s.status_1.innerHTML = id;
			
		}
		
		return false;
	}
	
	this.__construct();
};


// Load data accordingly
$(function() {
	// If <div id="widget_content"> has BSL class then show specific BSL page (BSLhome.page.php)
	var page = ( $('#widget_content').hasClass('BSL')) ? 'BSLhome.page' : 'home.page' ;
	
	// Get first page content from server 
	// return JSON
	$.getJSON("http://www.brainsparklearning.com/projects/clearspring-widget/?callback=?", {ajaxed:'1', page:page},  function(data){
		// replace content with fetch page
		$('#widget_content').html(data.html);
		// attach listener to start button in header
		$('#start').click(function() { 
			// when user clicks start fetch quiz page and substitute content
			$.getJSON("http://www.brainsparklearning.com/projects/clearspring-widget/?callback=?", {ajaxed:'1', page:'quiz.page'},  function(data){
				$('#start').hide();
				$('#widget_content').html(data.html);
				// instantiate quiz object
				$('#widget_content').ready(function(){
					var quiz = new Quiz();
				});
			});
			return false;
		});
	});
	
	// Check for containing div overflow restrictions
	$('div').each(function() {
		// only edit overflow of containing body tag
		if($(this).css('overflow')=='hidden' && $(this).parent()[0].tagName.toLowerCase()=='body') {
			$(this).css( {'overflow':'auto'} );
		}
	});
});



// CLEARSPRING FUNCTIONS
var kernelUrl = "http://widgets.clearspring.com/o/49ee0cd847bf57c3/49ee0cd847bf57c3/-/-TRK/1/lib.v3.js?onLoad=onLibLoad";
var kernel;

function trace(message)
{
	alert(message);
}
/**
* Callback for Clearspring share services; since sharing is asynchronous,
* we need to specify a callback function to interpret the results.
* In this example, we're using share.get() below to return an embed tag.
* @see http://www.clearspring.com/docs/tech/apis/in-widget/share#share.get
*/
function shareCallback(status, result)
{
	if (status) {
		trace('An error occurred: ' + status);
	} else if (result.tag) {
		trace('Got embed tag: ' + escape(result.tag));
	} else {
		trace('No embed tag returned');
	}
}
function onLibLoad(k)
{
	kernel = k;

	// Send a custom event
	// @see http://www.clearspring.com/docs/tech/apis/in-widget/track
	kernel.track.event('Kernel loaded');
	
	// @see http://www.clearspring.com/docs/tech/apis/in-widget/context
	//trace('You have viewed this widget ' + kernel.context.user.WIDGET_VIEWS + ' times');
	//trace('You seem to be in ' + kernel.context.user.geo.getCountry());
	
	// Retrieves a new embed tag for this widget
	// @see http://www.clearspring.com/docs/tech/apis/in-widget/share
	// Uncomment the following line to see how it works:
	// kernel.share.get('tag', {}, shareCallback);
	
	// Shows menu in given HTML element
	// For example, you'd pass 'menu' to load the menu into this div: 
	// 	<div id="menu"></div>
	// @see http://www.clearspring.com/docs/tech/apis/in-widget/menu
	//kernel.menu.load(document.getElementById('YOUR-ID-HERE')); /* <- uncomment this line after adding your own element ID */
	
	// WARNING:
	// Do not publicly deploy a widget containing your user ID, as it can
	// be used to modify any of your widgets. Treat it like your password.
	
}

document.write('<scr'+'ipt type="text/javascript" src="' + kernelUrl + '"></scr'+'ipt>');
