/* chizh */
var loadingLinesInterval = undefined;
var loadingPercentInterval = 0;
var loadingPercentNum = 0;
var loadingPercentStopNum = 0;
var loadingPercentStep = 0;
var loadingPercentElem = 0;

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(){
	loadingPercentNum++;
	if ( loadingPercentStopNum <= loadingPercentNum ){
		clearInterval(loadingPercentInterval);
		jQuery(loadingPercentElem).text(loadingPercentStopNum);
	}else{
		jQuery(loadingPercentElem).text(loadingPercentNum);
	}
}
function loadingPercentStart(elem, startNum, stopNum, delay){
	clearInterval(loadingPercentInterval);
	loadingPercentNum = startNum;
	var nums = stopNum - startNum;
	loadingPercentStep = Math.round( delay / nums );
	loadingPercentStopNum = stopNum;
	loadingPercentElem = elem;
	loadingPercentInterval = setInterval( function(){ loadingPercentSet() }, loadingPercentStep );
}
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, 0, 10, 500);
	jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'10%'}, 500, 'linear');
	
	
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('input:checked[name="dinamikavesa"]').attr('value') );
		switch( inputVal ){
			case 1:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 3кг</strong></p>');
			break;
			case 2:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 5 кг</strong></p>');
			break;
			case 3:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 10 кг</strong></p>');
			break;
			case 4:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 20 кг</strong></p>');
			break;
			case 5:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 30 кг</strong></p>');
			break;
			case 6:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Ваш излишний вес: <strong>до 30 кг</strong></p>');
			break;
		}
		loadingPercentStart(elem, 10, 20, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'20%'}, 500, 'linear');
	}, 500 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('input:checked[name="pol"]').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;
		}
		loadingPercentStart(elem, 20, 30, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'30%'}, 500, 'linear');
	}, 1000 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('select[name="vozrast"]').attr('value') );
		switch( inputVal ){
			case 17:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный возраст: <strong>менее 18 лет</strong></p>');
			break;
			case 71:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный возраст: <strong>более 70 лет</strong></p>');
			break;
			default:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный возраст: <strong>'+inputVal+' лет</strong></p>');
		}
		loadingPercentStart(elem, 30, 40, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'40%'}, 500, 'linear');
	}, 1500 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('select[name="ves"]').attr('value') );
		switch( inputVal ){
			case 39:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный вес: <strong>менее 40 кг</strong></p>');
			break;
			case 121:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный вес: <strong>более 120 кг</strong></p>');
			break;
			default:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный вес: <strong>'+inputVal+' кг</strong></p>');
		}
		loadingPercentStart(elem, 40, 50, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'50%'}, 500, 'linear');
	}, 2000 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('select[name="visota"]').attr('value') );
		switch( inputVal ){
			case 149:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный рост: <strong>менее 150 см</strong></p>');
			break;
			case 201:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный рост: <strong>более 200 см</strong></p>');
			break;
			default:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранный рост: <strong>'+inputVal+' см</strong></p>');
		}
		loadingPercentStart(elem, 50, 60, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'60%'}, 500, 'linear');
	}, 2500 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('input:checked[name="gruppakrovi"]').attr('value') );
		switch( inputVal ){
			case 0:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранная группа крови: <strong>не известна</strong></p>');
			break;
			default:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Выбранная группа крови: <strong>'+inputVal+' группа</strong></p>');
		}
		loadingPercentStart(elem, 60, 70, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'70%'}, 500, 'linear');
	}, 3000 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('input:checked[name="allerg"]').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;
			default:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Есть ли пищевые аллергии: <strong>нет</strong></p>');
		}
		loadingPercentStart(elem, 70, 80, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'80%'}, 500, 'linear');
	}, 3500 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('select[name="berem"]').attr('value') );
		switch( inputVal ){
			case 0:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Есть ли у Вас дети: <strong>да</strong></p>');
			break;
			case 1:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Есть ли у Вас дети: <strong>нет</strong></p>');
			break;
		}
		loadingPercentStart(elem, 80, 90, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'90%'}, 500, 'linear');
	}, 4500 );
	setTimeout( function(){ 
		var inputVal = parseInt( jQuery('select[name="zabolevanie"]').attr('value') );
		switch( inputVal ){
			case 0:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Наличие заболеваний щитовидной железы: <strong>нет</strong></p>');
			break;
			case 1:
				jQuery('#afterTestScene .step1 .infoOfStage').append('<p>Наличие заболеваний щитовидной железы: <strong>да</strong></p>');
			break;
		}
		loadingPercentStart(elem, 90, 100, 500);
		jQuery('#afterTestScene>div.step1>div.loadingLine>div.line').animate({'width':'100%'}, 500, 'linear');
	}, 5000 );
	
	
	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');
	}, 6000 );
	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');
	}, 8000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Подбор подходящего режима питания...........<font color="#78CD14">OK</font></p>');
		loadingPercentStart(elem2, 38, 60, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'60%'}, 2000, 'linear');
	}, 10000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Расчет интервалов приёма пищи...............<font color="#78CD14">OK</font></p>');
		loadingPercentStart(elem2, 66, 70, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'70%'}, 2000, 'linear');
	}, 12000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .infoOfStage').append('<p>Подбираем оптимальный срок диеты............<font color="#78CD14">OK</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">OK</font></b></p>');
		loadingPercentStart(elem2, 88, 100, 2000);
		jQuery('#afterTestScene>div.step2>div.loadingLine>div.line').animate({'width':'100%'}, 2000, 'linear');
	}, 19000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step2 .loadingLine').slideUp(100);
		jQuery('#afterTestScene .step2 .loadingPercent').slideUp(100);
		jQuery('#afterTestScene .step3').slideDown(300);
		loadingPercentStart(elem3, 0, 100, 7000);
		jQuery('#afterTestScene>div.step3>div.loadingLine>div.line').animate({'width':'100%'}, 7000, 'linear');
	}, 25000 );
	setTimeout( function(){ 
		jQuery('#afterTestScene .step3 .loadingLine').slideUp(100);
		jQuery('#afterTestScene .step3 .loadingPercent').slideUp(100);
		jQuery('#afterTestScene .step3 .hiddened').show(300);
	}, 33000 );
}
/* 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);
                i++;
                if(i == max) {
                    $('div.next').hide();
                    $('div.next').remove();
					//alert('!');
					//window.scrollTo(0,0);
					$.get('getj.php', function(data){
						if(data != 'OK') {
							//alert('error: '+data);
						}else{
							//alert('Методика составлена!');	
						}
						
					});
					makeDietAnimate();
                }
            }

function init() {
			//makeDietAnimate();
            $('div.question').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 = ($('select', $('div.question#'+(i-1)))[0].selectedIndex!=-1);
	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 savedata(idx)
{
	if (idx==0) return;
	var vls='';
	if ($('input', $('div.question#'+(idx))).length>0) $('input', $('div.question#'+(idx))).each(
	function(){
		if ((this.type=='checkbox')||(this.type=='radio'))
		{
			vls += "_"+(this.checked?'1':'0');
		} else if ((this.type=='text')){
			vls += "_"+this.value;
		}
	});
	if ($('select', $('div.question#'+(idx))).length>0) vls = ";"+$('select', $('div.question#'+(idx)))[0].selectedIndex;
	if ($('textarea', $('div.question#'+(idx))).length>0) $('textarea', $('div.question#'+(idx))).each(function(){
		vls = ";"+this.value;
	});	
	//alert(ctestname()+'_'+idx.toString()+' : '+vls.substr(1));
	setCookie(ctestname()+'_'+idx.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;
}
$(document).ready(function(){
	init();
});