$(document).ready(function(){
	$('#content a').click(function(){
		var url = $(this).attr('href');
		if(url.match(/www\.youtube\.com/)){
			url = url.replace(/^http:\/\/(?:www\.youtube\.com|youtu\.be)(?:\/watch\?v=|\/)([\w-]{11})/,'$1');
			window.open("http://avlic.ca/videos?video="+url,'video');
			return false;
		}else{
			return true;
		}
	});
	if($('#content.faq').length > 0){
		var Qs = $('#content.faq h2').length;
		if($('#content.faq').hasClass('drp') || $('#content.faq').hasClass('resources')){
			Qs++;
		}
		$('#content.faq h2').each(function(n){
			var q = n+1;
			if(q < Qs){
				$(this).attr('id','question_'+q).addClass('question').after('<div id="answer_'+q+'" class="answer"></div>');
				$('#answer_'+q).append($('#answer_'+q).nextUntil('h2').clone());
				$('#answer_'+q).nextUntil('h2').detach();
				var h = $('#answer_'+q).outerHeight();
				$(this).attr('data-questionsize',h);
				$('#answer_'+q).animate({height:'toggle',opacity:'toggle'},0);
			}
		});
		$('h2.question').click(function(){
			var id = parseInt($(this).attr('id').replace(/[^\d]+/,''),10);
			var speed = $(this).attr('data-questionsize');
				$('#question_'+id).toggleClass('open');
			$('#answer_'+id).animate({height:'toggle',opacity:'toggle'},(speed*1.5));
		});
	}
	if($('div.ces-section').length > 0){
		var Ss = $('div.ces-section').length;
		$('div.ces-section').each(function(n){
			$(this).attr('data-sectionsize',$(this).outerHeight());
			if(n>0){
				var id = $(this).attr('id');
				$('#'+id+' div.block-content').animate({height:'toggle',opacity:'toggle'},0);
				$('#'+id).next('div.ces-block').animate({height:'toggle',opacity:'toggle'},0);
			}
		});
		$('div.ces-section h2.block-title').click(function(n){
			var id = $(this).parents('div.ces-section').attr('id');
			var speed = $('#'+id).attr('data-sectionsize');
			$('#'+id+' div.block-content').animate({height:'toggle',opacity:'toggle'},speed);
			$('#'+id).next('div.ces-block').animate({height:'toggle',opacity:'toggle'},250);
		});
	}
	if($('#timer').length > 0){
		var now = $('#timer').attr('data-now');
		var end = $('#timer').attr('data-end');
		var time = end - now;
		$('#timer').html('Test in progress. Time remaining: <span></span>');
		var clock = function(){
			var time_ = time;
			var units = {
				'hour': 3600,
				'minute': 60
			};
			var display = {};
			var hour;
			var minute;
			
			for(var u in units){
				display[u] = 0;
				while(time_ >= units[u]){
					var test = time_ - units[u];
					if(test >= 0){
						display[u]++;
						time_ = test;
					}
				}
			}
			
			if(display['hour'] < 10){
				display['hour'] = '0'+display['hour'];
			}
			if(display['minute'] < 10){
				display['minute'] = '0'+display['minute'];
			}
			if(time_ < 10){
				time_ = '0'+time_;
			}
			
			time = time - 1;
			$('#timer span').html(display['hour']+':'+display['minute']+':'+time_);
		}
		setInterval(clock,1000);
		clock();
	}
});
