function updatePicture(link) 
{
	var img = $(link).prev('img');
	var imgCopy = img.clone();
	img.remove();
	imgCopy.insertBefore(link);
	return false;
}



countDown = {

	init : function(options) 
	{
		this.options = options;

		if(!this.options.continue) 
		{
			this.current_time = new Date(this.options.startDate);
			this.end_time = new Date(this.current_time);
			this.end_time.setMinutes( this.current_time.getMinutes() + this.options.minutes );
		} 
		else 
		{
			interval = this.options.time - this.options.startDateTime;

			this.current_time = new Date();
			this.end_time = new Date(this.current_time);
			this.end_time.setSeconds( this.current_time.getSeconds() + (this.options.minutes * 60) - interval );
		}

		this.tick();
	},
	convert : function(x) 
	{
		if (x > 0) 
		{
			if (x < 60) 
			{
				h = 0;
				m = 0;
				s = x;
			}

			if (x >= 60) 
			{
				sec = x / 60;
				a = (sec.toString()).split(".");
				s = x - (a[0] * 60);

				if (a[0] < 60) 
				{
					h = 0;
					m = a[0];
				}

				if (a[0] >= 60) 
				{
					b = ((a[0] / 60).toString()).split(".");
					h = b[0];
					m = a[0] - (b[0] * 60);
				}
			}

			if (h < 10) { h = h.toString(); h = "0" + h; }
			if (m < 10) { m = m.toString(); m = "0" + m; }
			if (s < 10) { s = s.toString(); s = "0" + s; }

			return h + ":" + m + ":" + s;
		}
		
		return '00:00:00';
	},
	showOnThePage : function(millisec) 
	{
		$('#countdown_timer').html(this.convert(parseInt(millisec/1000)));
	},
	tick : function() 
	{
		this.current_time.setSeconds(this.current_time.getSeconds() + 1);
		var diff = this.end_time.getTime() - this.current_time.getTime();
		this.showOnThePage(diff);
		if (diff >= 1) {
			setTimeout('countDown.tick()',1000);
		} else {
			tester.finishTesting();
		}
	}
};

tester = {
	init : function(options) 
	{
		this.options = options;

		this.questionNumberBox = $('.questionNumber');
		this.answerBox = $('#answerBox');
		this.questionBox = $('#questionTextBox');
		this.pictureBox = $('#questionPictureBox');
		this.progressbarText = $('#progressbarText');
		this.progressbar = $('#progressbar');

		this.timeOfStartOfAnswering = new Date();
		this.setQuestion(this.options.global_id);
	},
	updateNumber : function() 
	{
		this.questionNumberBox.text(this.options.global_id);

		this.updateProgressbar();
	},
	updateProgressbar : function() 
	{
		var progress = Math.round(((this.options.global_id - 1) / this.options.questions_count) * 100);

		this.progressbarText.text(progress);
		this.progressbar.css('width', progress + '%');
	},
	resetQuestion : function() 
	{
		this.questionBox.html('');
		this.answerBox.html('');
		this.pictureBox.html('');
		$('#questionThemeBox').html('');

		var sendInfoBox = $('#sendInfoBox');
		sendInfoBox.append('<div class="row"><div class="col-sm-8" style="margin:0 auto;float:none;"><div class="gray_box"><p>Результат Вашего тестирования необходимо отправить на сервер для обработки.</p><p>Этот процесс может занять некоторое время. Не производите никаких действий и не закрывайте окно браузера до тех пор, пока не будет получен результат тестирования.</p><p style="margin:0 auto; float:none;"><img src="/images/bx_loader.gif" alt=""></p></div></div></div>');
	},
	setQuestion : function(id) 
	{
		var q = this.options.questions[id];
		this.questionBox.text(q['text']);
		this.answerBox.html('');
		$.each(q['answers'],function(a,b) {
			if (q['type'] == tester.options.one_option) {
				html = '<input id="answer-'+a+'" type="radio" name="radio" class="radio"><label for="answer-'+a+'">' + b + '</label>';
				html = '<div class="input_bg">' + html + '</div>';
				tester.answerBox.append(html);
			}
			if (q['type'] == tester.options.few_options) {
				html = '<input id="answer-'+a+'" type="checkbox" class="checkbox"><label for="answer-'+a+'">' + b + '</label>';
				html = '<div class="input_bg">' + html + '</div>';
				tester.answerBox.append(html);
			}
			if (q['type'] == tester.options.user_answer) {
				tester.answerBox.html('');
				tester.answerBox.append('<div class="input_bg"><input type="text" class="textarea" value="" placeholder="Ваш ответ" /></div>');
			}
			tester.answerBox.append('<div class="clear"></div>');
		});
		this.answersChangeStatus();
		this.pictureBox.html('');
		$.each(q['pictures'],function(a,b) {
			tester.pictureBox.append('<div class="testing_img_block"><img src="'+b+'" /></div>');
		});

		/* delete */
		$('#questionThemeBox').text(q['theme']);

		this.updateNumber();

	},
	saveAnswer : function(id) 
	{
		var send = false;
		var clickNext = $('#clickNext');
		var q = this.options.questions[id];
		var answer = [];

		if (q['type'] == this.options.one_option) 
		{
			this.answerBox.find('input:radio:checked').each(function(){
				answer.push($(this).parent().text());
			});
		}

		if (q['type'] == this.options.few_options) 
		{
			this.answerBox.find('input:checkbox:checked').each(function(){
				answer.push($(this).parent().text());
			});
		}

		if (q['type'] == this.options.user_answer) 
		{
			this.answerBox.find('input.textarea').each(function(){
				answer.push($(this).val());
			});
		}

		// сохранение времени ответа
		var current_time = new Date();
		var diff = current_time.getTime() - this.timeOfStartOfAnswering.getTime();
		var time = diff/1000;
		this.timeOfStartOfAnswering = new Date();

		clickNext.attr('disabled','disabled');

		// сохранение ответа
		$.ajax({
			url : this.options.answerUrl,
			data : {
				'question_id' 	: q['id'],
				'userAnswer' 	: answer.join(this.delimiter),
				'time'			: time
			},
			dataType : 'json',
			type : 'POST',
			timeout : 20000,
			success : function(data) {
				if(data.success)
				{
					$('#button'+tester.options.global_id).removeClass('selected');

					if (tester.options.global_id == tester.options.questions_count) 
					{
						tester.finishTesting();
					}
					else 
					{
						tester.options.global_id++;
						$('#button'+tester.options.global_id).addClass('selected');
						tester.setQuestion(tester.options.global_id);
						tester.restoreUserAnswer(tester.options.global_id);
					}

					if($('#messageStep50').data('timer') != 'true' && data.percentStep == 50)
					{
						$('#messageStep50').data('timer', 'true');
						$('#messageStep50').text(data.messageStep);
						setTimeout(function(){
							$('#messageStep50').css('display', 'none');
						}, 10000);
					}
					else if($('#messageStep75').data('timer') != 'true' && data.percentStep == 75)
					{
						$('#messageStep75').data('timer', 'true');
						$('#messageStep75').text(data.messageStep);
						setTimeout(function(){
							$('#messageStep75').css('display', 'none');
						}, 10000);
					}
					else if(data.percentStep == 100)
					{
						$('#messageStep100').text(data.messageStep);
					}
				}
				else
				{
					$('p.uploading_info').remove();
					clickFinish.removeAttr('disabled');
					sendInfoBox.append('<p class="uploading_info" style="color: red;">Произошла ошибка при отправке данных!</p>');
					sendInfoBox.append('<p class="uploading_info" style="color: red;">Подождите пару минут и нажмите на кнопку ниже.</p>');
				}

				if (($('#answerBox input:radio:checked').length > 0)
					|| ($('#answerBox input:checkbox:checked').length > 0)
					|| ($('#answerBox input[type="text"]').length > 0)
				) {
					clickNext.removeAttr('disabled');
				} else {
					clickNext.attr('disabled','disabled');
				}				
			},
			error : function() {
				$('p.uploading_info').remove();
				clickFinish.removeAttr('disabled');
				sendInfoBox.append('<p class="uploading_info" style="color: red;">Произошла ошибка при отправке данных!</p>');
				sendInfoBox.append('<p class="uploading_info" style="color: red;">Подождите пару минут и нажмите на кнопку ниже.</p>');
			}
		});

		this.updateNumber();
		
	},
	restoreUserAnswer : function(id) 
	{
		var q = this.options.questions[id];
		var userAnswer = q['userAnswer'];
		var answers = userAnswer.split(this.options.delimiter);

		if (q['type'] == this.options.one_option) {
			$.each(answers,function(a,b){
				$('#answerBox label').each(function(){
					if ($(this).text() == b) {
						$(this).prev('input:radio').attr('checked','checked');
					}
				});
			});
		}
		if (q['type'] == this.options.few_options) {
			$.each(answers,function(a,b){
				$('#answerBox label').each(function(){
					if ($(this).text() == b) {
						$(this).prev('input:checkbox').attr('checked','checked');
					}
				});
			});
		}
		if (q['type'] == this.options.user_answer) {
			$.each(answers,function(a,b){
				$('#answerBox textarea').text(b);
			});
		}
	},
	finishTesting : function() {
		var clickNext = $('#clickNext');
		var sendInfoBox = $('#sendInfoBox');
		clickNext.css('display','none');
		this.questionNumberBox.remove();
		this.resetQuestion();
		$('p.uploading_info').remove();

		var request = $.ajax({
			url : tester.options.finishUrl,
			data : {
				'questions': this.options.questions
			},
			dataType : 'json',
			type : 'POST',
			timeout : 20000
		});
		request.done(function() {
			window.location.href = tester.options.passUrl;
		});
		request.fail(function(){
			$('p.uploading_info').remove();
			clickFinish.removeAttr('disabled');
			sendInfoBox.append('<p class="uploading_info" style="color: red;">Произошла ошибка при отправке данных!</p>');
			sendInfoBox.append('<p class="uploading_info" style="color: red;">Подождите пару минут и нажмите на кнопку ниже.</p>');
		});
	},

	nextQuestion : function() 
	{
		this.saveAnswer(this.options.global_id);
	},

	answersChangeStatus : function() {
		var clickNext = $('#clickNext');
		if ($('#answerBox input:radio:checked').length > 0 || $('#answerBox input:checkbox:checked').length > 0 || $('#answerBox input[type="text"]').val() != '')
		{
			clickNext.removeAttr('disabled');
		} 
		else 
		{
			clickNext.attr('disabled','disabled');
		}
	}

}

$(function(){
	$('#answerBox').on('change', '*', tester.answersChangeStatus);
	$(document).delegate('#answerBox input[type="text"]', 'keydown', tester.answersChangeStatus);
});