window.onload = function(){getTest();};
var req;
var test = {};
var ua = navigator.userAgent.toLowerCase();
isIE = (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1);
isIE8 = (ua.indexOf("msie 8") != -1 && ua.indexOf("opera") == -1);
isOpera = (ua.indexOf("msie") == -1 && ua.indexOf("opera") != -1);
var user_id = mkUniId(mtRand(10, 14));
var homeUrl = 'http://testing-all.ru/';
//alert(user_id);
function loadXMLDoc(method, url, params , funcName) {

    if (window.XMLHttpRequest) {

        req = new XMLHttpRequest();
        req.onreadystatechange = funcName;
        req.open(method, url, true);
        if( method =='POST' ) req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        req.send(params);
    }
	else if (window.ActiveXObject) {

        req = new ActiveXObject("Microsoft.XMLHTTP");
		isDonkey = 1;

		if (req) {

            req.onreadystatechange = funcName;
            req.open(method, url, true);
            if( method =='POST' ) req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.send(params);
        }
    }
}

function cleanNode(dest)
{
  while (dest.firstChild)
    dest.removeChild(dest.firstChild);
}

function getTest(){
	
	var meta = document.createElement('meta');
	meta.setAttribute( 'http-equiv' , 'X-UA-Compatible' );
	meta.setAttribute( 'content' , 'IE=EmulateIE7' );
	document.getElementsByTagName('head')[0].appendChild( meta );

	sendScriptRequest( homeUrl+"api/starttest", 'id='+test_id+'&uid='+user_id , startTest , ["test123"]);
	//loadXMLDoc( 'POST' , 'http://testing-all.ru/index.php?r=api/starttest' , 'id='+test_id , startTest );

}

function startTest(){

	//if (req.readyState == 4 && req.status == 200){
		//alert( responseText );
		test = eval("(" + responseText + ")");
		delete(responseText);
		if( test.error != '' ){

			document.getElementById('test_'+test_id).innerHTML = test.error;

		}else{

			var css = document.createElement('style');
			css.type = 'text/css';

			if( isIE )
				css.styleSheet.cssText = test.decor.css ;
			else
				css.appendChild( document.createTextNode(test.decor.css) );

			document.getElementById('test_'+test_id).appendChild( css );

			var div = document.createElement( 'div' );
			div.className = 'bgr_test';

			var div2 = document.createElement( 'div' );
			div2.className = 'testHeader';
			div2.appendChild( document.createTextNode( test.lang.title+' '+htmlspecialchars(test.testTitle) ) );

			var img = document.createElement('img');
			img.id = 'loading_'+test_id;
			img.src = homeUrl+'images/loading.gif';
			img.style.display = 'none';
			div2.appendChild( img );

			div.appendChild( div2 );

			div2 = document.createElement( 'div' );
			div2.style.cssFloat = 'left';
			div2.style.width = '70%';
			div2.id = 'main'+test_id;

			div2.appendChild( document.createTextNode(test.description) );

			div.appendChild(div2);

			div2 = document.createElement('div');
			div2.style.cssFloat = 'left';
			div2.style.width = '30%';
			div2.id = 'ads'+test_id;

			div.appendChild(div2);

			div2 = document.createElement('div');
			div2.style.clear = 'both';
			div.appendChild(div2);

			div2 = document.createElement('div');
			div2.className = 'nav';
			div2.id = 'nav_'+test_id;

				var button = document.createElement('button');
				button.setAttribute( 'type', 'button' );
				if( isIE&&!isIE8 )
					button.setAttribute( 'onclick', function(){firstQuestion();} );
				else
					button.onclick = function(){firstQuestion();};
				button.innerHTML = test.lang.startTest;

				div2.appendChild(button);


			div.appendChild(div2);

			span = document.createElement('span');
			span.innerHTML = "<span style='float:right;font-size:10px'>"+test.lang.makeOn+" <a href='http://testing-all.ru' style='text-decoration:none;'><font color='#275d9b' style='font-weight:bold'>"+test.lang.testing+"</font> <font color='#9bbd1b' style='font-weight:bold'>"+test.lang.all+"</font></a></span><div style='clear:both'></div>";

			div.appendChild(span);

			document.getElementById('test_'+test_id).appendChild( div );

			var img = document.createElement('img');
			img.src = homeUrl+'api/image'+'?uid='+user_id+'&tid='+test_id+'&resolution='+screen.width+'x'+screen.height+'&colorDepth='+screen.colorDepth+'&type=test&referer='+escape(document.referrer);
			document.getElementById('test_'+test_id).appendChild( img );
		}



	//}

}

function firstQuestion(){
	
	var divMain = document.getElementById('main'+test_id);
	var divAds = document.getElementById('ads'+test_id);
	var divNav = document.getElementById('nav_'+test_id);

	cleanNode(divMain);
	cleanNode(divNav);

	/*Устанавливаем вопрос*/
	var div3 = document.createElement('div');
	div3.className = 'question';
	div3.id = 'question_'+test_id;

	if( test.decor.shownum == '1' ){

		var span = document.createElement('span');
		span.id = 'pagenum';
		span.innerHTML = '1. ';
		div3.appendChild( span );

	}

	div3.appendChild( document.createTextNode( htmlspecialchars(test.ques.title) ) );

	divMain.appendChild(div3);

		div3 = document.createElement( 'div' );
		div3.className = 'variables';
		div3.id = 'variables_'+test_id;
		if( test.ques.answerSet == 1 ) {
			if( test.answer != null ) {
				for( var i=0 ; i<test.answer.length ; i++ ){

					label = document.createElement('label');
					if( isIE ){

						var type;
						if( test.ques.mselect == 1 )
							type = 'checkbox';
						else type = 'radio';
						input = document.createElement("<input name='ans"+test_id+"' id='ans"+test_id+i+"' type='"+type+"' value='"+test.answer[i].num+"'/>");

					}else{
						input = document.createElement('input');
						if( test.ques.mselect == 1 )
							input.type = 'checkbox';
						else input.type = 'radio';

						input.name = 'ans'+test_id;
						input.id = 'ans'+test_id+i;
						input.value = test.answer[i].num;
					}


					label.appendChild(input);

					if( test.ques.text == 1 ) {
						label.appendChild( document.createTextNode( htmlspecialchars(test.answer[i].text) ) );
					}//end if

					if( test.ques.pic == 1 ){

						var img = document.createElement('img');
						img.src = test.answer[i].pic;
						label.appendChild(img);
					}

					div3.appendChild(label);
					div3.appendChild( document.createElement('br') );

				}//end for
			}//end if
		}//end if

		if( test.ques.answerFree == 1 ){

			label = document.createElement('label');
			if( test.ques.answerSet == 1 ) {
				label.appendChild( document.createTextNode( test.lang.otherAnswer ) );
			} else {
				label.appendChild( document.createTextNode( 'Ваш ответ' ) );
			}

			if( isIE ){
				input = document.createElement("<input name='ans"+test_id+"' id='ans"+test_id+"0' type='text' value='' />");
			} else {
				input = document.createElement('input');
				input.name = 'ans'+test_id;
				input.id = 'ans'+test_id+'0';
			}

			test.answer='1';
			label.appendChild(input);
			div3.appendChild( label );
		}

	if( (test.answerFree == 0)&&((test.answerSet == 0)||(test.answerSet == 1))&&( test.answer == null ) )
		div3.appendChild( document.createTextNode( test.lang.notAnswers ) );

	divMain.appendChild(div3);

	/*Устанавливаем рекламу*/
	divAds.appendChild( document.createTextNode('') );//Вставляем рекламу


	/*Устанавливаем строку навигации*/
	var button = document.createElement( 'button' );
	/*button.setAttribute( 'type', 'button' );
	if( isIE )
		button.setAttribute( 'onclick', function(){ alert( test.lang.funcInDevelop ); } );
	else
		button.onclick = function(){ alert( test.lang.funcInDevelop ); };
	button.appendChild( document.createTextNode( test.lang.remember ) );
	div2.appendChild(button);

	button = document.createElement('button');*/
	button.setAttribute( 'type', 'button' );
	if( isIE&&!isIE8 )
		button.setAttribute( 'onclick', function(){nextQuestion();} );
	else
		button.onclick = function(){nextQuestion();};
	button.innerHTML = test.lang.next;
	divNav.appendChild(button);
	
	if( test.decor.shownum == '1' ){

		var span = document.createElement('span');
		span.id = 'pagein';
		span.appendChild(document.createTextNode( ' ( ' ));
		divNav.appendChild( span );
		
		var span2 = document.createElement('span');
		span2.id = 'actualQues';
		span2.appendChild(document.createTextNode('1'));
		
		span.appendChild(span2);
		span.appendChild(document.createTextNode( test.lang.from+test.quescount+' )' ));

	}
}

function nextQuestion(){

	var answer = '';
	var elemAnswer;
	if( test.answer != null )
	for( var i = 0 ; i < test.answer.length ; i++ ){
            elemAnswer = document.getElementById( 'ans'+test_id+i );
		if( elemAnswer.type != 'text' ) {
			if( elemAnswer.checked ){

				if( test.ques.mselect == 1 ){

					answer += elemAnswer.value+',';

				}else{

					answer = elemAnswer.value;
				}
			}
		} else {
				if( test.ques.mselect == 1 ){

					answer += '|'+elemAnswer.value+',';

				}else{
					answer = elemAnswer.value;
				}
		}
                //alert(answer);
	}
	if( test.weightChar.length == 0 ) test.weightChar = {};
	var char = test.weightChar;

	var charstring = '{';
	for(var key in char) {
		if( charstring.length > 1 ) charstring +=',';
		charstring += '"'+key+'":"'+char[key]+'"';
	}

	charstring += '}';
	//alert(charstring);
	if( answer != '' ){
		document.getElementById('loading_'+test_id).style.display = 'inline';
		sendScriptRequest( homeUrl+"api/nextquestion", 'id='+test_id+'&qnum='+test.ques.order+'&weight='+test.weight+'&weightChar='+charstring+'&answer='+answer+'&uid='+user_id , validateResponse , ["test123"]);
		//loadXMLDoc( 'POST' , 'http://testing-all.ru/api/nextquestion' , 'id='+test_id+'&qnum='+test.ques.order+'&weight='+test.weight+'&weightChar='+charstring+'&answer='+answer , validateResponse );
		delete( answer );
	}else alert(test.lang.notSelect);
}

function validateResponse(){

	//if (req.readyState == 4 && req.status == 200){
		document.getElementById('loading_'+test_id).style.display = 'none';
                
		var response = eval("(" + responseText + ")");

		if( response.type =='question' )
			setNewQuestion( response  );
		else if( response.type =='result' )
			setResult( response );
	//}
}

function setNewQuestion( ques ){

	cleanNode( document.getElementById('question_'+test_id) );
	if( test.decor.shownum == '1' ){
		var qnum = ques.ques.qnum+'. ';
		cleanNode(document.getElementById('actualQues'));
		document.getElementById('actualQues').innerHTML = ques.ques.qnum;
	}else
		var qnum = '';
	document.getElementById('question_'+test_id).appendChild( document.createTextNode( qnum+htmlspecialchars(ques.ques.title) ) );

	cleanNode( document.getElementById( 'variables_'+test_id ) );
        //alert( parseInt( ques.ques.answerSet ) );
        if( parseInt( ques.ques.answerSet ) == 1 ){

            for( var i=0 ; i<ques.answer.length ; i++ ){

                    label = document.createElement('label');

                    if( isIE ){

                            var type;
                            if( ques.ques.mselect == 1 )
                                    type = 'checkbox';
                            else type = 'radio';
                            input = document.createElement("<input name='ans"+test_id+"' id='ans"+test_id+i+"' type='"+type+"' value='"+ques.answer[i].num+"'/>");

                    }else{
                            input = document.createElement('input');
                            if( ques.ques.mselect == 1 )
                                    input.type = 'checkbox';
                            else input.type = 'radio';

                            input.name = 'ans'+test_id;
                            input.id = 'ans'+test_id+i;
                            input.value = ques.answer[i].num;
                    }

                    label.appendChild(input);

                    if( ques.ques.text == 1 )
                            label.appendChild( document.createTextNode( htmlspecialchars(ques.answer[i].text) ) );

                    if( ques.ques.pic == 1 ){

                            var img = document.createElement('img');
                            img.src = ques.answer[i].pic;
                            label.appendChild(img);
                    }

                    document.getElementById( 'variables_'+test_id ).appendChild(label);
                    document.getElementById( 'variables_'+test_id ).appendChild( document.createElement('br') );

            }

            test.answer = ques.answer;
        }
        
        if( parseInt( ques.ques.answerFree ) == 1 ){

            label = document.createElement('label');
            if( ques.ques.answerSet == 1 ) {
                label.appendChild( document.createTextNode( test.lang.otherAnswer ) );
            } else {
                label.appendChild( document.createTextNode( 'Ваш ответ' ) );
            }

            if( isIE ){
                input = document.createElement("<input name='ans"+test_id+"' id='ans"+test_id+"0' type='text' value='' />");
            } else {
		input = document.createElement('input');
		input.name = 'ans'+test_id;
		input.id = 'ans'+test_id+'0';
            }

            test.answer='1';
            label.appendChild(input);
            document.getElementById( 'variables_'+test_id ).appendChild( label );
        }

	/*Обновляем номер вопроса, ответы, вес, и колчество веса*/
	
	test.weight = ques.weight;
	test.weightChar = ques.weightChar;
	test.ques.order = ques.ques.order;
}

function getResultCode(){

	document.getElementById('code_'+test_id).style.display = 'block';

}

function setResult( result ){

	cleanNode( document.getElementById('question_'+test_id) );
	document.getElementById('question_'+test_id).appendChild( document.createTextNode( htmlspecialchars(result.title) ) );

	cleanNode( document.getElementById( 'variables_'+test_id ) );
	document.getElementById( 'variables_'+test_id ).className = 'result';
	
	
	
	if( result.showSum == '1' ){

		document.getElementById( 'variables_'+test_id ).appendChild( document.createTextNode( test.lang.youHave+result.weight+test.lang.balls ) );
	}
	
	if( result.typePic == '1' ){

		var img = document.createElement('img');
		img.src = result.pic;
		document.getElementById( 'variables_'+test_id ).appendChild( img );
	}

	if( result.typeText == '1' ){

		document.getElementById( 'variables_'+test_id ).appendChild( document.createElement( 'br' ) );
		document.getElementById( 'variables_'+test_id ).appendChild( document.createTextNode( htmlspecialchars(result.text) ) );
	}

	
	
	if( result.showWeight == '1' ){
		if( result.showWeightType == 'list' ){
			
		}else if( result.showWeightType == 'pie' ){
			
			document.getElementById( 'variables_'+test_id ).appendChild( document.createElement( 'br' ) );
			
			var img = document.createElement('img');
			img.src = result.graffUrl;
			document.getElementById( 'variables_'+test_id ).appendChild( img );
		}
		
	}
	
	if( result.showScale == '1' ){
		
		if( result.scales.length > 0 ){
		
			for( var i = 0 ; i< result.scales.length ; i++ ){
				
				document.getElementById( 'variables_'+test_id ).appendChild( document.createElement( 'br' ) );
				b = document.createElement('b');
				b.appendChild( document.createTextNode( result.scales[i].title+' : ' ) );
				document.getElementById( 'variables_'+test_id ).appendChild(b);
				document.getElementById( 'variables_'+test_id ).appendChild( document.createTextNode( result.scales[i].count ) );
				
				document.getElementById( 'variables_'+test_id ).appendChild( document.createElement('br') );
				
				if( (result.scales[i].subject != '')&&( result.scales[i].desc != '' ) ){
					b = document.createElement('b');
					b.appendChild( document.createTextNode( result.scales[i].subject ) );
					document.getElementById( 'variables_'+test_id ).appendChild(b);
					
					document.getElementById( 'variables_'+test_id ).appendChild( document.createElement('br') );
					
					document.getElementById( 'variables_'+test_id ).appendChild( document.createTextNode( result.scales[i].desc ) );
				}else{
					document.getElementById( 'variables_'+test_id ).appendChild( document.createTextNode( test.lang.notdesc ) );
				}
				document.getElementById( 'variables_'+test_id ).appendChild( document.createElement('br') );
			}
		}
	}

	
	
	

	cleanNode( document.getElementById('nav_'+test_id) );

	var button = document.createElement('button');
	button.setAttribute( 'type' , 'button' );
	if(isIE&&!isIE8)
		button.setAttribute('onclick' , function(){getResultCode();} );
	else button.onclick = function(){getResultCode();};
	button.appendChild( document.createTextNode( test.lang.codeBlog ) );

	document.getElementById( 'nav_'+test_id ).appendChild( button );
	document.getElementById( 'nav_'+test_id ).appendChild( document.createElement( 'br' ) );
	document.getElementById( 'nav_'+test_id ).appendChild( document.createElement( 'br' ) );

	var textarea = document.createElement( 'textarea' );
	textarea.style.width = '90%';
	textarea.style.height = '70px';
	textarea.id = 'code_'+test_id;
	textarea.style.display = 'none';

	var resultText='';

	if( result.typeText == '1' ){
		resultText += htmlspecialchars(result.text);
	}
	if( result.typePic == '1' ){
		resultText += "<img src='"+result.pic+"'/>";
	}

	if( (test.decor.url == '')||( test.decor.url == 'http://' ) )
		test.decor.url = homeUrl;
	//textarea.innerHTML = "<div style='width:200px;border:1px solid #CCC'><span><b>"+htmlspecialchars(result.title)+"</b></span><br/><span>"+resultText+"</span><br><div style='width:100%'><a href='"+test.decor.url+"'>"+test.decor.url+"</a></div><br/><div style='width:100%;font-size: 8px;text-align:right'><a href='http://testing-all.ru'>Сделано на Тестируем все!</a></div></div>";
	//textarea.innerHTML = "<center><div style='width:400px;border:1px solid #CCC; font-size: 1em;'><div style=\"background: #AAAAFF; padding: 5px 10px; color:#0000FF\">"+test.testTitle+"</div><div style=\"font-size: 1.2em; padding: 3px; background: #EEE;margin: 3px;\"><b>"+htmlspecialchars(result.title)+"</b></div><p>"+resultText+"</p><form action=\""+location.href+"\" method=\"POST\"><input type=\"submit\" value=\"Пройти тест\" /></form><img src='"+homeUrl+"api/image?uid="+user_id+"&tid="+test_id+"&type=code' style='display:none;'/><div style=\"background: #BBBBFF; padding: 3px 3px; font-size:0.8em\"><a href=\""+test.decor.url+"\" style=\"color: #555555;\">"+test.decor.url+"</a></div><span style=\"font-size: 0.75em;\">Создано на <a href=\"http://testing-all.ru\" style=\"text-decoration: none;\">Тестируем все!</a></span></div></center>";
	if( !isOpera )
		textarea.innerHTML = "<center><div style='width:400px;border:1px solid #CCC; font-size: 16px;background: #FFFFFF;'><div style='background: #AAAAFF; padding: 5px 10px; color:#0000FF;font-weight:bold'>"+test.testTitle+"</div><div style='font-size: 20px; padding: 3px; background: #EEE;margin: 3px;'><b>"+htmlspecialchars(result.title)+"</b></div><p>"+resultText+"</p><a href='"+location.href+"' style='height:20px;font-weight:bold;text-decoration:none;'>Пройти тест</a><br/><br/><img src='"+homeUrl+"api/image?uid="+user_id+"&tid="+test_id+"&type=code' style='display:none;'/><div style='background: #BBBBFF; padding: 3px 3px; font-size:11px'><a href='"+test.decor.url+"' style='color: #555555;'>"+test.decor.url+"</a></div><span style='font-size: 12px;'>Создано на <a href='http://testing-all.ru' style='text-decoration: none;font-weight:bold'><font color='#275D9B'>Тестируем</font> <font color='#9BBD1B'>ВСЕ!</font></a></span></div></center>";
	else
		textarea.value = "<center><div style='width:400px;border:1px solid #CCC; font-size: 16px;background: #FFFFFF;'><div style='background: #AAAAFF; padding: 5px 10px; color:#0000FF;font-weight:bold'>"+test.testTitle+"</div><div style='font-size: 20px; padding: 3px; background: #EEE;margin: 3px;'><b>"+htmlspecialchars(result.title)+"</b></div><p>"+resultText+"</p><a href='"+location.href+"' style='height:20px;font-weight:bold;text-decoration:none;'>Пройти тест</a><br/><br/><img src='"+homeUrl+"api/image?uid="+user_id+"&tid="+test_id+"&type=code' style='display:none;'/><div style='background: #BBBBFF; padding: 3px 3px; font-size:11px'><a href='"+test.decor.url+"' style='color: #555555;'>"+test.decor.url+"</a></div><span style='font-size: 12px;'>Создано на <a href='http://testing-all.ru' style='text-decoration: none;font-weight:bold'><font color='#275D9B'>Тестируем</font> <font color='#9BBD1B'>ВСЕ!</font></a></span></div></center>";
	document.getElementById( 'nav_'+test_id ).appendChild( textarea );
}

/*Реализуем кроссдоменный AJAX*/
function sendScriptRequest(url, httpParams, callback, callbackArgsArray) {
	var currentScript = document.createElement("SCRIPT");
	if (httpParams)
		httpParams="?rand=" + Math.random() + "&" + httpParams;
	else
		httpParams="?rand=" + Math.random();
	currentScript.ajax_readyState = false;
	currentScript.onload = scriptCallback(currentScript, callback, callbackArgsArray);
	currentScript.onreadystatechange = scriptCallback(currentScript, callback, callbackArgsArray);
	currentScript.src = url + httpParams;
	//alert(currentScript.src);
	document.getElementsByTagName("script")[0].parentNode.appendChild(currentScript);
}
function scriptCallback(currentScript, callback, callbackArgsArray){
	return function() {
		if (currentScript.ajax_readyState)
			return;
		if (! currentScript.readyState || currentScript.readyState == "loaded" || currentScript.readyState == "complete") {

			currentScript.ajax_readyState = true;
			callback.apply(currentScript, callbackArgsArray)
			currentScript.parentNode.removeChild(currentScript);
		}
	};
}
/*END*/

/*Преобразовываем обратно кавычки*/
function htmlspecialchars(text)
{
   var chars = Array("&amp;", "&lt;", "&gt;", '&quot;', "'");
   var replacements = Array("&", "<", ">", '"', "'");
   for (var i=0; i<chars.length; i++)
   {
       var re = new RegExp(chars[i], "gi");
       if(re.test(text))
       {
           text = text.replace(re, replacements[i]);
       }
   }
   return text;
}

function mtRand(min, max)
{
    var range = max - min + 1;
    var n = Math.floor(Math.random() * range) + min;
    return n;
}

function mkUniId(len)
{
    var len=len?len:14;
    var pass = '';
    var rnd = 0;
    var c = '';
    for (i = 0; i < len; i++) {
        rnd = mtRand(0, 2); // Латиница или цифры
        if (rnd == 0) {
            c = String.fromCharCode(mtRand(48, 57));
        }
        if (rnd == 1) {
            c = String.fromCharCode(mtRand(65, 90));
        }
        if (rnd == 2) {
            c = String.fromCharCode(mtRand(97, 122));
        }
        pass += c;
    }
    return pass;
}

