var Answer = Class.create({
	initialize: function(text){
		this.text = text;
		this.options = Object.extend({
			file_name: '',
			width: 0,
			height: 0
		}, arguments[1] || { });
	}
});
var Question = Class.create({
	initialize: function(text){
		this.text = text;
		this.answers = new Array;
		this.control = new Element('span').update('Управляющий елемент не создан!');
		this.options = Object.extend({
			type:    'radio_group',
			direction:    'vertical',
			required_number_of_answer: 1,
			file_name: '',
			width: 0,
			height: 0
		}, arguments[1] || { });
	},
	addAnswer: function(answer){ this.answers.push(answer); },
	toElement: function(){
		var question_conteiner = new Element('div', { className: 'question_conteiner' });
		if (this.options.file_name!='') question_conteiner.insert(new Element('p', { className: 'question' }).update(this.text)).insert(new Element('p', { className: 'question_image' }).insert(new Element('img', { src: this.options.file_name, alt: '', title: '', width: this.options.width, height: this.options.height })));
		else question_conteiner.insert(new Element('p', { className: 'question' }).update(this.text));
		var answer_conteiner = new Element('div', { className: 'answer_conteiner' });
		if (this.options.direction=='horisontal') answer_conteiner.addClassName('horizontal-direction');
		switch (this.options.type) {
		case 'radio_group': this.control = new RadioGroup(this.answers);
		break;
		case 'check_box': this.control = new Checkbox(this.answers, this.options.required_number_of_answer);
		break;
		case 'select': this.control = new SelectTag(this.answers);
		break;
		case 'textarea': this.control = new Textarea();
		break;
		case 'image_radio_group': this.control = new ImageRadioGroup(this.answers, ( this.options.direction=='table' ? 'table' : 'list' ));
		break;
		case 'image_check_box': this.control = new ImageCheckbox(this.answers, ( this.options.direction=='table' ? 'table' : 'list' ), this.options.required_number_of_answer);
		break;
		}
		answer_conteiner.insert(this.control);
		question_conteiner.insert(answer_conteiner);
		return question_conteiner;
	}
});
var Test = Class.create({
	initialize: function(conteiner){
		this.questions = new Array;
		this.countries = new Array;
		this.sms_text = new Hash;
		this.number = new Hash;
		this.price_link_span = new Hash;
		this.price_link = new Hash;
		this.number_price_link = new Hash;
		this.sms_textLow = new Hash;
		this.number_price_linkLow = new Hash;
		this.conteiner = conteiner;
		this.current_question = 1;
		this.questions_count = 0;
		this.options = Object.extend({
			traffic_flow_id: 'direct',
			referer_test_id: '',
			id: '',
			name: '',
			iso_code: 'ru',
			selected_country: 0,
			user_result_id: Math.round(Math.random() * 10000),
			has_question_gender_division: false,
			has_answer_gender_division: false,
			gender: 'first'
		}, arguments[1] || { });
		if (this.options.has_question_gender_division){
			this.questions['male'] = new Array;
			this.questions['female'] = new Array;
			this.questions['first'] = new Array;
		}
	},
	addPriceLink: function(id, text,star){
		this.price_link_span.set(id,'<span style="cursor: pointer;" onclick="window.open(\''+text+'\');">'+star+'</span>');
		this.price_link.set(id,'<a href="'+text+'" target="_blank">информация о стоимости '+star+'</a>')
	},
	addSmsText: function(iso, text){this.sms_text.set(iso,text);},
	addNumberPriceLinkLow: function(iso, text){this.number_price_linkLow.set(iso,text);},
	addNumberPriceLink: function(iso, text){this.number_price_link.set(iso,text);},
	addCountry: function(country){this.countries.push(country);},
	addNumber: function(iso, prefix){this.number.set(iso,prefix);},
	addQuestion: function(question){
		if (this.options.has_question_gender_division)
			this.questions[question.options.gender].push(question);
		else
			this.questions.push(question);
	},
	addSmsTextLow: function(iso, text){this.sms_textLow.set(iso,text);},
	start: function(){
		this.conteiner = $(this.conteiner);
		if (this.options.has_question_gender_division)
			this.questions_count = this.questions['female'].length+1;
		else
			this.questions_count = this.questions.length;
		var question_counter = new Element('span', { className: 'current' }).update('1');
		var button = new Element('input', { type: 'image', src: 'http://img.'+domain+'/images/'+this.options.name+'/controls/next_button.jpg', alt: 'Следующий вопрос', title: 'Следующий вопрос', id: 'next_question_button' });
		button.observe('click', this.nextQuestion.bindAsEventListener(this));
		if (this.options.has_question_gender_division)
			cur_question = this.questions[this.options.gender][this.current_question-1];
		else
			cur_question = this.questions[this.current_question-1];
		this.conteiner.insert(new Element('div',{ id: 'questions_counter' }).insert(new Element('span').update('Вопрос:&nbsp;')).insert(question_counter).insert(new Element('span').update('&nbsp;из&nbsp;'+this.questions_count))).insert(new Element('div', { id:'current_question' }).insert(cur_question)).insert(new Element('div', { id: 'error_message', className: 'blank_message'}).update('&nbsp;')).insert(button);
		this.question_counter = question_counter;
	},
	nextQuestion: function(event){
		var cur_question = null;
		if (this.options.has_question_gender_division)
			cur_question = this.questions[this.options.gender][this.current_question-(this.current_question==1?1:2)];
		else
			cur_question = this.questions[this.current_question-1];
		var selected_value = cur_question.control.hasValue();
		if (selected_value){
			if (this.current_question==1){
				new Ajax.Request('/test_statistic.php?test_id='+this.options.referer_test_id+'&action_type=s&traffic_flow_id='+this.options.traffic_flow_id);
				this.options.gender = selected_value=='&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;мужской'?'male':'female';
			}
			new Ajax.Request('/question_statistic.php?question_id='+cur_question.options.id+'&answer_id='+Math.round(Math.random() * 1000));
			this.current_question++;
			this.question_counter.update(this.current_question);
			if (this.current_question<=this.questions_count){
				$('error_message').removeClassName('error_message').setStyle('background: white;').update('&nbsp;');
				if (this.options.has_question_gender_division)
					cur_question = this.questions[this.options.gender][this.current_question-2];
				else
					cur_question = this.questions[this.current_question-1];
				$('current_question').update(cur_question);
			}else this.finish();
		}else{
			var required_number_of_answer = cur_question.options.required_number_of_answer;
			var error_text = '';
			if (required_number_of_answer==1) error_text = 'Нужно выбрать 1 вариант ответа';
			else error_text = 'Ответов должно быть '+required_number_of_answer;
			$('error_message').update(error_text).addClassName('error_message');
			new Effect.Highlight('error_message', { startcolor: '#ff9999', endcolor: '#ffdddd', restorecolor: '#ffdddd'});
		}
	},
	finish: function(){
		if (this.options.is_restore!='on') new Ajax.Request('/test_statistic.php?test_id='+this.options.referer_test_id+'&action_type=p&traffic_flow_id='+this.options.traffic_flow_id);
		if($('current_question'))$('current_question').remove();
		if($('questions_counter'))$('questions_counter').remove();
		if($('error_message'))$('error_message').remove();
		if($('next_question_button'))$('next_question_button').remove();
		if(this.options.test_status=='active'){
			var conteiner = $(this.conteiner);
			var sms_button = new Element('input', { type: 'image', src: 'http://img.'+domain+'/images/'+this.options.name+'/controls/get_result_button.jpg', alt: 'Получить результат теста', title: 'Получить результат теста', style: 'margin-top: 10px;' });
			var sms_code_input = new Element('input',{ type: 'text', value: '', id: 'sms_code' });
			var sms_number_text = new Element('p',{ className: 'question' }).update('Отправьте SMS'+this.sms_text.get(this.options.iso_code));
			var sms_number_text_low = new Element('p',{className:'low_p'}).update(this.sms_textLow.get(this.options.iso_code) ? 'Если у вас не отправляется SMS на '+this.number.get(this.options.iso_code)+' отправьте SMS'+this.sms_textLow.get(this.options.iso_code) : '');
			
			sms_button.observe('click', this.getTestResult.bindAsEventListener(this));
			
			var comment_conteiner = new Element('div');
			if (this.options.is_show_comment=='on'){
				if($('comment_rules'))$('comment_rules').show();
				var user_name = new Element('input',{ type: 'text', value: '', id: 'user_name', style: 'width: 234px;' });
				var user_avatar = new Element('input',{ type: 'text', value: '', id: 'user_email', style: 'width: 234px;' });
				var comment_code = new Element('input',{ type: 'text', value: '', id: 'user_email', style: 'width: 234px;' });
				var user_message = new Textarea();
				var send_button = new Element('input', { type: 'image', src: 'http://img.'+domain+'/images/'+this.options.name+'/controls/add_comment.jpg', alt: 'Добавить отзыв', title: 'Добавить отзыв', style: 'margin-top: 10px;' });
				this.user_name = user_name;
				this.user_avatar = user_avatar;
				this.user_message = user_message;
				this.comment_code = comment_code;
				send_button.observe('click', this.sendUserMessage.bindAsEventListener(this));
				comment_conteiner.insert(new Element('div', { id: 'test_comments', className: 'loading_message'}).update('Пожалуйста подождите, идет загрузка коментариев...'))
				.insert(new Element('p', { className: 'question' }).update('Добавить отзыв'))
				.insert( new Element('div', { className: 'question_conteiner' }).insert( new Element('p', { className: 'question' }).update('Ваше имя')).insert(new Element('div',{ className: 'input_tag', style: 'width: 250px;' }).insert(new Element('div', { className: 'left_side' }).insert(new Element('div', { className: 'right_side' }).insert(user_name)))))
				.insert( new Element('div', { className: 'question_conteiner' }).insert( new Element('p', { className: 'question' }).update('Код')).insert(new Element('div',{ className: 'input_tag', style: 'width: 250px;' }).insert(new Element('div', { className: 'left_side' }).insert(new Element('div', { className: 'right_side' }).insert(comment_code)))))
				.insert( new Element('div', { className: 'question_conteiner' }).insert( new Element('p', { className: 'question' }).update('Ссылка на аватар')).insert(new Element('div',{ className: 'input_tag', style: 'width: 250px;' }).insert(new Element('div', { className: 'left_side' }).insert(new Element('div', { className: 'right_side' }).insert(user_avatar)))))
				.insert( new Element('p', { className: 'question' }).update('Отзыв')).insert(user_message)
				.insert(send_button)
				.insert(new Element('div', { id: 'comment_error_message', className: 'blank_message'}).update('&nbsp;'))
				.insert(new Element('div', { id: 'comment_info_message', className: 'loading_message', style: 'display: none;'}).update('Пожалуйста подождите, идет загрузка ...'))
			}
			conteiner.insert(new Element('div', { className: 'question_conteiner', id: 'sms_form' }).insert(new Element('p', { className: 'question' }).update("Для получения результатов теста необходимо отправить " +this.options.auth_count+ "SMS. Отправляя смс, Вы соглашаетесь соблюдать <a href='/pages/terms_of_use.html'target='_blank'style='color:inherit;'>правила пользования сайтом</a>. <a href='http://sms911.ru' target='_blank'style='color:inherit;'>Информация для абонентов</a>."))
			.insert(new Element('p', { className: 'question' }).update('Выберите страну, в которой Вы проживаете.'))
			.insert(new SelectTag(this.countries, {onChange: this.changeSmsText.bindAsEventListener(this), default_value: 'Выберите страну', selected: this.options.selected_country})).insert(sms_number_text).insert(sms_number_text_low)
			.insert(new Element('p', { className: 'question' }).update('После отправки сообщения дождитесь ответного SMS с кодом. Полученный код введите в форму размещенную ниже.'))
			.insert(new Element('div',{ className: 'input_tag' }).insert(new Element('div', { className: 'left_side' }).insert(new Element('div', { className: 'right_side' }).insert(sms_code_input))))
			.insert(new Element('div').insert(sms_button))
			.insert(new Element('div', { id: 'sms_error_message', className: 'blank_message'}).update('&nbsp;'))
			.insert(new Element('div', { id: 'sms_info_message', className: 'loading_message', style: 'display: none;'}).update('Пожалуйста подождите, идет загрузка ...'))
			.insert(comment_conteiner)
			);
			if (this.options.is_show_comment=='on') new Ajax.Updater('test_comments','/test/showComments/test_id/'+this.options.id,{evalScripts:true});
			var i=0;
			this.sms_number_text = sms_number_text ;
			this.sms_number_text_low = sms_number_text_low;
			this.sms_code_input = sms_code_input;
		}
	},
	sendUserMessage: function(event){
		if (this.user_name.getValue()!=''&&this.user_message.getValue()!=''){
			var params = new Hash;
			params.set('user_name', this.user_name.getValue());
			params.set('user_message', this.user_message.getValue());
			params.set('user_avatar', this.user_avatar.getValue());
			params.set('comment_code', this.comment_code.getValue());
			new Ajax.Request('/js/test/addComment.pjs',{
				parameters: params,
				onLoading: function() {
					$('comment_info_message').update('Пожалуйста подождите, идет загрузка ...');
					new Effect.Parallel([
					new Effect.Appear('comment_info_message', { sync: true }),
					new Effect.Highlight('comment_info_message', { sync: true, startcolor: '#bbff2b', endcolor: '#ecffc4', restorecolor: '#ecffc4'})]);
				}
			});
		}else{
			$('comment_error_message').update('Нужно заполнить все поля.').addClassName('error_message');
			new Effect.Parallel([
			new Effect.Fade('comment_info_message', { sync: true }),
			new Effect.Highlight('comment_error_message', { sync: true, startcolor: '#ff9999', endcolor: '#ffdddd', restorecolor: '#ffdddd'})]);
		}
		new Effect.ScrollTo('sms_rules');
	},
	changeSmsText: function(value){
		this.options.iso_code = value;
		this.sms_number_text.update('Отправьте SMS'+this.sms_text.get(this.options.iso_code));
		this.sms_number_text_low.update(this.sms_textLow.get(this.options.iso_code) ? '<b>Внимание!</b> Если у вас не отправляется SMS на '+this.number.get(this.options.iso_code)+' отправьте SMS'+this.sms_textLow.get(this.options.iso_code) : '');
	},
	getTestResult: function(event){
		if (this.sms_code_input.getValue()!=''){
			new Ajax.Request('/js/test/sms/test_id/'+this.options.id+'/user_result_id/'+this.options.user_result_id+'/code/'+this.sms_code_input.getValue()+'.pjs',{
				onLoading: function() {
					$('sms_info_message').update('Пожалуйста подождите, идет загрузка ...');
					new Effect.Parallel([
					new Effect.Appear('sms_info_message', { sync: true }),
					new Effect.Highlight('sms_info_message', { sync: true, startcolor: '#bbff2b', endcolor: '#ecffc4', restorecolor: '#ecffc4'})]);
				}
			});
		}else{
			$('sms_error_message').update('Чтобы получить результат теста, нужно ввести код.').addClassName('error_message');
			new Effect.Highlight('sms_error_message', { startcolor: '#ff9999', endcolor: '#ffdddd', restorecolor: '#ffdddd'});
		}
	}
});