﻿var style = 'gray_pogaday.css';
/* chizh */

var loadingLinesInterval = undefined;
var loadingPercentInterval = 0;
var loadingPercentNum = [];
var loadingPercentStopNum = 0;
var loadingPercentStep = 0;
var loadingPercentElem = 0;
var form_default_value = new String();

statusLines = [];


var menuArray = [
	'Первый день',
		'Первый день',
			'Первый день',
	'Второй день',
	'Второй день',
		'Второй день',
'Третий день',
'Третий день',
'Третий день',
'Четвертый день',
'Четвертый день',
'Четвертый день',

'Пятый день',
'Пятый день',
'Пятый день',

'Шестой день',
'Шестой день',
'Шестой день',

'Седьмой день',
'Седьмой день',
'Седьмой день'

];
var daysArray = [
'сухарик с чаем или черным кофе',	
'2 яйца, сваренных вкрутую, 80 г, заправленного ложечкой масла, шпината и помидор',	
'одна котлета и 150 г салата из помидоров и зеленого лука с небольшим количеством масла',	
'чай или кофе',	
'200 г морковки варенной и одно яйцо, сваренное вкрутую',	
'250 г салата из мандарина, груши, яблока, банана или иных фруктов',	
'стакан яблочного сока натурального',	
'250 г рыбы, отварной или жаренной, 1 яблоко, 1 помидор',	
'одна мясная котлета с гарниром',	
'стакан сока морковного',	
'100 г салата из зелени, 200 г жареной курицы',	
'2 яйца сваренных вкрутую, 100 г, заправленной маслом, тертой морковки',
'сухарик с чаем без сахара',
'200 г жареного мяса и 150 г, заправленного лимонным соком, салата из капусты',	
'150 г сыра и 100 г, заправленной маслом, тертой моркови',	
'стакан сока морковного',
'200 г курицы, отварной или жареной',	
'300 г различных фруктов'	
	
];


nextStatusLine = function( SLIndex ){
	var next = Math.round( Math.random() * statusLines[SLIndex].array.length );
	jQuery( statusLines[SLIndex].elem ).text( statusLines[SLIndex].array[next] );
}

startStatusLine = function( element, actArray ){
	statusLines.push({
		elem: element,
		array: actArray,
		interval: false
	});
	var statusLineIndex = statusLines.length - 1;
	statusLines[statusLineIndex].interval = setInterval( function(){ nextStatusLine(statusLineIndex); }, 30 );
	
	return statusLineIndex;
}
stopStatusLine = function( SLIndex ){
	jQuery( statusLines[SLIndex].elem ).hide(0);
	clearInterval( statusLines[SLIndex].interval );
}
pauseStatusLine = function( SLIndex ){
	clearInterval( statusLines[SLIndex].interval );
}

function loadingLineMove( loadingLines ){
	if (!jQuery.browser.msie){
		var posXBg = parseInt( jQuery(loadingLines).css('backgroundPosition') );
		if ( posXBg < -27 ){
			jQuery(loadingLines).css({'backgroundPosition':'-3px 4px'});
		}else{
			jQuery(loadingLines).css({'backgroundPosition':posXBg-2+'px 4px'});
		}
	}
	//jQuery(loadingLines).animate( { 'backgroundPosition': '27px 4px' }, 1000, 'linear', function(){ loadingLineMove( loadingLines ); } );
}
function loadingPercentSet(indexLPN){
	loadingPercentNum[indexLPN].num++;
	if ( loadingPercentNum[indexLPN].stopNum <= loadingPercentNum[indexLPN].num ){
		clearInterval(loadingPercentNum[indexLPN].interval);
		jQuery(loadingPercentNum[indexLPN].elem).text(loadingPercentNum[indexLPN].stopNum);
	}else{
		jQuery(loadingPercentNum[indexLPN].elem).text(loadingPercentNum[indexLPN].num);
	}
}
function loadingPercentStart(elem, startNum, stopNum, delay){
	//clearInterval(loadingPercentInterval);
	loadingPercentNum.push({
		elem: elem,
		startNum: startNum,
		stopNum: stopNum,
		interval: false,
		num: startNum
	});
	var indexLPN = loadingPercentNum.length - 1;
	var nums = stopNum - startNum;
	var loadingPercentStep = Math.round( delay / nums );
	
	loadingPercentNum[indexLPN].interval = setInterval( function(){ loadingPercentSet(indexLPN) }, loadingPercentStep );
	return indexLPN;
}
function makeDietAnimate(){
	var loadingLines = jQuery('#afterTestScene .loadingLine .line');
	jQuery('#afterTestScene .loadingLine').css({'overflow': 'hidden'});
	loadingLinesInterval = setInterval( function(){ loadingLineMove( loadingLines ); }, 50 );
	var elem = jQuery('#afterTestScene>div.step1>div.loadingPercent>span.num');
	var elem2 = jQuery('#afterTestScene>div.step2>div.loadingPercent>span.num');
	var elem3 = jQuery('#afterTestScene>div.step3>div.loadingPercent>span.num');
	
	loadingPercentStart(elem, 7, 15, 500);
	jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'15%'}, 500, 'linear');
	
	
	setTimeout( function(){ //Ваше имя и фамилия
		var inputVal = parseString( jQuery('input[name="fio"]').attr('value') );
        jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше имя и фамилия: <strong>' + inputVal + '</strong></p>');
		loadingPercentStart(elem, 15, 23, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'23%'}, 500, 'linear');
	}, 500 );

	setTimeout( function(){ //Дата Вашего рождения
        var inputVal1 = parseInt( jQuery('select[name="birth_day"]').val() );
        var inputVal2 = parseInt( jQuery('select[name="birth_month"]').val() );
		var inputVal3 = parseInt( jQuery('select[name="birth_year"]').val() );
        jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Дата Вашего рождения: <strong>' + inputVal1 + '.' + inputVal2 + '.' + inputVal3 + '</strong></p>');
		loadingPercentStart(elem, 23, 30, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'30%'}, 500, 'linear');
	}, 1000 );

	setTimeout( function(){ //Какого цвета Ваши глаза
		var inputVal = parseInt( jQuery('input:checked[name="glaza"]').attr('value') );
		switch( inputVal ){
			case 1:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет глаз: <strong>Карие</strong></p>');
			break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет глаз: <strong>Серые</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет глаз: <strong>Голубые</strong></p>');

            break;
			case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет глаз: <strong>Зелёные</strong></p>');
			break;
		}
		loadingPercentStart(elem, 30, 35, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'35%'}, 500, 'linear');
	}, 1500 );

	setTimeout( function(){ //Какого цвета Ваши волосы
        var inputVal = parseInt( jQuery('input:checked[name="volosi"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет волос: <strong>Светлые</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет волос: <strong>Рыжие</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет волос: <strong>Каштановые</strong></p>');

            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Цвет волос: <strong>Чёрные</strong></p>');
            break;
        }
		loadingPercentStart(elem, 35, 40, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'40%'}, 500, 'linear');
	}, 2000 );

	setTimeout( function(){ //Каким было Ваше детство
        var inputVal = parseInt( jQuery('input:checked[name="detstvo"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше детство было <strong>тяжёлым</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше детство было <strong>тяжёлым, но с моментами радости</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше детство было <strong>обычным</strong></p>');

            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше детство было <strong>радостным</strong></p>');
            break;
        }
		loadingPercentStart(elem, 40, 45, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'45%'}, 500, 'linear');
	}, 2500 );

	setTimeout( function(){ //Каким было Ваше прошлое(Прошлое: негатив/трудный опыт/опыт/позитив.)
        var inputVal = parseInt( jQuery('input:checked[name="proshloe"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Прошлое: <strong>негатив</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Прошлое: <strong>трудный опыт</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Прошлое: <strong>опыт</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Прошлое: <strong>позитив</strong></p>');
            break;
        }
		loadingPercentStart(elem, 45, 50, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'50%'}, 500, 'linear');
	}, 3000 );

    setTimeout( function(){ //Вы когда-либо причиняли людям зло(Тёмная сторона: да/скорее да/скорее нет/нет)
        var inputVal = parseInt( jQuery('input:checked[name="zlo"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Тёмная сторона: <strong>да</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Тёмная сторона: <strong>скорее да</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Тёмная сторона: <strong>скорее нет</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Тёмная сторона: <strong>нет</strong></p>');
            break;
        }
        loadingPercentStart(elem, 50, 55, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'55%'}, 500, 'linear');
    }, 3500 );

    setTimeout( function(){ //Ваше желание на ближайшее будущее(Проекция: бизнес/любовь/популярность/развитие.)
        var inputVal = parseInt( jQuery('input:checked[name="future"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Проекция: <strong>бизнес</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Проекция: <strong>любовь</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Проекция: <strong>популярность</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Проекция: <strong>развитие</strong></p>');
            break;
        }
        loadingPercentStart(elem, 55, 60, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'60%'}, 500, 'linear');
    }, 4000 );

    setTimeout( function(){ //Имя самого близкого человека
        var inputVal = parseString( jQuery('input[name="bliz_name"]').attr('value') );
        jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Имя самого близкого человека: <strong>' + inputVal + '</strong></p>');
        loadingPercentStart(elem, 60, 65, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'65%'}, 500, 'linear');
    }, 4500 );

    setTimeout( function(){ //Ваше любимое число
        var inputVal = parseString( jQuery('input[name="my_num"]').attr('value') );
        jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваше любимое число: <strong>' + inputVal + '</strong></p>');
        loadingPercentStart(elem, 65, 70, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'70%'}, 500, 'linear');
    }, 5000 );

    setTimeout( function(){ //«Чёрные полосы» неудач в Вашей жизни(постоянно/часто/иногда/редко)
        var inputVal = parseInt( jQuery('input:checked[name="black_lines"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Чёрные полосы» неудач в Вашей жизни: <strong>постоянно</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Чёрные полосы» неудач в Вашей жизни: <strong>часто</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Чёрные полосы» неудач в Вашей жизни: <strong>4иногда</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Чёрные полосы» неудач в Вашей жизни: <strong>5редко</strong></p>');
            break;
        }
        loadingPercentStart(elem, 70, 75, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'75%'}, 500, 'linear');
    }, 5500 );

    setTimeout( function(){ //Удивительные совпадения в Вашей жизни(постоянно/часто/иногда/редко)
        var inputVal = parseInt( jQuery('input:checked[name="sovpad"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Удивительные совпадения в Вашей жизни: <strong>постоянно</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Удивительные совпадения в Вашей жизни: <strong>часто</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Удивительные совпадения в Вашей жизни: <strong>иногда</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Удивительные совпадения в Вашей жизни: <strong>редко</strong></p>');
            break;
        }
        loadingPercentStart(elem, 75, 80, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'80%'}, 500, 'linear');
    }, 6000 );

    setTimeout( function(){ // «Дежавю», или ощущение, что когда-то с Вами это уже происходило? постоянно/часто/иногда/редко.
        var inputVal = parseInt( jQuery('input:checked[name="dejavu"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Дежавю»: <strong>постоянно</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Дежавю»: <strong>часто</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Дежавю»: <strong>иногда</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>«Дежавю»: <strong>редко</strong></p>');
            break;
        }
        loadingPercentStart(elem, 80, 85, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'85%'}, 500, 'linear');
    }, 6500 );

    setTimeout( function(){ //Много ли у Вас друзей? Очень много/достаточно/немного/мало или нет.
        var inputVal = parseInt( jQuery('input:checked[name="friends"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас друзей: <strong>очень много</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас друзей: <strong>достаточно</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас друзей: <strong>немного</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас друзей: <strong>мало или нет</strong></p>');
            break;
        }
        loadingPercentStart(elem, 85, 90, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'90%'}, 500, 'linear');
    }, 7300 );

    setTimeout( function(){ //Много ли у Вас врагов? Очень много/достаточно/немного/мало или нет.
        var inputVal = parseInt( jQuery('input:checked[name="enemies"]').attr('value') );
        switch( inputVal ){
            case 1:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас врагов: <strong>очень много</strong></p>');
            break;
            case 2:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас врагов: <strong>достаточно</strong></p>');
            break;
            case 3:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас врагов: <strong>немного</strong></p>');
            break;
            case 4:
                jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Много ли у Вас врагов: <strong>мало или нет</strong></p>');
            break;
        }
        loadingPercentStart(elem, 90, 95, 500);
        jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'95%'}, 500, 'linear');
    }, 8000 );
	
	setTimeout( function(){ 
		jQuery('#afterTestScene .step1 .loadingLine').slideUp(100);
		jQuery('#afterTestScene .step1 .loadingPercent').slideUp(100);
		jQuery('#afterTestScene .step2').slideDown(300);
		loadingPercentStart(elem2, 0, 20, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'20%'}, 2000, 'linear');
	}, 8000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Обрабатываем данные.........<font color="#78CD14">OK</font></p>');
		loadingPercentStart(elem2, 21, 40, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'40%'}, 2000, 'linear');
	}, 10000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Рассчитываем генетические особенности...........<font color="#78CD14">OK</font></p>');
		loadingPercentStart(elem2, 40, 66, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'60%'}, 2000, 'linear');
	}, 12000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Вычисляем фазу луны...............<font color="#78CD14">OK</font></p>');
		loadingPercentStart(elem2, 66, 83, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'70%'}, 2000, 'linear');
	}, 14000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Судьба детей............<font color="#78CD14">предсказана</font></p>');
		loadingPercentStart(elem2, 83, 88, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'88%'}, 2000, 'linear');
	}, 16000 );
		setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p><b>Судьба...<font color="#78CD14">предсказана</font></b></p>');
		loadingPercentStart(elem2, 88, 100, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'100%'}, 2000, 'linear');
	}, 19000 );
	setTimeout( function(){
		var elem3 = jQuery('#afterTestScene>div.step3>div.loadingPercent>span.num');
		
		// Заполнение верхней полосы
		var time1 = 8000;
		
		// Заполнение второй полосы
		var time2 = Math.floor( time1 / 3 );
		
		// Заполнение 3-ей полосы, начинается после второй полосы
		var time3 = 3500;
		
		jQuery('#afterTestScene .step2 .loadingLine').slideUp(100);
		jQuery('#afterTestScene .step2 .loadingPercent').slideUp(100);
		jQuery('#afterTestScene .step3').slideDown(300);
		
		loadingPercentStart(elem3, 0, 100, time1);
		jQuery('#afterTestScene>div.step3>div.loadingLine>div.line').animate({'width':'100%'}, time1, 'linear');
		
		jQuery('#afterTestScene>div.step3 div.subInfo2').hide();
		stLineElem1 = jQuery('#afterTestScene>div.step3 div.subInfo1 span.stateText:first');
		var stLine1Int = startStatusLine( stLineElem1, menuArray );
		setTimeout( function(){
			jQuery('#afterTestScene>div.step3 div.subInfo1').hide();
			jQuery('#afterTestScene>div.step3 div.subInfo2').show();
			stopStatusLine(stLine1Int);
			stLineElem2 = jQuery('#afterTestScene>div.step3 div.subInfo2 span.stateText:first');
			stLine2Int = startStatusLine( stLineElem2, daysArray );
		}, time2 );
		
		setTimeout( function(){
			jQuery('#afterTestScene>div.step3 div.subInfo2').hide();
			stopStatusLine(stLine2Int);
			jQuery('#afterTestScene .step3>.loadingLine').slideUp(100);
			jQuery('#afterTestScene .step3>.loadingPercent').slideUp(100);
			jQuery('#afterTestScene .step3>.subInfoOfStage').slideUp(100);
			jQuery('#afterTestScene .step3 .hiddened').show(300);
		}, time1 );
	}, 21000 );
    setTimeout( function(){ 
        jQuery('#afterTestScene .step3 .loadingLine').slideUp(100);
        jQuery('#afterTestScene .step3 .loadingPercent').slideUp(100);
        jQuery('#afterTestScene .step3 .hiddened').show(300);
    }, 29000 );
}
/* chizh */
function ctestname()
{
	var testname = 'locationpath';
	testname = testname.substr(testname.lastIndexOf('/')+1);
	testname = testname.substr(testname.lastIndexOf('-')+1);
	testname = testname.substr(0,testname.lastIndexOf('.'));
	return testname;
}
//alert(ctestname());
var i=0; var max=0;
function next_q() {
    $('div.question#'+(i-1)).hide();
    $('div.question#'+i).show();
    $('#qcurrent').text(i);
    savedata(i-1);
    if(i == max) {
        $('div.next').hide();
        $('#q_current_place').text('закончились...');
        $('div.after').show();
        makeDietAnimate();
    }
    i++;
}

function wanna_more() {
    op=0;
    $('div.question').each(function() {
        setCookie('_' + op, '', -7);
        op++;
    });
    $('div.alltest').html(form_default_value);
    init();
}            

function init() {
			//makeDietAnimate();
			
            $('div.question').hide();
            $('div.after').hide();
			$('div.question select').each(function(){if (this.id!='country_select') this.selectedIndex=-1});
            max=1;
            $('div.question').each(function() {
                this.id = max;
                max++;
            });
            $('#qmax').text(max-1);
            i=1;
			i=loadall(i);

            next_q();
            
            $('#test_next_image').click(pressbtn);
	        $('#country_select').change(function() {
            var id = $('#country_select').val();
            if(!id) $('#sms_inp').hide();
            else $('#sms_inp').show();
            });

			}
    



function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}


function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	//alert(c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString()));
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}



function isselected()
{
	var a=false;
	if ($('input', $('div.question#'+(i-1))).length>0) $('input', $('div.question#'+(i-1))).each(
	function(){
		if((this.type=='checkbox')||(this.type=='radio'))a|=this.checked;
		if((this.type=='text'))a|=(this.value.length > 0);
	});
    
	if ($('select', $('div.question#'+(i-1))).length > 0) {
        a = true;
        $('select', $('div.question#'+(i-1))).each(function() {
            if(this.selectedIndex == -1) {
                a = false;
            }
        });
    }

	if ($('textarea', $('div.question#'+(i-1))).length>0) $('textarea', $('div.question#'+(i-1))).each(function(){
		a|=(this.value.length > 0);
	});
	return a;
}

function pressbtn()
{
	if (isselected()){
		next_q();
	} else {
		alert('Нет выбранного ответа!');
	}
}

function savedata(idx)
{
	var vls='';
	if ($('input', $('div.question#'+(idx))).length>0) $('input', $('div.question#'+(i-1))).each(
	function(){
		vls = ";"+this.checked?'1':'0';
	});
	if ($('select', $('div.question#'+(idx))).length>0) vls = ";"+this.selectedIndex;
	if ($('textarea', $('div.question#'+(idx))).length>0) $('textarea', $('div.question#'+(i-1))).each(function(){
		vls = ";"+this.value;
	});	
	//alert(ctestname()+'_'+i.toString()+' : '+vls.substr(1));
	setCookie(ctestname()+i.toString(),vls.substr(1),7);
}



function loaddata(idx)
{
	if (idx==0) return;
	var vls = getCookie(ctestname()+'_'+idx.toString());
	if ($('input[type=text]', $('div.question#'+(idx))).length>0)
	{
		$('input[type=text]', $('div.question#'+(idx)))[0].value = vls;
	}
	if ($('textarea', $('div.question#'+(idx))).length>0)
	{
		$('textarea', $('div.question#'+(idx)))[0].value = vls;
	}
	if ($('input[type=radio]', $('div.question#'+(idx))).length+$('input[type=checkbox]', $('div.question#'+(idx))).length>0){
			 
		vls = vls.split('_');
		var items = $('input', $('div.question#'+(idx)));
		for (var j=0; j<vls.length; j++)
		{
			 items[j].checked = parseInt(vls[j])!=0;
		}
	}
	
	if ($('select', $('div.question#'+(idx))).length>0) {
		$('select', $('div.question#'+(idx)))[0].selectedIndex = vls;
	}
	
	//alert(ctestname()+'_'+idx.toString()+' : '+vls.substr(1));
}

function loadall(i)
{
	while (getCookie(ctestname()+'_'+i.toString()) && (getCookie(ctestname()+'_'+i.toString())!=''))
	{
		loaddata(i);
		i++;
	}
	return i;
}

function set_dates() {
    for(dd = 1; dd < 32; dd++) {
        $('select[name=birth_day]').append('<option value="' + dd + '">' + dd + '</option>');
    }
    $('select[name=birth_day] option:first').attr('selected', 'selected');
    
    $('select[name=birth_month]').append('<option value="1">Январь</option>');
    $('select[name=birth_month]').append('<option value="2">Февраль</option>');
    $('select[name=birth_month]').append('<option value="3">Март</option>');
    $('select[name=birth_month]').append('<option value="4">Апрель</option>');
    $('select[name=birth_month]').append('<option value="5">Май</option>');
    $('select[name=birth_month]').append('<option value="6">Июнь</option>');
    $('select[name=birth_month]').append('<option value="7">Июль</option>');
    $('select[name=birth_month]').append('<option value="8">Август</option>');
    $('select[name=birth_month]').append('<option value="9">Сентябрь</option>');
    $('select[name=birth_month]').append('<option value="10">Октябрь</option>');
    $('select[name=birth_month]').append('<option value="11">Ноябрь</option>');
    $('select[name=birth_month]').append('<option value="12">Декабрь</option>');
    $('select[name=birth_month] option:first').attr('selected', 'selected');

    for(yy = 1970; yy <= 2000; yy++) {
        $('select[name=birth_year]').append('<option value="' + yy + '">' + yy + '</option>');
    }
    $('select[name=birth_year] option:first').attr('selected', 'selected');
}

$(document).ready(function(){
    set_dates();
    
    var url = new String(location.href);
    if(url.indexOf('#questions') != -1) {
        start_test();
    }
    
    form_default_value = $('div.alltest').html();
	init();
});

function start_test() {
    $('div.alltest').show(100);
    $('div.uznai').hide(100);
}

