var score=0;
var questions = [];
var checkedQuestions = [];
var currentQuestion;
var score_posted=false;
var points = {
// What Are Your Gut Reactions to People?
	q1_a1: 1,
	q1_a2: 0,

	q2_a1: 1,
	q2_a2: 0,

	q3_a1: 1,
	q3_a2: 0,

	q4_a1: 1,
	q4_a2: 0,

	q5_a1: 1,
	q5_a2: 0,

	q6_a1: 1,
	q6_a2: 0,

	q7_a1: 1,
	q7_a2: 0,

	q8_a1: 1,
	q8_a2: 0,

	q9_a1: 1,
	q9_a2: 0,

	q10_a1: 1,
	q10_a2: 0,

	q11_a1: 1,
	q11_a2: 0,

	q12_a1: 1,
	q12_a2: 0,

	q13_a1: 1,
	q13_a2: 0,

	q14_a1: 1,
	q14_a2: 0,

	q15_a1: 1,
	q15_a2: 0,

	q16_a1: 1,
	q16_a2: 0,

	q17_a1: 1,
	q17_a2: 0,

	q18_a1: 1,
	q18_a2: 0,

	q19_a1: 1,
	q19_a2: 0,

	q20_a1: 1,
	q20_a2: 0,

	q21_a1: 1,
	q21_a2: 0,

	q22_a1: 1,
	q22_a2: 0,

	q23_a1: 1,
	q23_a2: 0,

	q24_a1: 1,
	q24_a2: 0,

	q25_a1: 1,
	q25_a2: 0
};

var Rules = {
	'div#continueButton:click': function(el) {
		var box = currentQuestion;
		goToNextQuestion(box);
	},
	'div.answer li:click': function(el) {
		if (el.parentNode.className != 'answer') {
			el = el.parentNode;
		}
		var box = el.parentNode.id;
//		if (isQuestionChecked(box)) {
//			doUncheck(el);
//		}
//		else {
			doCheck(el);
//		}
	},
	'div.answerb li:click': function(el) {
		if (el.parentNode.className != 'answerb') {
			el = el.parentNode;
		}
		var box = el.parentNode.id;
//		if (isQuestionChecked(box)) {
//			doBossUncheck(el);
//		}
//		else {
			doCheck(el);
//		}
	}
	
	/*'#a1 div.answer:click': function(element) {
		var box = element.id;
		var val = eval('points.'+box);
		updateScore(val*1);		// add to the score
		goToNextQuestion(box);
	}*/
}

function getPoints(box) {
	return eval('points.'+box);
}

function postScore() {
	if (!score_posted) {
		var url = 'track.php';
		var pars = 'score=' + score;

		var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			parameters: pars,
			onComplete: function(){score_posted=true;}
		});
	}
}

function doCheck(el) {
	var box = el.parentNode.id;

	updateScores(box);
//	$('sectiontitle').innerHTML = 'score = '+score+', bossscore = '+bossscore;
}

function doUncheck(el) {
	var box = el.parentNode.id;
	if (isQuestionChecked(box)) {
		var val = getPoints(box);
		updateScore(val*-1);	// subtract from the score
	}
	checkedQuestions = checkedQuestions.without(box);
	el.className='checked_n';
}

function doBossUncheck(el) {
	var box = el.parentNode.id;
	if (isQuestionChecked(box)) {
		//var val = getPoints(box);
		//updateScore(val*-1);	// subtract from the score
	}
	checkedQuestions = checkedQuestions.without(box);
	el.className='checked_n';
}


function updateScores(number) {
	var qnum = number.substring(number.indexOf('_')+1);
	var mainnum = number.substring(0,number.indexOf('_')+1);
//	when anything gets clicked
		//first go through and get the current state

		if ($(mainnum+'a1').childNodes[0].className == 'checked_y') {
 			var a1start = true;
		} else {
 			var a1start = false;
		}
		if ($(mainnum+'a2').childNodes[0].className == 'checked_y') {
 			var a2start = true;
		} else {
 			var a2start = false;
		}
		
		if (qnum == 'a1') {
			//if it was already checked
			if (a1start) {
				score -= 1;
				$(mainnum+'a1').childNodes[0].className = 'checked_n';
			} else {
				score += 1;
				$(mainnum+'a2').childNodes[0].className = 'checked_n';
				$(mainnum+'a1').childNodes[0].className = 'checked_y';
			}
		} else if (qnum == 'a2') {
			//if a1 was already checked
			if (a1start) {
				score -= 1;
				$(mainnum+'a1').childNodes[0].className = 'checked_n';
				$(mainnum+'a2').childNodes[0].className = 'checked_y';
			} else if (a2start) {
				$(mainnum+'a2').childNodes[0].className = 'checked_n';
			} else {
				$(mainnum+'a2').childNodes[0].className = 'checked_y';
			}
		}
}


function isQuestionChecked(box) {
	if (checkedQuestions.indexOf(box)!=-1) return true;
	else return false;
}

function updateScore(val) {
	score += val*1;

	var queue = Effect.Queues.get('myQueue');
	queue.each(function(e) { e.cancel() });
	
}


function getQuestions() {
	var divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++) {
		if (divs[i].className=="part") {
			questions.push(divs[i].id);
		}
	}
	currentQuestion = questions[0];
}


function hideStuff() {
	var divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++) {
		if (divs[i].className=="answer") {
			if (!divs[i].id.match(/^q1_/)) divs[i].style.display='none';
		}
	}
}


function goToNextQuestion(box) {
	questions.shift();
	if (questions.length>0) {
		currentQuestion = questions[0];
		Effect.Fade('continue', { duration:0.25, queue: 'end' });
		Effect.DropOut(box, { duration:0.5, queue: 'end' });
		Effect.Appear(questions[0], { duration:0.5, queue: 'end' });
		Effect.Appear('continue', { duration:0.25, queue: 'end' });
	}
	else {
		// go to the finale
		Effect.DropOut('continue', { duration:0.5, queue: 'end' });
		Effect.DropOut(box, { duration:0.5, queue: 'end' });
		$('sectiontitle').innerHTML = "Your Boss's BRASS Score";
		finalScore();
		Effect.BlindDown('p_done', { duration:0.5, queue: 'end' });
		postScore();
	}
}


function finalScore() {
	
//	$('main').morph('height: 680px');
	
	$('big_num').innerHTML = score;
//	$('boss_num').innerHTML = bossscore;
	if (score >= 16) {
//		$('score4').className += ' scorehilite';
		$('results').innerHTML = 'You have the worst of the worst, a CERTIFIED BRASSHOLE.  If you can\'t get him or her fired, get out as fast as you can.';
	}
	else if (score >= 11) {
//		$('score3').className += ' scorehilite';
		$('results').innerHTML = 'You have a pretty bad boss--a BORDERLINE BRASSHOLE. Start planning your escape or hatching a plan for getting rid of this loser.';
	}
	else if (score >= 6) {
//		$('score2').className += ' scorehilite';
		$('results').innerHTML = 'You have a pretty good boss.  You could do better, but could do a lot worse too.';
	}
	else if (score >= 0) {
//		$('score1').className += ' scorehilite';
		$('results').innerHTML = 'You have a damn good boss.   You better treat him or her well!';
	}

/*
	if (bossscore >= 16) {
//		$('score8').className += ' scorehilite';
		$('bossresults').innerHTML = 'Your boss lives in a fool\'s paradise nearly all the time, and it is totally out of touch with reality. He or she can’t handle the truth.';
	}
	else if (bossscore >= 11) {
//		$('score7').className += ' scorehilite';
		$('bossresults').innerHTML = 'Your boss is lives in a fool\'s paradise much of the time.   Facing the truth would help him or her become a better boss.';
	}
	else if (bossscore >= 6) {
//		$('score6').className += ' scorehilite';
		$('bossresults').innerHTML = 'Your boss suffers from mild to moderate symptoms of self-delusion. Nearly all human-beings, especially bosses, are a bit out of touch reality - finding a boss with greater self-awareness won\'t be easy.';
		
		
	}
	else if (bossscore >= 0) {
//		$('score5').className += ' scorehilite';
		$('bossresults').innerHTML = 'Your boss has impressive self-awareness.  He or she has a firm grip on reality and is a rare find.';
	}
*/
	// set up sharing
//	twitter_url = "http://twitter.com/home?status=I got "+ score +" out of 25 on my BRASS test. Click here to find out more. http://bit.ly/arse_test";
//	$('twitter_link').href = twitter_url;
//	facebook_url = "http://www.facebook.com/share.php?u=http://electricpulp.com/guykawasaki/arse%3Fept="+score;
//	$('facebook_link').href = facebook_url;
	
	
	
	// Event.observe('facebook_link', 'click', function (e) {
	// 	u = "http://electricpulp.com/guykawasaki/arse";
	// 	t = "I got "+ score +" out of 24 on my ARSE test.";
	// 	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	// 	return false;
	// });
}


var EventSelectors = {
  version: '1.0_pre',
  cache: [],
  
  start: function(rules) {
    this.rules = rules || {};
    this.timer = new Array();
    this._extendRules();
    this.assign(this.rules);
  },
  
  assign: function(rules) {
    var observer = null;
    this._unloadCache();
    rules._each(function(rule) {
      var selectors = $A(rule.key.split(','));
      selectors.each(function(selector) {        
        var pair = selector.split(':');
        var event = pair[1];
        $$(pair[0]).each(function(element) {
          if(pair[1] == '' || pair.length == 1) return rule.value(element);
          if(event.toLowerCase() == 'loaded') {
            this.timer[pair[0]] = setInterval(this._checkLoaded.bind(this, element, pair[0], rule), 15);
          } else {
            observer = function(event) {
              var element = Event.element(event);
              if (element.nodeType == 3) // Safari Bug (Fixed in Webkit)
            		element = element.parentNode;
              rule.value($(element), event);
            }
            this.cache.push([element, event, observer]);
            Event.observe(element, event, observer);
          }
        }.bind(this));
      }.bind(this));
    }.bind(this));
  },
  
  // Scoped caches would rock.
  _unloadCache: function() {
    if (!this.cache) return;
    for (var i = 0; i < this.cache.length; i++) {
      Event.stopObserving.apply(this, this.cache[i]);
      this.cache[i][0] = null;
    }
    this.cache = [];
  },
  
  _checkLoaded: function(element, timer, rule) {
    var node = $(element);
    if(element.tagName != 'undefined') {
      clearInterval(this.timer[timer]);
      rule.value(node);
    }
  },
  
  _extendRules: function() {
    Object.extend(this.rules, {
     _each: function(iterator) {
       for (key in this) {
         if(key == '_each') continue;         
         var value = this[key];
         var pair = [key, value];
         pair.key = key;
         pair.value = value;
         iterator(pair);
       }
     }  
    });
  }
}

Event.observe(window, 'load', function(event){
	updateScore(0);
/*	hideStuff();*/
	getQuestions();
	EventSelectors.start(Rules);
});

