// $Revision: 5108 $

//var IDExercise = 0;
var BOpened = false;

// stop();

function SetWindowOpened(bVal)
{          
  BOpened = bVal;
}
function GetWindowOpened()
{
  return BOpened;
}

var siteUserList = {
  enable: function()
  {
    userQueueIntervalId = setInterval(updatePage, 10000);
  },
  
  disable: function()
  {
    clearInterval(userQueueIntervalId);
  }
};

// debug constants...
var IsDebug = false;  
var IsModeShowResult = true;
//

var IDUserCite = "IDCite";
var IDUserInput = "IDUserInput";
var IDUserInput2 = "IDUserInput2";
var CaretPos = 0;
var ExerciseText = "";
var ExerciseText2 = "";
var ReplacedExerciseText = "";
var keyboard = new TKeyboardInput(Type);
var bSymbolTyped = false;

function TimerSymbolTyped()
{
  bSymbolTyped = true;
}

var AfterErrorCounter = new TAfterErrorCounter("keyboardPlace", "AfterErrorCounter");

var CurTime = 0;
var LastKeyTime = 0;
var TypingTimeout = 1000;

//var CloseRedoObj = new TCloseRedoObj("CloseRedoObj", "Close", "ClickBegExercise", "Закрыть", "К началу");
var CloseRedoObjRes = new TCloseRedoObj("CloseRedoObjRes", "CloseOrGoToPage", "RepeatExercise", "Далее", "Повторить");

var IDFingerZones = "IDFingerZones";
var IDFingerZonesTd = "IDFingerZonesTd"; 
var FingerZonesObj = new TFingerZones(IDFingerZones);

var UserName = "";
var UserCaption = new TUserCaption(UserName);

var TaskNum = "10.2";
var TaskCaption = new TTaskCaption(TaskNum);

var Miksanatik = new TMiksanatik();
var IDErrorSpan = "IDErrorSpan";
var ErrorObj = new TError(IDErrorSpan);
var Speed = new TSpeed();
var Time = new TTime();
var ResultPanel = new TResultPanel();

var IDCiteInputTable = 'CiteInputTable';
var IDCloseRedoFingersTable = 'CloseRedoFingersTable';

var InputField;
var InputField2;

//var flashType = new TFlashType();
//var FlashKeyboard = new TFlashKeyboard();
var FlashError = new TFlashError();

var WindowTop = 0;
var WindowLeft = 0;

var BScreenResolutionLowRegime = false;
var BHighXYRatio = false;

//var CaptionArrow = new TArrow("IDCaptionArrow0", "IDArrowDelimiter",0);

var ResultPage = new TResultPage(/* "IDResultPage" */"ResultContent", "ExerciseContent");
var ResultImg = new TResultImg("IDResultImg", Environment.getResourceDirectory() + "img/Result/", ".jpg");
var RESULT_RATING_TABLE = 0;
var RESULT_LITERACY = 1;
var RESULT_MIKSANATIK = 2;
var RESULT_NONE = 3;

function isIe()
{
  return (navigator.appName == "Microsoft Internet Explorer");
}

function isMacOS()
{
  return (navigator.userAgent.indexOf("Macintosh") != -1);
}

function isIe6()
{
  var appVersion = navigator.appVersion;              
  
  var browser = "MSIE";
  
  if(appVersion.indexOf(browser) != -1)
  {
    var i = appVersion.indexOf(browser) + browser.length;
    
    while(isNaN(parseInt(appVersion.charAt(i)))) i++;
    
    for(var sd = ""; !isNaN(parseInt(appVersion.charAt(i))); i++)
      sd += appVersion.charAt(i);
      
    var d = parseInt(sd);
    
    if(d == 6) return true;
  }
  
  return false;
}

function isOpera()
{
  if(navigator.appName == "Opera")
  {
    return true;
  }
  return false;
}

function isOperaLess10()
{
  var appName = navigator.appName;
  var appVersion = navigator.appVersion;
  var nVersion = parseInt(appVersion.substring(0, appVersion.indexOf('.')));
  
  if(appName == "Opera" && nVersion < 10)
    return true;
  
  return false;    
}

function getScrollY() {

       if( typeof( window.pageYOffset ) == 'number' ) {
               // Netscape compliant
               return window.pageYOffset;
       } else if( document.body && (document.body.scrollTop ) ) {
               // DOM compliant
               return document.body.scrollTop;
       } else if( document.documentElement && (document.documentElement.scrollTop ) ) {
               // IE6 Strict
               return document.documentElement.scrollTop;
       }
       return 0;
}

exerciseUserStatus = {
  numErrors: 0,
  getNumErrors: function()
  {
    return this.numErrors;
  },
  setNumErrors: function(n)
  {
    this.numErrors = n; 
  }
};

// exercise text get functions
function GetCaretProgress()
{
  return 100.0*(CaretPos+1)/ExerciseText.length;
}
function ExNumOfLines()
{
  // count num of lines
  var begInd, i;
  
  for(i = 0, begInd = ExerciseText.indexOf('\n', begInd) + 1; begInd != 0; i++, begInd = ExerciseText.indexOf('\n', begInd) + 1);
         
  return i;  
}
//

var BUserLogin = false;
function IsUserLogin()
{
  return (ExerciseInfo.UserName != "" || SpeedTestInfo.UserName != "");
}

function InitForScreenResolution()
{
// current variant commented... this is only a variant for low resolution

  if(Environment.IsOnline())
  {
    BScreenResolutionLowRegime = ( screen.height < 1024 );
  }
  else
  {
    BScreenResolutionLowRegime = true;
  }
  BHighXYRatio = (screen.height * 1.6 <= screen.width);
  if(!BScreenResolutionLowRegime)
  {
    WindowTop = 50;
    ResultPage.nPageUsers = 8;
    
    WindowLeft = (screen.width - 1000) / 2;
    if(WindowLeft < 0)  WindowLeft = 10;    
    
  }
  else
  {
    WindowTop = 5;
    WindowLeft = 5;
    ResultPage.nPageUsers = 5;
  }

// low resoltion (delete later)
//


  if(BScreenResolutionLowRegime)
  {
    ResultSpeedTestInfo.SetNumFields(5);
  }
  else
  {
    ResultSpeedTestInfo.SetNumFields(8);
  }
}


var BAutoTyping = false;

function GoToLastAvailable()
{
   document.location.href = "/study/10/#10.1";
}

function GoToLessonList(ref)
{
   document.location.href = "/study/" + commonInfo.CourseID + "/#"+ExerciseInfo.LessonNumber;
}

function CloseOrGoToPage()
{	
  if(GetExType() == 32)
  {
    UnsetResultPageClose();
    return;
  }

  var bCloseWindow = true;

  if(ResultInfo.RefToNext != "")
  {
    document.location.href = ResultInfo.RefToNext;
    return;  
    // bCloseWindow = false;
  }
  if(ResultInfo.IDNext != "")
  {
    lessonChanger.exercise.activate(ResultInfo.IDNext);
  }
  if(ResultInfo.IDRemove != "")
  {
    var obj = document.getElementById("start"+ResultInfo.IDRemove);
    obj.style.display = "none";
  }
  if(ResultInfo.IDAdd != "")
  {
    var obj = document.getElementById("start"+ResultInfo.IDAdd);
    var objText = document.getElementById("repeat"+ResultInfo.IDAdd);
    obj.style.display = "";
    objText.innerHTML = ResultInfo.TextRepeat; 
  }

  if(bCloseWindow)
  {
// alert("bCloseWindow=true");
    UnsetResultPageClose();
    return;
  }

}

// for test grammar exercise
var CorrectWords = new Array();
//

function FillCorrectWords(textCorrect)
{
  var curWord = Array();
  for(var i = 0; i < textCorrect.length; i++)
  {
    if(textCorrect.charAt(i) != ' '  &&  textCorrect.charAt(i) != '\n')  
      curWord += textCorrect.charAt(i);
    else
    {
      CorrectWords.push(curWord);
      curWord = "";
    }  
  }
  // alert(CorrectWords);
}

// global function to change content of fields and panels


// FLASH. The information from flash

var FlashText = "", FlashText2 = "";

// flash event handlers

window.onblur = function()
{
//  flashType.ShowTypeHere();
}
     
//

function IsWindows()
{
  return   navigator.appVersion.indexOf("Windows") != -1;
}   
      
function onTypeFlashLoaded()
{
  var exType = GetExType(); 
  
  soloTypeFlash.hidePleaseWait();
  soloTypeFlash.initialize();
  
  soloTypeFlash.setResourceDirectory(Environment.getResourceDirectory()); 
   
  try
  {
    soloTypeFlash.setCite(CiteInfo.Text);
  }
  catch(e)
  {
    alert("Не установлен FlashPlayer (пройдите по ссылке http://get.adobe.com/flashplayer)");
  }
  
  soloTypeFlash.setCiteAuthor(CiteInfo.Author);
     
  if(exType == 32)
  {
    if(Environment.IsOnline())
    {
      info = SpeedTestInfo;
    }
    else
    {
      if(ExerciseInfo.IsExam)
        info = ExamInfo;
      else
        info = SpeedTestInfo;   
    }    
  }
  else
  {
    info = ExerciseInfo;
  }
  
  if(exType == 7)
  {
    soloTypeFlash.setText1(info.Text);
    soloTypeFlash.setText2(info.Text2);
  }
  else
  {
    soloTypeFlash.setText(info.Text);                                            
  }
         
  soloTypeFlash.setErrorTexts(ErrorsInfo.GetErrors().join('|'));
  
  soloTypeFlash.beginExercise();
  
  var language = commonInfo.getFlashLanguage(); 
  
  soloTypeFlash.setLanguage(language);
  
  if(exType == 32)
  {
    switch(ExerciseInfo.typeExam)
    {
    case 'startExam':
      soloTypeFlash.setTypeTest("startExam");
      break;
    case 'finalExam':
      soloTypeFlash.setTypeTest("endExam");
      break;
    default:
      soloTypeFlash.setTypeTest("speedTest");                                      
    }
    soloTypeFlash.setExerciseType("2");
  }
  else 
    soloTypeFlash.setExerciseType(commonInfo.TypeOfExercise);
  
  soloTypeFlash.setMaxErrors(ExerciseInfo.MaxNumOfMistakes);
  
  soloTypeFlash.setUser(info.UserName);
  
  if(exType != 32)
    soloTypeFlash.setLessonExercise(ExerciseInfo.LessonNumber + "." + ExerciseInfo.ExerciseNumber);
  
  soloTypeFlash.setCourse(courseUtilities.getFlashNameById(commonInfo.CourseID));
  
  with(KeyboardInfo)
  {
    soloTypeFlash.setKeyboardParameters(Layout, bNextKey, bShowChars, bColored);
  }  
  
//  alert("This is message 2: new message");
  
}      

//function reinitSpeedTest()
//{
//  alert("in reinit speed test, SpeedTestInfo.Text='"+SpeedTestInfo.Text+"'");

/*  soloTypeFlash.reset();
    
  soloTypeFlash.setCite("Цитата");
  soloTypeFlash.setCiteAuthor("Автор цитаты");
    
  soloTypeFlash.setText(SpeedTestInfo.Text);*/
  
//  soloTypeFlash.reset();  
  
//}
                   
function fInputLoaded()
{
  // if(bDontExit != true) return;
 
  if(!FlashInput.IsFlashLoaded())
  {  
    setTimeout(fInputLoaded, 500);   
    if(Environment.IsOnline()) FlashInput.GenerateOnloadMessage();
    return;
  }
  
  FlashInput.InitOS();		
  		
  FlashInput.OnFlashLoaded();

  fSetRegime(GetExType());                                                      
}

function keyboardSetVal(listenerParam, val)
{
/*  if(window.flashKeyboard) 
  {
    window.document["flashKeyboard"].SetVariable("listener."+listenerParam, val);
  }
  else
	if(document.flashKeyboard)
  {
    document.flashKeyboard.SetVariable("listener."+listenerParam, val);
  }*/ 
}

function keyboardSetDefaultLayout()
{
  KeyboardInfo.Layout = "0";
//  FlashKeyboard.SetLayout(KeyboardInfo.Layout); 
//  FlashKeyboard.InitLanguage();
}

function flashKeyboardChangeLayout(layout)
{  
  if(IsUserLogin())
  {
    RequestSaveKeyboardParam("layout", layout);
  }
  
//  FlashInput.SetCanType(true);
  
  KeyboardInfo.Layout = layout;
                                          
//  FlashKeyboard.SetLayoutChanged();

  soloTypeFlash.layoutChanged();

}                                   

function flashKeyboardChangeShowNextKey(bShowNextKey)
{
    RequestSaveKeyboardParam("next_key", bShowNextKey);
}
function flashKeyboardChangeColored(bColored)
{
    RequestSaveKeyboardParam("keyboard_colored", bColored);
}
function flashKeyboardChangeShowChars(bShowChars)
{
    RequestSaveKeyboardParam("show_chars", bShowChars);
}


function flashShowAboutLayout()
{
  window.open("/study/");
}

function flashInputLoaded()
{                   
//  FlashInput.SetHighXYRatio(BHighXYRatio);
//  FlashInput.SetFlashLoaded(true);
}

function flashFastError()
{
  ExerciseError(false);
}

function flashError(errorCh, index, sLayError)
{  
  Context.SetError(true);	
	
//  FlashInput.SetCanType(false);
  ExerciseError(IsWrongLayout(errorCh));
  CaretPos = parseInt(index);
}

var NumOfTypedChars = 0;


function IsTypChError(ch)
{
  if(ch == String(null))  return false;
  else
    return true;
}

function flashErrorFix()
{
//  FlashKeyboard.SetBkspMode(false);
}

function flashMiksErrFixed()
{
  CiteField.Restore();
  CiteField.Render();
  CiteField.Update();
}

function flashMiksFixErr()
{
  CiteField.SetErrorText("Исправьте последнюю ошибку!");
  CiteField.RenderError();
}

  function fFinishExercise()
  {
    switch(GetExType())
    {    
    case 0: case 4: case 7: case 8:
      PrepareResult(RESULT_MIKSANATIK);  
      return;
    case 3:
      BAutoTyping = false;
      PrepareResult(RESULT_MIKSANATIK);
      return;       
    case 5:
  // grammar test
      return;
    case 2: case 32:
       PrepareResult(RESULT_NONE);
       return;
    default:
       PrepareResult(RESULT_RATING_TABLE);      
    }
  }  
                                
  function flashFinishExercise(numErrors, numOfTypedChars, time)
  { 
    exerciseUserStatus.setNumErrors(parseInt(numErrors));
    
    NumOfTypedChars = numOfTypedChars;
    Time.SetTime(parseInt(time));  
  
    fFinishExercise();
  }
  
  function fSetRegime(typeOfExercise)
  {
    switch(typeOfExercise)
    {
      case 0: case 2:
//        FlashInput.SetRegime("qerror");
//        FlashInput.SetModeNormal();
        return;
      case 32:
//        FlashInput.SetRegime("speedtest");
//        FlashInput.SetModeNormal();
        return;
      case 1: case 6: case 8:
//        FlashInput.SetRegime("error");
//         FlashInput.SetModeNormal();
        return;
      case 3:
//        FlashInput.SetRegime("autotype");
//        FlashInput.SetModeNormal();
        return;
      case 4:
//        FlashInput.SetRegime("skiperror");
//        FlashInput.SetModeNormal();
        return;
      case 7:
//        FlashInput.SetRegime("qerror");
//        FlashInput.SetModeBottomFragments(); 
        return;
    }
  }

// ...

function IsExFinished()
{
  return  (CaretPos == ExerciseText.length);
}

function GetExType()
{
  return commonInfo.TypeOfExercise;
}

function SetExerciseText(text_, text2_)
{ 
  var text, text2;

  FlashText = text_;
  FlashText2 = text2_;
  ExerciseText = FlashText; 
  
  if(GetExType() != 32)
  {
	if(Environment.IsOnline())
	{
		text = convertSolo9Online2(text_);
		text2 = convertSolo9Online(text2_);
	}
	else
	{
		text = text_;
		text2 = text2_;
	}
  }
  else
  {
    text = text_;   
  }
  switch(GetExType())
  {
  case 5:
    TextFragmentsData.SetBlockingWords(text); // set numbers of words not
												// allowing to type if they are
												// incorrect
    
//    FlashInput.SetText1(text);
//    FlashInput.SetText2(text2);
    
    text = StrDeleteSymbols(text, "«»"); 
    text2 = StrDeleteSymbols(text2, "«»");       
    FillCorrectWords(text2);
    break;
  case 7:
//    FlashInput.SetText1(text);
    text = StrDeleteSymbols(text, "«»"); 
//    FlashInput.SetText2(text2);      
    break;
  default: 
//    FlashInput.SetText(text);
  }
//  FlashInput.BegExercise();
  ExerciseText = text;
  ReplacedExerciseText = StrReplaceAll(ExerciseText, "\n", " ");
}

function SetExerciseNumberCaption(str)
{
  TaskCaption.SetTaskCaption(str);
}

function SetStartExamCaption()
{
  TaskCaption.SetStartExamCaption();
}

function SetFinalExamCaption()
{
  TaskCaption.SetFinalExamCaption();
}

function SetSpeedTestCaption()
{
  TaskCaption.SetSpeedTestCaption();
}

function SetExerciseUser(val)
{
  if(val != "") BUserLogin = true;
  else  BUserLogin = false;
  UserCaption.Set(val);
}

function SetExerciseMaxNumOfMistakes(val)
{
  // IMPORTANT !!! Do not remove this. This is used in SCORM!
  ErrorObj.SetMaxNumOfMistakes(val);
  ErrorObj.Update();
}

function TMouse()
{
  this.X = -1; this.Y = -1;
  this.PrevX = -1; this.PrevY = -1;
  this.GetX = function()
  {
    return this.X;
  }
  this.GetY = function()
  {
    return this.Y;
  }
  
  this.BChangeWndPos = false;
  
  this.Capture = function()
  {
    this.BChangeWndPos = true;
//    FlashInput.ShowTypeHere();
  } 
  this.Release = function()
  {
    this.BChangeWndPos = false;
    soloTypeFlash.killFocus();
  } 
  this.IsCaptured = function()
  {
    return this.BChangeWndPos;
  }
  
}

var Mouse = new TMouse();

function SetExercsiePos(left, top)
{
  var obj = document.getElementById("Exercise");
  obj.style.left = String(left) + "px";
  obj.style.top = String(top) + "px";
}

function MouseMove(e)
{
  if (window.navigator.appName == "Microsoft Internet Explorer") { // grab the
																	// x-y pos.s
																	// if
																	// browser
																	// is IE
    Mouse.X = event.clientX;
    Mouse.Y = event.clientY;
  } else {  // grab the x-y pos.s if browser is NS
    Mouse.X = e.pageX;
    Mouse.Y = e.pageY;
  }
  
  if(Mouse.X < 0)  Mouse.X = 0;
  if(Mouse.Y < 0)  Mouse.Y = 0;
  
  if(Mouse.IsCaptured())
  {
    var shX = Mouse.X - Mouse.PrevX;
    var shY = Mouse.Y - Mouse.PrevY;
    
    var prevX = getPxNumber(windowSys.main.style.left);
    var prevY = getPxNumber(windowSys.main.style.top);
    
    windowSys.main.style.left = String(prevX + shX) + "px";
    windowSys.main.style.top = String(prevY + shY) + "px";
  }
  
  Mouse.PrevX = Mouse.X;
  Mouse.PrevY = Mouse.Y; 
  
  return true;  
}

InitMouse();

function InitMouse()
{
  if(window.navigator.appName != "Microsoft Internet Explorer") document.captureEvents(Event.MOUSEMOVE);
  document.onmousemove = MouseMove;
}

var PrevText = "";
var ReturnSpecChar = ' ';

var DbgTypeCntr = 0;

function TypeDebug()
{
  if(IsDebug == false)  return false;
  
  if(DbgTypeCntr == 2)
  {
    setTimeout("FinishExercise()", 0);  
    ShowResult(RESULT_RATING_TABLE);
  }
  else
  {
    ExerciseStepForward();
    UpdatePanels(); 
  }
  DbgTypeCntr++;
  return true;
}

function PrepareResult(iResult)
{
	
  CaretPos = 0;     
  keyboard.SetTypeBlock(true);
  ResultSpeedTestInfo.Reset();
  
  if(Environment.IsOnline())
  {
    setTimeout("FinishExercise()", 0);
    ShowResult(iResult);
  }
  else
  {   	      
	
	  if(commonInfo.TypeOfExercise == 32)
    {
      if(ExerciseInfo.isExam == false)
	     scormExchange.setSpeedTestFinished(scormUtils.markSpeed.isSpeedTestPassed(exerciseUserStatus.getNumErrors(), Speed.GetTotalSpeed()), Speed.GetTotalSpeed(), exerciseUserStatus.getNumErrors());
	    else
	    {
	     var bFinalExam = (ExerciseInfo.examType == "finalExam");
	    
       scormExchange.setExamFinished(true/*scormUtils.markSpeed.isExamPassed(ErrorObj.GetNumOfMistakes())*/,
          bFinalExam, Speed.GetTotalSpeed(), exerciseUserStatus.getNumErrors()); 
	    }
    }
	  else
    {
      if(ErrorObj.isAllowableMistakes()) scormExchange.setExerciseFinished(ExerciseInfo.ExerciseNumber);
    }
	
	  setTimeout("FinishExercise()", 0);
    ShowResult(iResult);
	
    //_offlineParams.defaultAction();
  }
}

/*function TIntermSpeed()
{
  this.Intervals = new Array(0, 0, 0, 0, 0, 0);
  this.NumOfInt = 0;
  this.BInited = false;
  this.PrevTime = 0;
  this.LastChangeTime = 0;
  this.Mark = function()
  {
    if(this.BInited)
    {
      var curTime = getCurTime();
      var interval = curTime - this.PrevTime;
      if(interval > 2000) interval = 0;
      this.Intervals[this.NumOfInt] = interval;
      this.PrevTime = curTime;
      this.NumOfInt++;
      if(this.NumOfInt > 2)  this.NumOfInt = 0;
    }
    else  
    {
      this.PrevTime = getCurTime();
      this.BInited = true;
    }
  }
  this.Get = function()
  {
    var sumI = 0;
    for(var i = 0, j = 0; i < 6; i++)
    {
      if(this.Intervals[i] != 0)
      {      
        sumI += this.Intervals[i];
        j++;
      }
    }
    
    if(sumI == 0) return 0;
    return Math.floor(j * 60000 / sumI);
  }
  this.Reset = function()
  {
    this.Intervals[0] = 0;
    this.Intervals[1] = 0;
    this.Intervals[2] = 0;
    this.Intervals[3] = 0;
    this.Intervals[4] = 0;
    this.Intervals[5] = 0;
    this.BInited = false;
  }
  this.Init = function()
  {
    this.BInited = true;
  }
  this.IsInited = function()
  {
    return this.BInited;
  }
  this.DoChange = function()
  {
    var curTime = getCurTime();
    if(curTime - this.LastChangeTime > 1000) 
    {
      this.LastChangeTime = curTime;
      return true;
    }
    return false;
  }
}*/
//var IntermSpeed = new TIntermSpeed();

function Type(ch /* not using */)
{
  var keyCode;

  if(BAutoTyping == true  &&
      ch != '') return;   

  if(keyboard.GetTypeBlock()) return; // we can't type...
  
  bSymbolTyped = true;
  
  if(BAutoTyping == false)
  {
    if(navigator.appName == 'Microsoft Internet Explorer')
      keyCode = window.event.keyCode;
    else
    if(navigator.appName == 'Netscape')
      keyCode = ch.which;
    else
      keyCode = window.event.which;
  }  
  
  var key=String.fromCharCode(keyCode);
  
  
  if(keyCode == 27)  
  {
    Close();
    return;
  }
  
  if(keyCode == 16 || keyCode == 17 || keyCode == 18 ||// shift, ctrl, alt
     keyCode == 116 ||
     keyCode == 8) return; // Backspace, Delete
  
  
  if(TypeDebug())  return;    
     
  switch(GetExType())
  {
  /* case 2: /*Exam */
    
    // break;
  case 7:
    
    break;  
    
  case 5:
    if(key == ' '  ||  key == '\r')
    {
      if(InputField2.GetCurWord() != "")
      {
        // test if exercise has finished...
        
        if(TextFragmentsData.IsWordBlocked(InputField2.GetCurNumOfWord()))
        {
          if(InputField2.GetCurWord() != CorrectWords[InputField2.GetCurNumOfWord()]) return;
        }
        
        var numOfWords = InputField.GetNumOfWords();
        
        if(numOfWords == InputField2.GetCurNumOfWord() + 1)
        { 
          var strErrorWords = "";
          var typedWords = new Array();  
          PrepareResult(RESULT_LITERACY);
          ResultPage.SetGrammarResult(CorrectWords, typedWords);
          
          document.getElementById("IDUserTableTd").style.verticalAlign = "top";
          return;
        }
    
        ExerciseStepForward(true);
        UpdatePanels(true);
      }
    }
    else
    { 
      if(TextFragmentsData.IsWordBlocked(InputField2.GetCurNumOfWord()))
      {
        if(key == CorrectWords[InputField2.GetCurNumOfWord()].charAt(InputField2.GetWordSymbolIndex()))
        {
          ExerciseStepForward(false/* complete word */);
        }        
            
        return;
      }
      
      ExerciseStepForward(false/* complete word */);
    }
    
    return;
  case 3:
    if(CaretPos < ExerciseText.length - 1)
    {
      setTimeout("Type('')", 100);
      BAutoTyping = true; 
      ExerciseStepForward();
      UpdatePanels();
    }
    else  
    {
      BAutoTyping = false;
      PrepareResult(RESULT_MIKSANATIK);
    } 
    return;
  case 4:
    if(CaretPos < ExerciseText.length - 1)
    {
      ExerciseStepForward();
      UpdatePanels();
    }
    else  
    {
      PrepareResult(RESULT_MIKSANATIK);
    }  
    return;   
  default: ;
  }        
     
  if(ExerciseText.charAt(CaretPos) == '\n')
  {
    if(keyCode == 13  ||  keyCode == 32)
    {
      if(CaretPos < ExerciseText.length - 1)
      {
        ExerciseStepForward();
        UpdatePanels();
      }
      else
      {
        if(GetExType() == 0  || GetExType() == 7  ||  GetExType() == 8)
          PrepareResult(RESULT_MIKSANATIK); 
        else
        if(GetExType() == 32)
          PrepareResult(RESULT_NONE);
        else 
          PrepareResult(RESULT_RATING_TABLE);    
        return;        
      }     
    }
    else  
    {
      ExerciseError(false);
    }
  }
  else
  {
    if(key == ExerciseText.charAt(CaretPos))
    {
      if(CaretPos < ExerciseText.length - 1)
      {
        ExerciseStepForward();
        UpdatePanels();
      }
      else
      {
        PrepareResult(RESULT_RATING_TABLE);      
        return;        
      }
    }
    else
    {
      switch(GetExType())
      {
        case 8:
//          if(ErrorObj.GetNumOfMistakes() > ErrorObj.GetMaxNumOfMistakes())
//            ErrorObj.SetNumOfMistakes(ErrorObj.GetMaxNumOfMistakes());
                
        break;
        default:;
      }     
      ExerciseError(false);
    }
  }
}

function UpdatePanels(bWordMode)
{
  if(bWordMode == true)
  {
    if(progress > 100)  progress = 100;
  }
}

function IsSymbolCorrect(correctSymbol, enteredSymbol)
{
  return ((correctSymbol == enteredSymbol)  ||  (correctSymbol == '\n'  &&  enteredSymbol == ' '));
}

function DoBuffersMatch()
{
  
}


var IntervalFirstKeyboardKeyID = ""; 
function SetCurKeyboardKey()
{
  clearInterval(IntervalFirstKeyboardKeyID);
//  FlashKeyboard.SetKey(ExerciseText.charAt(CaretPos));
}

function ExerciseInit()
{

//  IntermSpeed.Reset();
  CaretPos = 0;
//  ErrorObj.SetNumOfMistakes(0);
  Speed.SetSpeed(0); 
  
  
  UpdatePrevText(ExerciseText.slice(0, CaretPos));
  
// Spec actions for types of exercise...
  switch(GetExType())
  {
  case 0: case 5: /*case 7:*/
//    ErrorObj.Hide();
    break;
  default: 
//    ErrorObj.Show();
  }       
  
  NumOfTypedChars = 0;
  
  
//  soloTypeFlash.initialize();
    
// init flash here
//  fInputLoaded(); // flash may be initialized now
}



function StrReplaceAll(str, chIn, chOut)
{
  var res = str;
  var res1 = "";
  while(res != res1)
  {
    res1 = res;
    res = res1.replace(chIn, chOut);
  }
    
  return res;
}

var BErrorMovieFinished = false;

function SetFlashErrorDuration()
{
// alert("SetFlashErrorDuration()");
  if(IsKeyboard)  window.document["flashError"].SetVariable("listener.duration", "3000");
}

function SetFlashErrorDuration2()
{
// alert("SetFlashErrorDuration2()");
  if(IsKeyboard)  document.flashError.SetVariable("listener.duration", "3000");
}

function RestoreAfterFastError()
{
// InputField.RestoreCursor();
// InputField2.TrimLastChar();
  keyboard.SetTypeBlock(false);
}

var MessWrongLayout = "Выбрана неверная раскладка клавиатуры!<br>Используйте русскую раскладку.";
var MessWrongLayoutEng = "Выбрана неверная раскладка клавиатуры!<br>Используйте английскую раскладку.";

function GetMessWrongLayout()
{
  if(commonInfo == "4") // English
    return MessWrongLayoutEng;
  else
    return MessWrongLayout;
}

function IsWrongLayout(errorCh)
{
  if(commonInfo.Language == "English")
  {
    var str = "йцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
    for(var i = 0; str.charAt(i) != errorCh && i < str.length; i++);
    if(str.charAt(i) == errorCh)  return true;
    return false;
  }
  else
  {
    var str = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM";
    for(var i = 0; str.charAt(i) != errorCh && i < str.length; i++);
    if(str.charAt(i) == errorCh)  return true;
    return false;
  }
}

function SetCiteErrorText(bWrongLay)
{
  if(bWrongLay)
    CiteField.SetErrorText(GetMessWrongLayout());
  else
    CiteField.SetErrorText(ErrorsInfo.GetError());
}

function UpdateKey()
{
  var ch = ExerciseText.charAt(CaretPos);
  if(ch == '\n') ch = ' ';

  if(IsKeyboard)  
  {
    try{
//      FlashKeyboard.SetKey(ch);
    }
    catch(e)
    {
    }
  }
}

function ExerciseStepForward(bVal)
{
  switch(GetExType())
  {
  case 7:
    CaretPos++;
    
    break;
  case 5:
    if(bVal /* word completed */)
    {
      CaretPos++;
      return;
    }
    else
    {
       return;     
    }
    break;

  default:

    CaretPos++;
  }

  UpdateKey();
  
// next - use bVal not to take in account speed
  if(bVal == undefined || bVal == true)
  {
    iSymbolsTypedOneSecond++;
  }
}

function ExercisePos(pos)
{
  CaretPos = pos;
}

function UpdatePrevText(val)
{
  var typer = document.getElementById("typer");
  PrevText = StrReplaceAll(val, "\n", " "); // store exercise text in typer
}

function GoToBeginningOfExercise()
{    
//  if(FlashInput.BCanType == false) return;     
//  IntermSpeed.Reset();
  
//  CaretPos = 0;
//  FlashInput.BegExercise();
//  FlashInput.ShowTypeHere();
//  ErrorObj.SetNumOfMistakes(0); 
//  ErrorObj.Update();
//  ErrorObj.SetFat(false);
  
//  NumOfTypedChars = 0;
 
//  FlashKeyboard.SetBkspMode(false);
 
// SetCurKeyboardKey();
  
// restore cite field
}

function ShowResult(iResOption)
{
  ResultPage.Set();
  
  switch(iResOption)
  {
    case RESULT_MIKSANATIK:
      ResultPage.ShowMiksanatik();
      break;
    case RESULT_LITERACY:
      ResultPage.ShowGrammarResult();
      break;
    case RESULT_NONE:
      ResultPage.HideMain();
      break;
    default:  
      ResultPage.ShowRatingTable();
  }
}

this.CharsRusCaption = function(num)
{
  if(num >= 6  &&  num < 20)
    return "знаков";

  var end = new Array("ов", "", "а", "а", "а", "ов", "ов", "ов", "ов", "ов");
  
  var sNum = String(num);
  var lastNum = parseInt(sNum.charAt(sNum.length-1));
  return  "знак"+end[lastNum];
}
this.ErrorsRusCaption = function(num)
{
  if(num >= 6  &&  num < 20)
    return "ошибок";

  var end = new Array("ок", "ка", "ки", "ки", "ки", "ок", "ок", "ок", "ок", "ок");
  
  var sNum = String(num);
  var lastNum = parseInt(sNum.charAt(sNum.length-1));
  return  "ошиб"+end[lastNum];
}

function FinishExercise()
{

  keyboard.SetTypeBlock(true); // set type blocking
  
  if(GetExType() == 32)
  {  
	  if(ResultExtPage != "")
    {
      document.location.href = ResultExtPage + "?speed="+Speed.GetTotalSpeed()+"&errors="+exerciseUserStatus.getNumErrors();
      return;
    }  
  
    if(ResultSpeedTestInfo.IsResponseReceived() == false)
    {
      if(ResultSpeedTestInfo.IsRequested() == false)  
      {
          RequestSpeedTestResult(Speed.GetTotalSpeed(), exerciseUserStatus.getNumErrors(), Time.GetTimeSec(), commonInfo.CourseID);
      }
      setTimeout("FinishExercise()", TimeoutAJAX );
      return;
    }   
  }
  else
  {
	
    if(ResultInfo.IsResponseReceived() == false)
    {
      if(ResultInfo.IsRequested() == false)  
      {                 
        RequestResult(ExerciseInfo.SortID, Speed.GetTotalSpeed(), exerciseUserStatus.getNumErrors(), Math.floor( Time.GetTimeSec() ), commonInfo.CourseID);
      }
      setTimeout("FinishExercise()", TimeoutAJAX );
      return;
    }  
  }    
  
  if(TodayResultInfo.IsResponseReceived() == false)
  {
    if(TodayResultInfo.IsRequested() == false)  
    {
      RequestTodayResult();
    }
    setTimeout("FinishExercise()", TimeoutAJAX );
    return;
  }    
  
  ResultSpeedTestInfo.Reset();
  ResultInfo.Reset();
  TodayResultInfo.Reset();
  
  if(GetExType() == 32)
  {
    with(ResultPage)
    {
    	UpdatePanelFullTime();
    }
    var speed_ = Speed.GetTotalSpeed();
    
    var errors_ = exerciseUserStatus.getNumErrors();
    
    ResultPage.SetHeader("Ваш результат: " + String( Math.floor( speed_ ) ) + " " + this.CharsRusCaption(speed_) + " в минуту, " + String(errors_) + " " + this.ErrorsRusCaption(errors_));
    
    with(ResultPage)
    {
    	SetResultMessage(ResultSpeedTestInfo.Text);
    	SetResultPanelDisplay(false);
    }
                
    with(ResultPage)
    {
		SetNumOfTasks(TodayResultInfo.NumOfTasks);
		SetAvarageSpeed(TodayResultInfo.AvarageSpeed);
		SetNumOfSymbolsTyped(TodayResultInfo.SymbolsTyped);
		SetNumOfErrors(TodayResultInfo.NumOfErrors);
    	
    	if(IsUserLogin() || !Environment.IsOnline())  SetSpeedTestRegisterEnterTrDisplay(false);
    	else
    		SetSpeedTestRegisterEnterTrDisplay(true);
    	SetCrit(3);
    
    	SetResultPageContinueRef("Закрыть");
    	PostForm();
    	ExTable.Hide();
    }
  }
  else
  {
	with(ResultPage)
	{
	  SetPanelSpeed(Speed.GetTotalSpeed());
		UpdatePanelFullTime();
		SetPanelNumOfErrors(exerciseUserStatus.getNumErrors());
		SetPanelRating(Math.floor(ResultInfo.Rating * 100) / 100);
		SetHeader(ResultInfo.Header);
		SetResultMessage(ResultInfo.Text);
		SetLessonExercise(ExerciseInfo.LessonNumber, ExerciseInfo.ExerciseNumber);
  
		SetNumOfTasks(TodayResultInfo.NumOfTasks);
		SetAvarageSpeed(TodayResultInfo.AvarageSpeed);
		SetNumOfSymbolsTyped(TodayResultInfo.SymbolsTyped);
		SetNumOfErrors(TodayResultInfo.NumOfErrors);
		
		SetSpeedTestRegisterEnterTrDisplay(false);
		
		SetCrit(3);
		SetExerciseID(ExerciseInfo.ID);
		
		if(Environment.IsOnline())
		{ 
			ExTable.Show();
		}
		ResultPage.elements.showRowResSpeedTable(Environment.IsOnline());
    
	}
    UpdatePage(); // Set curPage here
    
    ResultPage.SetResultPageContinueRef("Продолжить");
  }
    
  ResultPage.ShowResBottomCaptions(true);
}

var SymbolsTyped = new Array(0,0,0);
var iSymbolsTypedOneSecond = 0;


function getCurTime()
{
  var d = new Date();
  return d.getTime();
}

function TimerGetElapse()
{
  var ct = getCurTime();
  var dt = ct - PrevTime;
  PrevTime = ct;
  return dt;
}

var BTimerWasStopped = true;
var PrevTime;

function LeftSideTyping(IDRightSide)
{
  var res = "";
  TableBuilder.ResetT();
  TableBuilder.SetTWidth("100%");
  if(IDRightSide == undefined)
  {
    TableBuilder.SetTHeight("100%");
  }
  else  
  {
    TableBuilder.SetTHeight(document.getElementById(IDRightSide).offsetHeight);
  }
  TableBuilder.SetTID(IDCloseRedoFingersTable);
  res += TableBuilder.BeginTable();
  TableBuilder.ResetT();
  res += TableBuilder.BeginTr();
  TableBuilder.SetTValign("top");
  res += TableBuilder.BeginTd();

//  res += CloseRedoObj.Generate();
  res += TableBuilder.EndTd();
  TableBuilder.ResetT();
  res += TableBuilder.EndTr();
  res += TableBuilder.BeginTr();
  TableBuilder.SetTValign("bottom");
  res += TableBuilder.BeginTd();
  
  res += FingerZonesObj.Generate();

  res += TableBuilder.EndTd();

  res += TableBuilder.EndTr();
  res += TableBuilder.EndTable(); 
  
  return res;
}

function LeftSideError()
{
  var res = "";
  TableBuilder.ResetT();
  
  TableBuilder.ResetT();
  TableBuilder.SetTHeight("100%");
  TableBuilder.SetTWidth(WidthLeftSideTyping);
  res += TableBuilder.BeginTable();
  
  TableBuilder.SetTHeight(String(CiteField.GetEmptyField().GetRowHeight()));
  
  res += TableBuilder.BeginTr();
  TableBuilder.SetTValign("top");
  res += TableBuilder.BeginTd();

//  res += CloseRedoObj.Generate();
  res += TableBuilder.EndTd();
  res += TableBuilder.EndTr();
  
  res += TableBuilder.BeginTr();
  TableBuilder.SetTValign("top");
  TableBuilder.SetTAlign('right');
  res += TableBuilder.BeginTd();

  res += "Вместо";

  res += TableBuilder.EndTd();
  res += TableBuilder.EndTr();
  
  TableBuilder.ResetT();
  
  res += TableBuilder.BeginTr();
  TableBuilder.SetTValign("top");
  TableBuilder.SetTAlign('right');
  res += TableBuilder.BeginTd();

  res += "Вы набрали";

  res += TableBuilder.EndTd();
  res += TableBuilder.EndTr();  

  
  res += TableBuilder.EndTable();
  return res;  
}

function SetLeftSideTyping()
{
  document.getElementById(FingerZonesObj.GetID()).innerHTML = FingerZonesObj.Insert();
}

var WidthLeftSideTyping = 0;


function SetLeftSideError()
{

  document.getElementById("IDTimeLowResolution").style.display = "none";

  var style= 'font-family: Arial; font-size: 14pt; color: #555555;';
  var tableHeight = height;
  var tableWidth = document.getElementById(IDFingerZonesTd).offsetWidth;
  
  var heightInput1 = document.getElementById('IDTdInput').offsetHeight / 2;
  var heightInput2 = document.getElementById('IDTdInput').offsetHeight / 2;
  var heightInterval = 0;
  
  var height = heightInput1 + heightInput2 + heightInterval;
  var height1 = heightInput1 + heightInterval;
  var height2 = height - height1;
  
  document.getElementById(FingerZonesObj.GetID()).innerHTML =
  "<table height=" + tableHeight + " width=" + tableWidth + " cellspacing=0 cellpadding=0 border=0><tr height='" + height1 + "px'><td align='right' valign='top'>" +
  "<font style='" + style + "'>Вместо</font></td></tr><tr height='" + height2 + "px'><td align=right valign=top>" +
  "<font style='" + style + "'>Вы набрали</font></td></tr></table>";
}

function PlaceInitInputCntrl()
{
  var classForInput = "";
  classForInput = "hiderRadioOtherBrowsers";
  Write("<input id='IDInputRadio' type='text' class='" + classForInput + "' onKeyPress='Type(event);' onblur='SetInputFocus_();'>");   
  InitKeyPress();
}

function ShowTdUser(bShow)
{
  if(bShow == false)
    document.getElementById("IDTdUser").style.display = "none";
  else
    document.getElementById("IDTdUser").style.display = "";
}
function ShowTdFingerZones(bShow)
{
  if(bShow == false)
    document.getElementById("IDTdLeft").style.display = "none";
  else
    document.getElementById("IDTdLeft").style.display = "";  
}
function SetMainTypingTableWidth(w)
{
  document.getElementById('IDMainTypingTable').style.width = String(w) + "px";
}

var CiteField = new TCiteField(IDUserCite);

function GenerateExercise()
{	
  var sRet = "";
  
  sRet += "<table border=0 cellspacing=0 cellpadding=0>";
  // Bevels...
  sRet += "<tr height='10px'><td width='10px'  class='bevelTopLeft'>" + 
  "</td><td style='background: white' onmousedown='Mouse.Capture()'></td><td width='10px'  class='bevelTopRight'></td></tr>";
  sRet += "<tr><td style='background: white'></td><td style='background: white'>";
  
  
  //sRet += ;
  
  sRet += BeginSpan('id', 'ExerciseContent');
  
  if(!isIe6()) 
    sRet += "<span id='"+soloTypeFlash.getContainerId()+"'></span>";
  else
    sRet += "<span id='"+soloTypeFlash.getContainerId()+"'>" + soloTypeFlash.getFlash() + "</span>";
  
  sRet += EndSpan();
  sRet += BeginSpan("id", "ResultContent") + EndSpan();
  
  // Bevels...
  sRet += "</td><td style='background: white'></td><tr height='10px'>" + 
  "<td class='bevelBottomLeft'></td>" +
  "<td valign='bottom' style='background: white'></td>" +
  "<td class='bevelBottomRight'></td></tr></table>";
  
  sRet += "<div id=\'IDResultPage\'></div>"; 
  
  return sRet;
}

var IsDebugActivated = false;
function DebugOut(s)
{
  var obj = document.getElementById('IDDebug');
  if(IsDebugActivated == false)
  {
    document.getElementById('IDDebugTd').style.display = "";
    IsDebugActivated = true;
  }
  obj.innerHTML = s;
}

function UpdatePageIfSkipMode()
{
  if(ExerciseInfo.RefToNext != "")
    CloseOrGoToPage();
}


function UnsetResultPageClose(ref)
{
  ResultPage.Unset();
  Close();                       
  if(ref != undefined)
    document.location.href = ref;
  
}

function hide()
{
  document.getElementById("ExerciseBackground").style.display = "none";
  document.getElementById("Exercise").style.display = "none";
}

function Close()
{

  try {
  
    
    SetWindowOpened(false);
    
    Context.SetError(false);
  
    soloTypeFlash.deinit();
  
    if(!isIe6() && IsWindows()) soloTypeFlash.hide(); // падает как минимум здесь без исключения
    
    try
    {
      GoToBeginningOfExercise(); 
    }
    catch(e){}
    
    UpdatePageIfSkipMode();
    ShowStickoutWnds();
  }
  catch(e)
  {
    alert("error: "+e.message);
  }
  
  if(IsWindows())
    hide();
  else
    setTimeout(hide, 400);    
}

var OpacityCounter = 0;

var IDStickWnds = "videoblock"; 

function HideStickoutWnds()
{
  if(document.getElementById(IDStickWnds) != undefined)
    document.getElementById(IDStickWnds).style.visibility="hidden";
  // document.getElementById(videoblock2).innerHTML
}

function ShowStickoutWnds()
{
  if(document.getElementById(IDStickWnds) != undefined)
   document.getElementById(IDStickWnds).style.visibility="visible";
  // document.getElementById().style.visibility="none";
}

var ResultExtPage = "";
var IsKeyboard = true; // do show/update keyboard

function ShowSpeedTest(courseId)
{
  var objExtPage = document.getElementById('IDExtSpeedTestResultPage');
  if(objExtPage != null)
  {
    ResultExtPage = objExtPage.value;
    IsKeyboard = false;
    keyboard.Show(false);
    ShowTdUser(false);
    ShowTdFingerZones(false);
    SetMainTypingTableWidth(600);
    // hide table cells (left)
    SetExercsiePos(2, 2);
  }  
  ShowExercise({'type':'speedTest','courseId':courseId});
}

var TimeBegEx = 0;
function ResetBegTime()
{
  var d = new Date();
  TimeBegEx = d.getTime();
}

function GetFullExTime()
{
   var d = new Date();
   d.setTime(d.getTime() - TimeBegEx);
   var min = String(d.getMinutes());
   var sec = String(d.getSeconds());
   if(min.length < 2) min = "0" + min;
   if(sec.length < 2) sec = "0" + sec;
   return min + ":" + sec;
}

function GetActiveExTime()
{  
   var csec = Math.floor( Time.GetTimeSec()  );
   var k = Math.floor(csec / 60);
   var min = String(k);
   var sec = String(csec - 60*min);
   if(min.length < 2) min = "0" + min;
   if(sec.length < 2) sec = "0" + sec;
   return min + ":" + sec;
}

function Redirect(href)
{
  document.location.href = href;
}

var windowSys = {
	bk: undefined,
	main: undefined,
	init: function()
	{
		this.bk = document.getElementById("ExerciseBackground");
		this.main = document.getElementById("Exercise");
	}
};

function ShowExercise(initInformation/*exerciseId, courseId, bClicked, bOffline*/)
{	
    if(!generateStatus.isGenerated())
    {	  
      if(generateStatus.isTimeoutSet())
		    generateStatus.setTimeoutId( setTimeout( function() { ShowExercise(generateStatus.initInformation); } , TimeoutAJAX) );
    	else
    	{
		    generateStatus.setTimeoutId( setTimeout( function() { ShowExercise(initInformation); } , TimeoutAJAX) );
		    generateStatus.initInformation = initInformation;
    	} 

    	return;
    }
			
//  ExerciseInfo.ID = exerciseId;
  ExerciseInfo.ID = initInformation['exercise'];	
	
// test if we can do this task
  
  if(initInformation['bOffline'] != undefined && Mode.HasSet() == false)
  {  
	 PageSettings.Load();
	 Mode.SetOffline(true);
  }
  if(initInformation['bClicked'] == undefined  ||  initInformation['bClicked'] == true)
  {
    if(GetWindowOpened())
      return;
  }
  SetWindowOpened(true);

  HideStickoutWnds(); // hide video  

  if(initInformation['type'] == "speedTest")
  {
    if(SpeedTestInfo.IsResponseReceived() == false)
    {
      if(SpeedTestInfo.IsRequested() == false)  
      {
        /*if(isIe6()) */RequestSpeedTest(initInformation['courseId']);
        /*else  
        {
// Имитация того, что тест был запущен и сформирован. В основных браузерах
// формируем его по событию загрузки флеша,
// в IE6 - здесь (выше), т. к. в IE6 не формируется события загрузки флеша
          SpeedTestInfo.SimFormed();
          commonInfo.TypeOfExercise = 32; // bad...
        }*/
      }
      setTimeout("ShowExercise({'type':'speedTest', 'bClicked': false})");
      return;
    }
  }
  else if(initInformation['type'] == 'startExam' || initInformation['type'] == 'finalExam') // in SCORM version only
  {
// ввиду того, что непонятно, в какой файл выносить инициализацию, проводим её здесь, потом вынесем
      ExerciseInfo.isExam = true;
      ExerciseInfo.typeExam = initInformation['type'];
      ExerciseInfo.examType = initInformation['type'];  
      RequestAnswer.ExamGot();
  }  
  else if(ExerciseInfo.IsResponseReceived() == false)
  {
    if(ExerciseInfo.IsRequested() == false)  
    {
      RequestExercise(initInformation['exercise'], initInformation['courseId']);
    }
    var exStr = "ShowExercise({'type':'"+initInformation['type']+"', 'exercise':'" + initInformation['exercise'] + "', 'courseId':" + initInformation['courseId'] + ", 'bClicked':false})";
    setTimeout(exStr, TimeoutAJAX);

    return;
  }
  else
  {
    if(ExerciseInfo.Redirect != "")
    {
      Redirect(ExerciseInfo.Redirect);
      return;
    }   
  }
// discomment later
// also skip
/*  if( !( GetExType() == 32  &&  !isIe6() ) )
  {*/
    if(CiteInfo.IsResponseReceived() == false)
    {
      if(CiteInfo.IsRequested() == false)  
      {
        RequestCite();
      }
      setTimeout("ShowExercise({'type':'"+initInformation['type']+"', 'exercise':'" + initInformation['exercise'] + "', 'courseId':" + initInformation['courseId'] + ", 'bClicked':false})", TimeoutAJAX );
      return;
    }
  //}
  
  if(GetExType() != 32)
  if(ErrorsInfo.IsResponseReceived() == false)
  {
    if(ErrorsInfo.IsRequested() == false)  
    {
      RequestErrors();
    }
    setTimeout("ShowExercise({'type':'"+initInformation['type']+"', 'exercise':'" + initInformation['exercise'] + "', 'courseId':" + initInformation['courseId'] + ", 'bClicked':false})", TimeoutAJAX );
    return;
  }
   
  if(KeyboardInfo.IsResponseReceived() == false)
  {
    if(KeyboardInfo.IsRequested() == false)  
    {  
      RequestKeyboardParams();
    }
    setTimeout("ShowExercise({'type':'"+initInformation['type']+"', 'exercise':'" + initInformation['exercise'] + "', 'courseId':" + initInformation['courseId'] + ", 'bClicked':false})", TimeoutAJAX );
    return;    
  }
    
//  siteUserList.disable();  
     
  if(OpacityCounter < 5)
  {
    if(OpacityCounter == 0)
    {
      windowSys.init();
      try
      {
        if (window.navigator.appName != "Netscape")
        {      
          windowSys.bk.style.width = document.getElementById("full-page").offsetWidth;
          windowSys.bk.style.height = document.getElementById("full-page").offsetHeight;
        }
      }
      catch(e) {}      
    }    
    OpacityCounter++;
    if(window.navigator.appName == "Microsoft Internet Explorer")
    {
    	windowSys.bk.style.filter = "alpha(opacity=" + String(OpacityCounter * 10) + ")";
    }
    else  windowSys.bk.style.opacity = OpacityCounter / 10.0;
    
    windowSys.bk.style.display = "";   

//    setTimeout("ShowExercise(" + exerciseId + ", " + courseId + ", false)", 50);  
    setTimeout("ShowExercise({'type':'"+initInformation['type']+"', 'exercise':'" + initInformation['exercise'] + "', 'courseId':" + initInformation['courseId'] + ", 'bClicked':false})", 50 );    
    
    return;
  } 
  
  if(GetExType() == 32)
  {        
/*    if(ExerciseInfo.isExam)
      objInfo = ExamInfo;
  
    var strText = FormatToStrings(objInfo.Text, 40);
    
    SetExerciseMaxNumOfMistakes("0");
    
    if(!ExerciseInfo.isExam) 
    { 
      SetSpeedTestCaption();
      CaptionArrow.Show();
    }
    else
    {
      switch(ExerciseInfo.examType)
      {
        case 'startExam':
          SetStartExamCaption();
          break;
        default:
          SetFinalExamCaption();
      }
    }  */
  }
  else
  { 
    SetExerciseNumberCaption(String(ExerciseInfo.LessonNumber) + "." + String(ExerciseInfo.ExerciseNumber));
    SetExerciseMaxNumOfMistakes(ExerciseInfo.MaxNumOfMistakes);
    ExerciseInfo.Reset();   
//    CaptionArrow.Hide();
  }
  
//  alert("post 2");
  
  SpeedTestInfo.Reset();
  CiteInfo.Reset();
  
  KeyboardInfo.Reset();
  generateStatus.reset();
  
  OpacityCounter = 0;
  
  ResetBegTime();
  document.getElementById("Exercise").style.visibility = "hidden";
  document.getElementById("Exercise").style.display = "";
  document.getElementById("Exercise").style.visibility = "visible";
  
  if(!isIe6()) 
  {
    soloTypeFlash.show();
    soloTypeFlash.showPleaseWait();
  }
  else
    onTypeFlashLoaded();
  
/*  if(isIe6())
    setTimeout(onTypeFlashLoaded, 5000);*/
  
//  CloseRedoObj.Show(true);
  
//  alert("post 3");
  
/*  if(FlashInput.IsFlashLoaded() == false)
  {          
    if(!isIe6())  
    {
      FlashInput.Reset();
    }
    else  
    {
      FlashInput.ResetContent();
    } 
  }*/ 
  
  ExerciseInit(); // we have al the information about exercise
  
  keyboard.SetInputFocus();  
  
/*  document.getElementById('IDRightTable').style.height = document.getElementById('IDTdRight').clientHeight+"px";
  document.getElementById('IDLeftTable').style.height = document.getElementById('IDTdLeft').clientHeight+"px";  
  document.getElementById('IDRightTable').style.visibility = "visible";
  document.getElementById('IDLeftTable').style.visibility = "visible";*/
        
  if(isIe6()) document.getElementById("Exercise").style.top = getScrollY() + WindowTop;      
         
  ResultPage.RefToNextHasSet(false);
}

function requestCiteAndText()
{
    if(CiteInfo.IsResponseReceived() == false)
    {
      if(CiteInfo.IsRequested() == false)  
      {
        RequestCite();
      }
      return false;
    }  
    
    if(SpeedTestInfo.IsResponseReceived() == false)
    {  
      if(SpeedTestInfo.IsRequested() == false)  
      {
        RequestSpeedTest(commonInfo.CourseID);       
      }
      return false;
    }
    
    return true;
}

function resetRequestCiteAndText()
{
  CiteInfo.Reset();
  SpeedTestInfo.Reset();
}

function ClickBegExercise()
{ 
  if(GetExType() == 32)
  {
    
    if(requestCiteAndText() == false)
    {
      setTimeout(ClickBegExercise, TimeoutAJAX);
      return;
    }
    resetRequestCiteAndText();
  
    soloTypeFlash.setCite(CiteInfo.Text);
    soloTypeFlash.setCiteAuthor(CiteInfo.Author);
    soloTypeFlash.reset();
    soloTypeFlash.setText(SpeedTestInfo.Text);     
  }
  
  soloTypeFlash.beginExercise();
  
//  RequestCiteSpeedUpdate();
// something to update user text
}

function RepeatExercise()
{               
  if(isOperaLess10()) 
    soloTypeFlash.show();
     
  if(GetExType() == 32)
  {
    if(requestCiteAndText() == false)
    {
      setTimeout(RepeatExercise, TimeoutAJAX);
      return;
    }
    else
    if(!isIe6())
    {
      if(isIe()) soloTypeFlash.show();
    } 
    
    resetRequestCiteAndText();
  }
  
  ResultPage.Unset();
  
  if(isIe6())  
    ClickBegExercise();    
  
  ExerciseInit();
  
  GoToBeginningOfExercise();     
 
}

function ShowMainWindow(bShow)
{
  soloTypeFlash.deinit();
  
  if(bShow)
  {
    document.getElementById("Exercise").style.visibility = "visible";
  }
  else
  {
    document.getElementById("Exercise").style.visibility = "hidden"; 
  }
}

function SetInputFocus_()
{
  if(ResultPage.IsSet() == false  &&  keyboard.GetTypeBlock() == false)
  {
    keyboard.SetInputFocus();
  }
}
var generateStatus = {
  bGenerated: false,
  doGenerated: function()
  {
    this.bGenerated = true;
  },
      
  isGenerated: function()
  {
    return this.bGenerated;
  },
  idTimeout: -1,
  
  reset: function()
  {
    this.idTimeout = -1;
  },
  
  isTimeoutSet: function()
  {
    return (this.idTimeout != -1);
  },
  setTimeoutId: function(idTimeout)
  {
    this.idTimeout = idTimeout;
  }    
};

var ExerciseIniter = {
	init: function()
	{
	  /*
// init flash size coefficients    
    if(Environment.IsOnline())
	  {
      if(screen.height < 768)
        soloTypeFlash.setSizeCoefficient(0.5);
      else
      if(screen.height < 1024)
        soloTypeFlash.setSizeCoefficient(0.75);
      else
        soloTypeFlash.setSizeCoefficient(1.0);
    }
    else
    {
      if(screen.height < 768)
        soloTypeFlash.setSizeCoefficient(0.5);
      else
      if(screen.height < 1024)
        soloTypeFlash.setSizeCoefficient(0.75);
      else
        soloTypeFlash.setSizeCoefficient(1.0);
    }*/
	
		document.getElementById('Exercise').innerHTML = GenerateExercise();
		generateStatus.doGenerated();
	}
};

InitForScreenResolution();  
                   

Write("<div id='ExerciseBackground' onmouseup='Mouse.Release()' style='width: 3000px; height: 2000px; display: none'></div><div onmouseup='Mouse.Release()' id=\'Exercise\' style='top: " + WindowTop + "px; left:" + WindowLeft+ "px; display: none'></div>"); // main                    
                    																																					// exercise
																																															// div

function flashTrace(mess)
{
//  alert(mess);
}