

// Variables
var survey_answer_id = "";
var survey_workup_id = "";
var survey_ajax_url = "/wp-content/plugins/wp-survey/survey.php";
var survey = new sack(survey_ajax_url);
var s_id = 2;

var splitdate = 0;

var go, show, timeLimit;
var ms = 0;
var init = 0;
var timerID = null;
marknew = 0;
markold= 0;
var yav = 0;

function write_object(embedded_object)
{
	document.write(embedded_object);
	document.write('\n');
}

function survey_message () {
	document.getElementById('survey-message').style.display = 'none';
}

function hide_and_show (hide, show) {	var hide, show;
	if (hide !== 'none') {		document.getElementById(hide).style.display = 'none';
	}
	if (show !== 'none') {
		document.getElementById(show).style.display = 'block';
	}
}


// Function: When User Vote For Survey
function survey_vote() {
    var a, out;
    var tmVal="";
		survey_form = document.getElementById('surveys_form');
		survey_answer_id = "";
    out=1;
    var j = 1;
		while (eval("survey_form.surveyq_" + j)){
			a=0;
			survey_answer = eval("survey_form.surveyq_" + j);
			if(survey_answer.length != null) {
				for(i = 0; i < survey_answer.length; i++) {
					if (survey_answer[i].checked) {
							var tmFld = document.getElementById(j + "tm");
							tmVal += (tmFld) ? survey_answer[i].value+"::"+tmFld.value+"," : "";
							survey_answer_id = survey_answer_id + survey_answer[i].value + ",";
							a = 1;
					}
	    	}
			}
			if (!a) {
				document.getElementById('surveyqs_' + j).className = "alert";
				out = 0;
			}
			else {
				if (document.getElementById('surveyqs_' + j).className == "alert") {
					document.getElementById('surveyqs_' + j).className = "";
				}
			}
		j++;
   }
   srids = [survey_answer_id, tmVal];

   // IF USER COMPLETE OR TIME EXCEED
   if (out || (!out && timeLimit > 0 && ms < 1)) {
   	tmrOn(); //STOP TMR
  	return srids;
   }

   // IF NOT COMPLETE BUT YET HAVE TIME
   if (!out && timeLimit > 0 && ms > 1000) {
   	tmrOn(); //STOP TMR
   	way = confirm ("Вы ответили не на все вопросы. \nУ вас еще осталось времени: " + fTime(ms) + ". \nЕсли вы хотите продолжить отвечать на вопросы теста, нажмите \"ОК\". \nЕсли хотите завершить тест, нажмите \"Cancel\".");
   	if (way) {
   		tmrOn(); // START TMR
   		return false;
   	}
   	else
   		return srids;
   }

  // IF NOT COMPLETE AND TIMER DIRECTION NORMAL
   tmrOn(); //STOP TMR
   alert ("Вы ответили не на все вопросы. \nПожалуйста, ответьте на вопросы, отмеченные звездочкой.\nПосле этого снова нажмите \"Показать результаты!\"")
   tmrOn(); // START TMR
   return false;
}



// Function: WHEN USER USE WORKUP SURVEY
function workup_survey () {
    var survey_workup_id = uid = uids = ud = uds = "";
		var u = err= 0;
		var i;

    var sid = parseInt(document.getElementById('sid').value);

    while (document.getElementById(u + 'uid')) {
    	uid = parseInt(document.getElementById(u + 'uid').value);
    	uids = uids + uid + ",";

    	ud = document.getElementById(u + 'dt').value;
    	uds = uds + ud + ",";

			i = 1;
			while (document.getElementById(u + 'a' + i)){
				ans = parseInt(document.getElementById(u + 'a' + i).value);
	      check = 0;
	      if (ans > 0 && ans < 15) {
		      survey_workup_id = survey_workup_id  + i + "a" + ans + ",";
		      check = 1;
	      }
	      if (!check) {
	      	document.getElementById(u + 'q' + i).className = "center alert";
	      	err = 1;
		    }
		    else {
			    if (document.getElementById(u + 'q' + i).className == "center alert") {
			    	document.getElementById(u + 'q' + i).className = "center";
			    }
		    }
		  	i++;
	   	}
	   	survey_workup_id = survey_workup_id.slice(0, -1);
	   	survey_workup_id = survey_workup_id + ";";
	   	u++;
	  }
    uids = uids.slice(0, -1);
    uds = uds.slice(0, -1);

		if (err) {
			alert ("Вы допустили ошибку!");
      return false;
		}

		survey_workup_id = survey_workup_id.slice(0, -1);
		rids = [sid, uids, survey_workup_id, uds];

		//alert (rids[0] + " и еще " + rids[1] + " и еще " + rids[2] + " и еще " + rids[3]);
		return rids;
		//return false;

}

function workup_process () {

	  if (rids = workup_survey ()) {
	 		change_button ("Результаты сохраняются");

    	grid = document.getElementById('grid').value;
	 		survey.reset();
			survey.setVar("work", true);
			survey.setVar("surveyq_id", rids[0]);
			survey.setVar("uids", rids[1]);
			survey.setVar("surveya_ids_str", rids[2]);
			survey.setVar("u_dates", rids[3]);
			survey.setVar("grid", grid);
			survey.method = 'POST';
			survey.execute = true;
			survey.runResponse();
			survey.runAJAX();
		}
}


function close_survey(){	document.getElementById('survey-q-list').style.display = 'none';
	}

function change_button (some_text) {	document.getElementById('button_show_results').value = some_text + "...";
	document.getElementById('button_show_results').disabled = true;
}


function confirmSubmit()
{
	var agree=confirm("Вы действительно хотите продолжить?");
	if (agree) {
    return true;
		}
	else
		return false;
}

function process_survey () {
    srids = survey_vote ();
	  if (srids) {
	 		change_button ("Результаты сохраняются");

      survey_id = document.getElementById('survey_id').value;
      surveyrid = document.getElementById('surveyr_id').value;
	 		survey.reset();
			survey.setVar("s_vote", true);
			survey.setVar("surveya_ids_str", srids[0]);
			survey.setVar("surveyq_id", survey_id);
			survey.setVar("surveyr_id", surveyrid);
			survey.setVar("srtm", srids[1]);
			survey.method = 'POST';
			survey.execute = true;
			survey.runResponse();
			survey.runAJAX();
		}
}


function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

function validate(form_id,email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   var address = document.forms[form_id].elements[email].value;
   if (address.length > 0) {
	   if(reg.test(address) == false) {
	      alert('Неверный email адрес!');
	      return false;
	   }
   }

 	return true;
}




// FORMATING TIME MILLISEC TO HUMAN

function two(x) {
	return ((x>9)?"":"0")+x;
}

function three(x) {
	return ((x>99)?"":"0")+((x>9)?"":"0")+x;
}

function fTime(mls) {
  var t ='';
	var sec = Math.floor(mls/1000);
	mls = mls % 1000;
	//t = ":" + three(mls);

	var min = Math.floor(sec/60);
	sec = sec % 60;
	t = two(sec) + t;

	var hr = Math.floor(min/60);
	min = min % 60;
	t = two(min) + ":" + t;

	var day = Math.floor(hr/60);
	hr = hr % 60;
	//t = two(hr) + ":" + t;
	//t = day + ":" +  t;

	return t;
}

function fixupSlave (obj) {
	if (obj.childNodes) {
		for (var i = 0; i < obj.childNodes.length; ++i) {
			var cobj = obj.childNodes[i];
			if (cobj.tagName == 'INPUT' || cobj.tagName == 'SELECT')
				cobj.disabled = true;
			fixupSlave (cobj);
		}
	}
}


function tmrOn () {
	if (!init) {
 		init = 1;
		tLimitFld = document.getElementById("timeLimit");
		timeLimit = (tLimitFld)? tLimitFld.value : 0;
		go = (timeLimit > 0) ? 0 : 1;
		showFld = document.getElementById("showTm");
		show = (showFld) ? 1 : 0;

		then = new Date();
		markold = then.getTime();

		if (go)
			then.setTime(then.getTime() - ms);
		else {
			ms = (!ms) ? timeLimit*1000 : ms;
			then.setTime(then.getTime() + ms);
		}
	 	tmr();
 	}
 	else {
 		init = 0;
 		clearTimeout(timerID);
 	}
}

function tmr() {
	if (init) {
		now = new Date();
	  // normal direction
	  if (go) {
	  	ms = now.getTime() - then.getTime();
	  }
	  else {
	  	ms = then.getTime() - now.getTime();
	  	if (ms < 1) {
    		ms = 0;
	  		// action if time left
	  		var tstFrm = document.getElementById('surveys_form');
	  		fixupSlave(tstFrm);
	  		alert ("Время, отведенное на выполнение теста, истекло.\nНажмите \"ОК\", чтобы увидеть результаты.");
	  		process_survey ();

	  	}
	  }
	  if (show) {
	  	window.status = (go) ? "Прошло времени: " + fTime(ms) : "Осталось времени: " + fTime(ms);
	  	//document.stpw.time.value = fTime(ms);
	  }
	  timerID = setTimeout("tmr();", 1);
	}
}

function tmrSplit() {
	splitdate = new Date();
	marknew = splitdate.getTime() - markold;
	markold = splitdate;
}

function tmForAnswer (ansId) {

  timeFld = document.getElementById (ansId+'tm');
  if (!timeFld) {
    element = document.createElement("input");
    element.setAttribute("id", ansId+'tm');
    element.setAttribute("type", "hidden");
    element.setAttribute("value", marknew);
		surveys_form.appendChild(element);
	}
	else {
		document.getElementById(ansId+'tm').value = parseInt(timeFld.value) + marknew;
	}
}


function stopTimer (yav) {
    if (!yav) { return false; }
		tmrSplit();
		document.getElementById('tmr_fld').value =  marknew;
		return true;

}


function itemChanged (e) {
	e = e || event;
	var obj = e.target || e.srcElement;
	var switcher = e.type + '/' + obj.tagName +
						(obj.tagName == 'INPUT' ? '/' + obj.type : '');
	switch (switcher) {
	case 'click/INPUT/radio':
		tmrSplit();
		tmForAnswer (parseInt(obj.id));
		break;
	}
	return true;
}


