var score=0;
var questions = [];
var checkedQuestions = [];
var currentQuestion;
var score_posted=false;
var points = {
// Credit and blame?
	q1_a1: 1,
	q1_a2: 0,

	q2_a1: 1,
	q2_a2: 0,

	q3_a1: 1,
	q3_a2: 0,

// Civilized human-beings?
	q4_a1: 1,
	q4_a2: 0,

	q5_a1: 1,
	q5_a2: 0,

	q6_a1: 1,
	q6_a2: 0,

// Raging egomaniacs?
	q7_a1: 1,
	q7_a2: 0,

	q8_a1: 1,
	q8_a2: 0,

	q9_a1: 1,
	q9_a2: 0,

// Respect your time?
	q10_a1: 1,
	q10_a2: 0,

	q11_a1: 1,
	q11_a2: 0,

	q12_a1: 1,
	q12_a2: 0,

// Willing to pay what you are worth?
	q13_a1: 1,
	q13_a2: 0,

	q14_a1: 1,
	q14_a2: 0,

	q15_a1: 1,
	q15_a2: 0,

// Emotional reactions?
	q16_a1: 1,
	q16_a2: 0,

	q17_a1: 1,
	q17_a2: 0,

// Your overall reactions?
	q18_a1: 1,
	q18_a2: 0,

	q19_a1: 1,
	q19_a2: 0,

	q20_a1: 1,
	q20_a2: 0
};

var Rules = {
	'div#continueButton:click': function(el) {
		var box = currentQuestion;
		goToNextQuestion(box);
	},
	'div.answer li:click': function(el) {
		if (!el.parentNode.hasClassName('answer')) {
			el = el.parentNode;
		}
		var box = el.parentNode.id;
		if (isQuestionChecked(box)) {
			doUncheck(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;
	if (!isQuestionChecked(box)) {
		if ($(box).parentNode.hasClassName('single')) {
			$(box).siblings().each(function(boxsib){
				var el = boxsib.descendants()[0];
				doUncheck(el);
				el.className='checked_n';
			});
		}
		var val = getPoints(box);
		updateScore(val*1);		// add to the score
		checkedQuestions.push(box);
		el.className='checked_y';
	}
}

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 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() });
	
	Effect.Fade('score', {
		duration:0.1,
		from:1.0, to:0.01,
		queue: {position: "end", scope: "myQueue"}
	});
	$('score').innerHTML = score;
	Effect.Appear('score', {
		duration:0.5,
		from:0.01, to:1.0,
		queue: {position: "end", scope: "myQueue"}
	});
}


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];
		if (box=='p3') $('sectiontitle').innerHTML = 'Civilized human-beings?';
		else if (box=='p6') $('sectiontitle').innerHTML = 'Raging egomaniacs?';
		else if (box=='p9') $('sectiontitle').innerHTML = 'Respect your time?';
		else if (box=='p12') $('sectiontitle').innerHTML = 'Pay what you are worth?';
		else if (box=='p15') $('sectiontitle').innerHTML = 'Emotional reactions?';
		else if (box=='p17') $('sectiontitle').innerHTML = 'Your overall reactions?';
		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 Client&#8217;s ACHE Score';
		finalScore();
		Effect.BlindDown('p_done', { duration:0.5, queue: 'end' });
		postScore();
	}
}


function finalScore() {
	if (score >= 16) {
		$('score5').className += ' scorehilite';
	}
	else if (score >= 11) {
		$('score4').className += ' scorehilite';
	}
	else if (score >= 5) {
		$('score3').className += ' scorehilite';
	}
	else if (score >= 1) {
		$('score2').className += ' scorehilite';
	}
	else if (score >= 0) {
		$('score1').className += ' scorehilite';
	}
}


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);
});
