//
// $Id: Questionnaire.js,v 1.20 2007-09-28 08:23:26 thomas Exp $
//

/** usefull string trimming */
var FILL_FRONT = 1;
var FILL_BACK = 2;

/** progressbar */
function progressbar() {
   this.type = 0; // 0 chunks, 1 picture
   this.pct = 0;
   this.step = 10;
   this.bordersize = 0;

   this.images = new Array();
}

progressbar.prototype.setImage = function(i, imgsrc) {
   this.images[i] = imgsrc;
}

progressbar.prototype.getHTML = function() {
   var i, j;
   var sres = "";

   if (this.images.length > 0) this.step = 100 / this.images.length;

   sres += "<table border=" + this.bordersize + ">";
   sres += "<tr><td>";

   sres += "<table border=0 cellspacing=0 cellpadding=0>";
   sres += "<tr>";

   if (this.type == 0) {
      j = 0;
      for (i = 0; i < this.pct; i += this.step) {
         sres += "<td><img src=\"../../Images/Questionnaire/Viewer/Progress/" + this.images[j++] + "\"></td>";
      }
   }
   else {
      j = Math.floor(this.pct / this.step);

      if (j >= this.images.length && j > 0) j = this.images.length - 1;

      sres += "<td><img src=\"../../Images/Questionnaire/Viewer/Progress/" + this.images[j] + "\"></td>";
   }

   sres += "</tr>";
   sres += "</table>";

   sres += "</td></tr>";
   sres += "</table>";

   return sres;
}
/*progressbar end*/

/******* countDown object *******/
/* CONTANTS */
var COUNTDOWN_NORMAL = 0;
var COUNTDOWN_DIFFICULT = 1;

// Declare countDown object
function countDown(divElement, time) {
   var me = this;
   me.divElement = divElement;
   me.divElement.object = me;
   me.divElement.onclick = me.onmouseclick;

   me.time = time;
   me.value = time;
   me.type = 1;
   me.width = 100;
   me.typeWidthUnit = "px";
   me.height = 100;
   me.typeHeightUnit = "px";
}

// Render method of countDown object
countDown.prototype.render = function() {
   var me = this;
   switch (me.type) {
      case COUNTDOWN_NORMAL:
         {
            me.divElement.innerHTML = me.value;
            break;
         }
      case COUNTDOWN_DIFFICULT:
         {
            var widthFirst = Math.round(me.value / me.time * 100);
            var widthSecond = 100 - widthFirst;
            var sHTML = "<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=" + me.width + me.typeWidthUnit + " height=" + me.height + me.typeHeightUnit + ">";
            sHTML += "<tr>";
            if (me.typeWidthUnit == "px")
               sHTML += "<td width=" + (me.width - 50) + me.typeWidthUnit + " align=\"left\">";
            else if (me.typeWidthUnit == "%") {
               sHTML += "<td width=" + (me.width - 10) + me.typeWidthUnit + " align=\"left\">";

            }
            else {
               sHTML += "<td width=\"100%\" align=\"left\">";
            }
            sHTML += "<table cellspacing=\"0\" cellpadding=\"0\" border=\"2\" bordercolor=\"#225599\" width=\"100%\">";
            sHTML += "<tr>";
            if (widthFirst == 100) {
               sHTML += "<td style=\"filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#BBBFC2', EndColorStr='aliceblue'); HEIGHT: " + me.height + me.typeHeightUnit + "; WIDTH: " + widthFirst + "%\"></td>";
            }
            else if (widthFirst == 0) {
               sHTML += "<td style=\"WIDTH: " + widthSecond + "%; HEIGHT: " + me.height + me.typeHeightUnit + "\"></td>";
            }
            else {
               sHTML += "<td style=\"filter:progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#BBBFC2', EndColorStr='aliceblue'); HEIGHT: " + me.height + me.typeHeightUnit + "; WIDTH: " + widthFirst + "%\"></td>";
               sHTML += "<td style=\"WIDTH: " + widthSecond + "%; HEIGHT: " + me.height + me.typeHeightUnit + "\"></td>";
            }
            sHTML += "</tr>";
            sHTML += "</table>"
            sHTML += "</td>";
            sHTML += "<td width=\"50px\" align=\"right\">" + me.value + "</td>";
            sHTML += "</tr>";
            sHTML += "</table>";

            this.divElement.innerHTML = sHTML;
            break;
         }
      default:
         {
            this.divElement.innerHTML = --this.time;
         }
   }
}

/* Events */
countDown.prototype.onmouseclick = function(e) {
   // this references the div element, that
   // means that this.object references the
   // countDown object
   var me = this.object;
   var dummy = me.time;
   var x, y;
   if (navigator.appName.indexOf("Microsoft") != -1) {
      e = window.event;

      if (e.x || e.y) {
         x = e.offsetX;
         y = e.offsetY;
         me.type = me.type == 1 ? 0 : 1;
      }
   }
   else {
      if (e.x || e.y) {
         x = e.x;
         y = e.y;
         alert("NotMicrosoft:" + x + ":" + y);
         me.type = me.type == 1 ? 0 : 1;
      }
   }
}

function fillValue(value, fill, length, pos)
{
 var res;
 res = value.toString();
 while (res.length < length)
  res += fill;
 return res;
}

function toFixed(value, precision)
{
 var res, idx;
 res = value.toString();
 res = res.replace(/\,/ig, ".");
 idx = res.indexOf(".") + 1;
 len = parseInt(precision);
 if (idx > 0)
  res = res.substring(0, idx) + fillValue(res.substring(idx, idx + len), "0", len, FILL_BACK);
 else
  res = res + "." + fillValue("", "0", len, FILL_BACK);
 return res;
}
/*countdown end*/

//$Id: PopupImage.js,v 1.2 2007-06-22 08:18:00 tphuong Exp $

PositionX = 100;
PositionY = 100;

// Set these value approximately 20 pixels greater than the
// size of the largest image to be used (needed for Netscape)

defaultWidth = 500;
defaultHeight = 500;

// Set autoclose true to have the window close automatically
// Set autoclose false to allow multiple popup windows
var AutoClose = true;

if (parseInt(navigator.appVersion.charAt(0)) >= 4) {
   var isNN = (navigator.appName == "Netscape") ? 1 : 0;
   var isIE = (navigator.appName.indexOf("Microsoft") != -1) ? 1 : 0;
}

var optNN = 'left=' + PositionX + ',top=' + PositionY + ',resizable=1';
var optIE = 'left=' + PositionX + ',top=' + PositionY + ',resizable=1';

function popupImage(imageURL, widthImage, heightImage, imageTitle) {
   if (isNN) {
      imgWin = window.open('about:blank', '', optNN);
   }

   if (isIE) {
      imgWin = window.open('about:blank', '', optIE);
   }

   with (imgWin.document) {
      writeln('<html><head><title>Loading...</title><style>body{margin:0px;}</style>');
      writeln('<sc' + 'ript>');
      writeln('var isNN,isIE;');
      writeln('if (parseInt(navigator.appVersion.charAt(0))>=4){');
      writeln('isNN=(navigator.appName=="Netscape")?1:0;');
      writeln('isIE=(navigator.appName.indexOf("Microsoft")!=-1)?1:0;}');
      writeln('function reSizeToImage(){');
      writeln('if (isIE){');
      writeln('window.resizeTo(350,350);');
      writeln('width=350 - document.body.clientWidth +' + widthImage + ';');
      writeln('height=350-document.body.clientHeight+' + heightImage + ';');
      writeln('window.resizeTo(width,height);}');
      writeln('if (isNN){');
      writeln('window.innerWidth=350 - document.body.clientWidth +' + widthImage + ';');
      writeln('window.innerHeight=350-document.body.clientHeight+' + heightImage + ';}}');
      writeln('function doTitle(){document.title="' + imageTitle + '";}');
      writeln('</sc' + 'ript>');
      if (!AutoClose) {
         writeln('</head><body bgcolor=000000 onload="reSizeToImage();doTitle();self.focus()">');
      }
      else {
         writeln('</head><body bgcolor=000000 scroll="yes" onload="reSizeToImage();doTitle();self.focus()" >');
      }
      writeln('<img name="PopupImage" src=' + imageURL + ' width=' + widthImage + ' height=' + heightImage + '"></body></html>');
      close();
   }
}
/*popupimage end*/

function ltrim(str)
{
 return str.replace(/^[ \t]*/, "");
}

function rtrim(str)
{
 return str.replace(/[ \t]*$/, "");
}

function trim(str)
{
 var tmpstr;
 tmpstr = ltrim(str);
 return rtrim(tmpstr);
}

//
// Error message object
//
function ErrorMessages()
{
 if (document.getElementById != null)
  this.element = document.getElementById("errorMessages");
}

ErrorMessages.getInstance = function()
{
 if (this.instance == null)
  this.instance = new ErrorMessages();
 return this.instance;
}

ErrorMessages.prototype.showErrorMessage = function(errorMessage)
{
 if (this.element == null)
  alert(errorMessage);
 else
  this.element.innerHTML += errorMessage.replace(/\n/ig, "<br />") + "<br />";
}

ErrorMessages.prototype.clearErrorMessages = function()
{
 if (this.element != null)
  this.element.innerHTML = "";
}

/** option object */
function option(qobj, index, value, text, single, open)
{
 this.qobj = qobj;

 this.label = qobj.label;
 this.index = index;
 this.value = value;
 this.text = text;

 this.align = "center";

 if (single)
  this.single = single;
 else
  this.single = false;

 if ((typeof open) != "undefined")
  this.open = open;

 this.checked = false;
 this.disabled = false;
 this.visible = true;
}

option.prototype.getHTML = function(ltype)
{
 var sres = "";
 var stmp = "";

 if (this.visible)
 {
  switch (ltype)
  {
   //debugger; 
   case 1:
    if (this.disabled)
    {
     sres += this.text;
    }
    else
    {
     sres += "<a class=\"option_link\" href=\"javascript:optclick('" + this.label + "'," + this.index + ",true);\">";
     sres += this.text;
     sres += "</a>";
    }

    if ((typeof this.open) != "undefined")
    {
     sres += "<td><input type=\"text\" name=\"" + this.label + ".Open." + this.value + "\" value=\"" + this.open + "\" ";

     if (!this.checked) sres += "disabled";

     sres += "></td>";
    }
   case 2:
    stmp += "<input type=\"radio\" ";
    stmp += "name=\"" + this.label + "\" ";
    stmp += "value=\"" + this.value + "\" ";

    if (this.checked) stmp += "checked ";
    if (this.disabled) stmp += "disabled ";

    stmp += "onclick=\"optclick('" + this.label + "'," + this.index + ",false);\">";

    if (sres == "")
    {
     sres = "<td valign=\"center\" align=\"" + this.align + "\">" + stmp + "</td>";
    }
    else
    {
     sres = "<td class=\"answer_option_cell\"><table width=\"100%\"><tr><td width=\"16px\"  valign=\"top\" align=\"" + this.align + "\">" + stmp + "</td><td  valign=\"top\" align=\"left\">" + sres + "</td><td>&nbsp;</td></tr></table></td>";
    }
    break;
   case 3:
    if (this.disabled)
    {
     sres += this.text;
    }
    else
    {
     sres += "<a class=\"option_link\" href=\"javascript:optclick('" + this.label + "'," + this.index + ",true);\">";
     sres += this.text;
     sres += "</a>";
    }

    if ((typeof this.open) != "undefined")
    {
     sres += "<td><input type=\"text\" name=\"" + this.label + ".Open." + this.value + "\" value=\"" + this.open + "\" ";

     if (!this.checked) sres += "disabled";

     sres += "></td>";
    }
   case 4:
    stmp += "<input type=\"checkbox\" ";
    stmp += "name=\"" + this.label + "\" ";
    stmp += "value=\"" + this.value + "\" ";

    if (this.checked) stmp += "checked ";
    if (this.disabled) stmp += "disabled ";

    stmp += "onclick=\"optclick('" + this.label + "'," + this.index + ",false);\">";

    if (sres == "")
    {
     sres = "<td valign=\"center\" align=\"" + this.align + "\">" + stmp + "</td>";
    }
    else
    {
     sres = "<td class=\"answer_option_cell\"><table ><tr><td width=\"16px\" valign=\"top\" align=\"" + this.align + "\">" + stmp + "</td><td valign=\"top\" align=\"left\">" + sres + "</td><td>&nbsp</td></tr></table></td>";
    }
    break;
   case 5:
    sres += "<option label=" + this.label + " ";

    if (this.checked) sres += "selected ";

    sres += "value=" + this.value + ">" + this.text + "</option>";
    break;
   default:
    break;
  }
 }
 return sres;
}

/** --------------------------------------------------- */

/** question object */
function question(type, label, text, reference)
{
 this.doc = document;
 this.reference = reference;

 this.type = type;
 this.label = label;
 this.text = text;

 // Answer and properties
 this.answer = "";
 this.answertype = null; // answertype can be : null or 1 - Text or 2 - Number
 this.unit = "";

 this.options = new Array();
 this.questions = new Array();

 this.min = null; this.max = null; this.allowfloat = false;

 this.normalClose = false;
 this.end = false;
 this.redirectionurl = "";

 // Errormessages
 this.required = false;
 this.requiredtext = "Please answer the question.";
 this.minrequiredtext = "Please choose a minimum of [[x]] options from the list.";
 this.maxrequiredtext = "Please choose a maximum of [[x]] options from the list.";

 this.numberrequiredtext = "The value must be a number.";
 this.minvalrequiredtext = "The minimum value allowed is [[x]].";
 this.maxvalrequiredtext = "The maximum value allowed is [[x]].";
 this.nofloatvaltext = "Floating point values not allowed as answer.";
 this.numberoverflow = "The maximum value allowed is 10^14.";

 this.ingridrequiredtext = "Please answer the following question(s) to continue : ";
 this.miningridrequiredtext = "Please choose a minimum of [[x]] options from the following question(s) : ";
 this.maxingridrequiredtext = "Please choose a maximum of [[x]] options from the following question(s) : ";

 this.uniqueansweringridrequiredtext = "One or more of the answer options can only be used one time for this question";
 this.illegaltype = "The type of answer is not valid for the question : ";
 this.bufferingvideo = "Buffering video, please wait.. ";
 this.nowmp = "The required version of Windows Media Player was not found.";
 this.impsysrequiredtext = "Please use all the words.";
 this.impsysselectiontext = "Choose words";
 this.impsyschoicetext = "Choose here";

 this.backtext = "Previous"; this.backvisible = true; this.back = null;
 this.nexttext = "Next"; this.nextvisible = true; this.next = null;
 this.resettext = "Reset"; this.resetvisible = true; this.reset = null;
 this.closetext = "Close"; this.closevisible = false; this.close = null;

 this.next = function() { };
 this.back = function() { };
 this.reset = function() { };
 this.close = function() { };

 this.bordersize = 0;

 // Is question visible, usefull for grid questions only
 this.visible = true;
 this.catimode = false;
 this.checkansweruniqueness = false;
 this.answeruniquenessoptions = "";

 // Count down functionality
 this.showcountdowndisplay = true; // Show countdown to the user
 this.countDownObj = null;
 this.countdown = -1;     // The countdown is given in seconds, and -1 means infinite time
 this.countdownHandle = null;   // The handle for the timed trigger

 // Languages for languageselector
 this.languages = new Array();

 // General layout stylesheet for question   
 this.questionstylesheet = "";
 this.nolinebreak = true;

 // Answeroptions layout
 this.autoarrangeansweroptions = false;
 this.rows = 0; this.cols = 0;
 this.size = 0; this.maxlength = 0;
 this.displaytype = 1; // 1: Normal display, 5: Compact display

 // Grid layout -- Not used yet
 this.autoarrangegrid = true;
 this.gridunit = "%";
 this.gridwidth = "100";
 this.gridheight = "";
 this.gridsubquestionwidth = "";
 this.gridsubquestioncolumnheight = "";

 this.gridcolumns = new Array();
 this.gridcolumns[0] = "";

 // Sound
 this.sound = null;

 // Progress
 this.progress = new progressbar();
 this.progress.type = 1;
 this.progress.images = ["progres0.gif", "progres1.gif", "progres2.gif", "progres3.gif", "progres4.gif", "progres5.gif", "progres6.gif", "progres7.gif", "progres8.gif", "progres9.gif", "progres10.gif", "progres11.gif"];

 // Multimedia
 if (type == 10)
 {
  this.mm = new multimedia(this.reference + ".mm");
 }

 // Scale
 if (type == 11)
 {
  this.so = new scale();

  this.so.type = SCALE_DISCRETE;
  this.so.minimum = 0;
  this.so.maximum = 9;
  this.so.step = 1;
  this.so.minimumtext = "";
  this.so.maximumtext = "";
  this.so.textposition = SCALE_LEFT_RIGHT_TEXTPOS;
 }

 // Scalegrid
 if (type == 12)
 {
  this.so = new scale();

  this.so.type = SCALE_DISCRETE;
  this.so.minimum = 0;
  this.so.maximum = 9;
  this.so.step = 1;
  this.so.minimumtext = "";
  this.so.maximumtext = "";
  this.so.textposition = SCALE_NONE_TEXTPOS;
 }
}
question.prototype.rotateSubQuestions = function(startIndex, endIndex, offset)
{
 //debugger;
 if (isNaN(startIndex) || isNaN(endIndex) || isNaN(offset) || startIndex != Math.round(startIndex) || endIndex != Math.round(endIndex) || offset != Math.round(offset))
 {
  alert(this.ErrMsgInvalidParamater);
  return;
 }
 if (startIndex < 0 || endIndex > this.questions.length - 1 ||
     startIndex >= endIndex)
 {
  alert(this.ErrMsgRotationRange_SubQuestion);
  return;
 }
 if (offset < startIndex || offset > endIndex)
 {
  alert(this.ErrMsgInvalidRotate);
  return;
 }

 var subQuesCount = this.questions.length;
 var subQuesArray = new Array(subQuesCount);
 var qStep = offset - startIndex;
 var range = endIndex - startIndex;
 var i;
 for (i = startIndex; i < endIndex + 1; i++)
 {
  subQuesArray[i] = this.questions[startIndex + qStep];
  if (qStep < range)
   qStep++;
  else
   qStep = 0;
 }
 for (i = 0; i < startIndex; i++)
  subQuesArray[i] = this.questions[i];
 for (i = endIndex + 1; i < subQuesCount; i++)
  subQuesArray[i] = this.questions[i];

 this.setQuestions(subQuesArray);
}
question.prototype.rotateAnswerOptions = function(startIndex, endIndex, offset)
{
 //debugger;   
 if (isNaN(startIndex) || isNaN(endIndex) || isNaN(offset) || startIndex != Math.round(startIndex) || endIndex != Math.round(endIndex) || offset != Math.round(offset))
 {
  alert(this.ErrMsgInvalidParamater);
  return;
 }
 if (offset < startIndex || offset > endIndex)
 {
  alert(this.ErrMsgInvalidRotate);
  return;
 }
 if (this.type != 6 && this.type != 7)
 {

  if (startIndex < 0 || endIndex > this.options.length - 1 ||
     startIndex >= endIndex)
  {
   alert(this.ErrMsgRotationRange_AnswerOption);
   return;
  }

  var ansOptionCount = this.options.length;
  var ansOptArray = new Array(ansOptionCount);
  var aStep = offset - startIndex;
  var range = endIndex - startIndex;
  var i;
  for (i = startIndex; i < endIndex + 1; i++)
  {
   ansOptArray[i] = this.options[startIndex + aStep];
   if (aStep < range)
    aStep++;
   else
    aStep = 0;
  }
  for (i = 0; i < startIndex; i++)
   ansOptArray[i] = this.options[i];
  for (i = endIndex + 1; i < ansOptionCount; i++)
   ansOptArray[i] = this.options[i];
  this.setOptions(ansOptArray);
 }
 else
 {
  if (startIndex < 0 || endIndex > this.questions[0].options.length - 1 ||
     startIndex >= endIndex)
  {
   alert(this.ErrMsgRotationRange_AnswerOption);
   return;
  }

  for (var i = 0; i < this.questions.length; i++)
   this.questions[i].rotateAnswerOptionOfSubQuestion(startIndex, endIndex, offset)
 }
}
question.prototype.rotateAnswerOptionOfSubQuestion = function(startIndex, endIndex, offset)
{
 var ansOptionCount = this.options.length;
 var ansOptArray = new Array(ansOptionCount);
 var aStep = offset - startIndex;
 var range = endIndex - startIndex;
 var i;
 for (i = startIndex; i < endIndex + 1; i++)
 {
  ansOptArray[i] = this.options[startIndex + aStep];
  if (aStep < range)
   aStep++;
  else
   aStep = 0;
 }
 for (i = 0; i < startIndex; i++)
  ansOptArray[i] = this.options[i];
 for (i = endIndex + 1; i < ansOptionCount; i++)
  ansOptArray[i] = this.options[i];
 this.setOptions(ansOptArray);
}
question.prototype.randomizeSubQuestions = function(seed, startIndex, endIndex)
{
 if (isNaN(startIndex) || isNaN(endIndex) || startIndex != Math.round(startIndex) || endIndex != Math.round(endIndex) || seed != Math.round(seed))
 {
  alert(this.ErrMsgInvalidParamater);
  return;
 }
 if (startIndex < 0 || startIndex >= endIndex || endIndex > this.questions.length - 1)
 {
  alert(this.ErrMsgRandommizeRange_SubQuestion);
  return;
 }
 if (isNaN(seed))
 {
  alert(this.ErrMsgSeedNumber);
  return;
 }
 var randomObject = new randomMaker(seed, startIndex, endIndex);
 randomObject.run();
 var rangeSize = endIndex - startIndex + 1;
 var tempArr = new Array(rangeSize);
 for (var i = 0; i < rangeSize; i++)
  tempArr[i] = this.questions[randomObject.result[i]];

 for (var i = 0; i < rangeSize; i++)
  this.questions[startIndex + i] = tempArr[i];

}
question.prototype.randomizeAnswerOptions = function(seed, startIndex, endIndex)
{//debugger;
 if (isNaN(startIndex) || isNaN(endIndex) || startIndex != Math.round(startIndex) || endIndex != Math.round(endIndex) || seed != Math.round(seed))
 {
  alert(this.ErrMsgInvalidParamater);
  return;
 }
 if (isNaN(seed))
 {
  alert(this.ErrMsgSeedNumber);
  return;
 }
 if (this.type != 6 && this.type != 7)
 {
  if (startIndex < 0 || startIndex > endIndex || endIndex > this.options.length - 1)
  {
   alert(this.ErrMsgRandommizeRange_AnswerOption);
   return;
  }

  var randomObject = new randomMaker(seed, startIndex, endIndex);
  randomObject.run();
  var rangeSize = endIndex - startIndex + 1;
  var tempArr = new Array(rangeSize);
  for (var i = 0; i < rangeSize; i++)
   tempArr[i] = this.options[randomObject.result[i]];

  for (var i = 0; i < rangeSize; i++)
   this.options[startIndex + i] = tempArr[i];
 }
 else
 {
  if (startIndex < 0 || startIndex > endIndex || endIndex > this.questions[0].options.length - 1)
  {
   alert(this.ErrMsgRotationRange_AnswerOption);
   return;
  }
  for (var i = 0; i < this.questions.length; i++)
   this.questions[i].randomizeAnswerOptionOfSubQuestion(seed, startIndex, endIndex);
 }
}
question.prototype.randomizeAnswerOptionOfSubQuestion = function(seed, startIndex, endIndex)
{
 var randomObject = new randomMaker(seed, startIndex, endIndex);
 randomObject.run();
 var rangeSize = endIndex - startIndex + 1;
 var tempArr = new Array(rangeSize);
 for (var i = 0; i < rangeSize; i++)
  tempArr[i] = this.options[randomObject.result[i]];

 for (var i = 0; i < rangeSize; i++)
  this.options[startIndex + i] = tempArr[i];
}
question.prototype.getGridIndex = function()
{
 var labelArray = this.label.split(".");

 if (
   this.type == 6 ||
   this.type == 7 ||
   this.type == 8 ||
   this.type == 12
   )
 {
  return labelArray[labelArray.length - 1];
 }
 else
 {
  return null;
 }
}

question.prototype.setOptions = function(options)
{
 this.options = options;
}

question.prototype.setQuestions = function(questions)
{
 this.questions = questions;
}

question.prototype.setAnswer = function(answer)
{
 this.answer = answer;
}

question.prototype.calcrc = function()
{
 var prod, len;

 prod = this.rows * this.cols;
 len = this.options.length;

 if (0 < prod && prod < len)
 {
  //alert("Error : Rows and columns dimensioned too small to contain all questionoptions.");
  ErrorMessages.getInstance().showErrorMessage("Error : Rows and columns dimensioned too small to contain all questionoptions.");
 }
 else
 {
  if (this.rows <= 0 && this.cols > 0)
  {
   this.rows = Math.ceil(len / this.cols);
  }
  else if (this.rows > 0 && this.cols <= 0)
  {
   this.cols = Math.ceil(len / this.rows);
  }
  else if (this.rows <= 0 && this.cols <= 0)
  {
   this.rows = len;
   this.cols = 1;
  }
 }
}

question.prototype.getLanguageSelector = function(selectedLanguage)
{
 var res = "";

 if (this.languages.length > 0)
 {
  res += "<select name=\"languageselector\" onchange=\"changelanguage();\">";
  for (i = 0; i < this.languages.length; i++)
  {
   res +=
   "<option " +
   "value=\"" + this.languages[i][0] + "\"" +
   ((this.languages[i][0] == selectedLanguage) ? " selected" : "") +
   ">" + this.languages[i][1] + "</option>";
  }
  res += "</select>";
 }

 return res;
}

question.prototype.getNavigationPanel = function()
{
 var sres = "";

 var closeText = (this.changeclosetexttonexttext != null && this.changeclosetexttonexttext == true) ? this.nexttext : this.closetext;

 if (this.backvisible) sres += "<input type=\"button\" name=\"back\" value=\"" + this.backtext + "\" tabindex=1000 onclick=\"" + this.reference + ".back();\">";
 if (this.resetvisible) sres += "<input type=\"button\" name=\"reset\" value=\"" + this.resettext + "\" tabindex=1001 onclick=\"" + this.reference + ".reset();\">";
 if (this.closevisible) sres += "<input type=\"button\" name=\"close\" value=\"" + closeText + "\" tabindex=1002 onclick=\"" + this.reference + ".close();\">";
 if (this.nextvisible) sres += "<input type=\"submit\" name=\"next\" value=\"" + this.nexttext + "\" tabindex=0>";

 return sres;
}

question.prototype.getHTML = function()
{
 var i, j, k, l, x, y, len, size, ans, gridnumber;
 var sres = "";
 var oddOrEven, theIndex;
 var widthOpen, heigthOpen;

 sres += this.questionstylesheet;

 ans = this.answer.split("_|_");
 for (i = 0; i < ans.length; i++)
 {
  ans[i] = ans[i].split("_:_");
 }

 if (this.autoarrangeansweroptions && this.type != 5)
 {
  this.cols = Math.ceil(this.options.length / 10);
  this.rows = 0;
 }

 switch (this.type)
 {
  case 1:
   this.calcrc();
   // debugger;
   size = this.rows * this.cols;

   for (i = 0; i < ans[0].length; i++)
   {
    if (ans[0][i].length > 0)
    {
     for (j = 0; j < this.options.length; j++)
     {
      if (this.options[j].value == ans[0][i])
      {
       this.options[j].checked = true;

       if (ans.length > 1 && typeof this.options[j].open != "undefined" && typeof ans[1][i] != "undefined")
       {
        this.options[j].open = ans[1][i];
       }
      }
     }
    }
   }

   if (this.options.length < 10)
   {
    len = this.options.length;
   }
   else
   {
    len = 10;
   }

   sres += "<table border=" + this.bordersize + " class=\"question_outer\" cellpadding=\"0\" cellspacing=\"0\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";
   sres += "<tr><td align=\"center\">";

   switch (this.displaytype)
   {
    default:
    case 1:
     sres += "<table class=\"option_table\" cellpadding=\"0\" cellspacing=\"0\" border=" + this.bordersize + ">";

     i = 0;
     for (y = 0; y < this.rows; y++)
     {
      if ((y % 2) == 0)
      {
       oddOrEven = "option_row_even";
      }
      else
      {
       oddOrEven = "option_row_odd";
      }

      sres += "<tr class=\"option_row " + oddOrEven + "\">";
      for (x = 0; x < size; x += this.rows)
      {
       if ((x + y) < this.options.length)
       {
        this.options[x + y].index = i++;
        if (!this.options[x + y].disabled) sres += this.options[x + y].getHTML(1); //+"<td>&nbsp;</td>";
       }
       //      else
       //      {
       //      sres += "<td colspan=2>&nbsp;</td><td>&nbsp;</td>";
       //      }
      }
      if (this.cols > 1 && y == this.rows - 1 && (this.options.length % 2) != 0)
       sres += "<td class=\"answer_option_cell\">&nbsp;</td>";
      sres += "</tr>";
     }
     sres += "</table>";
     break;
    case 5:
     sres += "<select name=" + this.label + " size=1>";
     sres += "<option></option>";
     for (j = 0; j < this.options.length; j++)
     {
      if (!this.options[j].disabled) sres += this.options[j].getHTML(5);
     }
     sres += "</select>";
     break;
   }

   sres += "</td></tr>";
   sres += "</table>";
   break;
  case 2:
   this.calcrc();
   size = this.rows * this.cols;

   for (i = 0; i < ans[0].length; i++)
   {
    if (ans[0][i].length > 0)
    {
     for (j = 0; j < this.options.length; j++)
     {
      if (this.options[j].value == ans[0][i])
      {
       this.options[j].checked = true;

       if (ans.length > 1 && typeof this.options[j].open != "undefined" && typeof ans[1][i] != "undefined")
       {
        this.options[j].open = ans[1][i];
       }
      }
     }
    }
   }

   if (this.options.length < 10)
   {
    len = this.options.length;
   }
   else
   {
    len = 10;
   }

   sres += "<table border=" + this.bordersize + " class=\"question_outer\" cellpadding=\"0\" cellspacing=\"0\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";
   sres += "<tr><td align=\"center\">";

   switch (this.displaytype)
   {
    default:
    case 1:
     sres += "<table class=\"option_table\" cellspacing=\"0\" cellpadding=\"0\" border=" + this.bordersize + ">";

     i = 0;
     for (y = 0; y < this.rows; y++)
     {
      if ((y % 2) == 0)
      {
       oddOrEven = "option_row_even";
      }
      else
      {
       oddOrEven = "option_row_odd";
      }

      sres += "<tr class=\"option_row " + oddOrEven + "\">";
      for (x = 0; x < size; x += this.rows)
      {
       if ((x + y) < this.options.length)
       {
        this.options[x + y].index = i++;
        if (!this.options[x + y].disabled) sres += this.options[x + y].getHTML(3); //+"<td>&nbsp;</td>";
       }
       //      else
       //      {
       //      sres += "<td colspan=2>&nbsp;</td><td>&nbsp;</td>";
       //      }
      }
      if (this.cols > 1 && y == this.rows - 1 && (this.options.length % 2) != 0)
       sres += "<td class=\"answer_option_cell\">&nbsp;</td>";
      sres += "</tr>";
     }
     sres += "</table>";
     break;
    case 5:
     sres += "<select name=" + this.label + " size=" + len + " multiple>";
     for (j = 0; j < this.options.length; j++)
     {
      if (!this.options[j].disabled) sres += this.options[j].getHTML(5);
     }
     sres += "</select>";
     break;
   }

   sres += "</td></tr>";
   sres += "</table>";
   break;
  case 3:
  case 4:
   sres += "<table border=" + this.bordersize + " class=\"question_outer\" cellspacing=\"0\" cellpadding=\"0\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";
   sres += "<tr><td align=\"center\" class=\"question_content\">";
   sres += "<input ";
   sres += "type=\"text\" ";
   sres += "name=\"" + this.label + "\" ";

   if (this.size > 0) sres += "size=" + this.size + " ";
   if (this.maxlength > 0) sres += "maxlength=" + this.maxlength + " ";

   sres += "value=\"" + this.answer + "\">&nbsp;" + this.unit;

   sres += "</td></tr></table>";
   break;
  case 5:
   if (this.options.length == 0)
   {
    if (this.rows == 0)
     widthOpen = 8;
    else
     widthOpen = this.rows;
    if (this.cols == 0)
     heigthOpen = 55;
    else
     heigthOpen = this.cols;
   }
   else
   {
    widthOpen = 8;
    heigthOpen = 55;
   }

   for (i = 0; i < this.options.length; i++)
   {
    for (j = 0; j < ans[1].length; j++)
    {
     if (ans[1][j] == this.options[i].value) this.options[i].checked = true;
    }
   }

   sres += "<table border=" + this.bordersize + " class=\"question_outer\" cellspacing=\"0\" cellpadding=\"0\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";
   sres += "<tr><td align=\"left\">";
   sres += "<textarea name=\"" + this.label + "\" ";
   sres += "cols=" + heigthOpen + " rows=" + widthOpen;

   if (ans[1] == "" && ans[1].length == 1)
   {
    sres += ">" + ans[0][0];
   }
   else
   {
    sres += " disabled>";
   }

   sres += "</textarea>";
   sres += "</td></tr>";
   //   debugger;
   if (this.options.length > 0)
   {
    sres += "<tr><td>";
    sres += "<table class=\"option_table\" cellspacing=\"0\" cellpadding=\"0\" border=" + this.bordersize + ">";
    for (i = 0; i < this.options.length; i++)
    {
     this.options[i].label = this.label + ".Closed";
    }
    if (this.autoarrangeansweroptions == true)
    {
     this.cols = Math.ceil(this.options.length / 10);
     this.rows = 0;
    }
    this.calcrc();
    size = this.rows * this.cols;
    i = 0;
    for (y = 0; y < this.rows; y++)
    {
     if ((y % 2) == 0)
     {
      oddOrEven = "option_row_even";
     }
     else
     {
      oddOrEven = "option_row_odd";
     }

     sres += "<tr class=\"option_row " + oddOrEven + "\">";
     for (x = 0; x < size; x += this.rows)
     {
      if ((x + y) < this.options.length)
      {
       this.options[x + y].index = i++;
       if (!this.options[x + y].disabled)
        sres += this.options[x + y].getHTML(3);
      }
      else
      {
       sres += "<td colspan=2>&nbsp;</td><td>&nbsp;</td>";
      }
     }
     sres += "</tr>";
    }
    sres += "</table>";
    sres += "</td></tr>";
   }
   sres += "</table>";
   break;
  case 6:
   // debugger;
   for (i = 0; i < this.questions.length; i++)
   {
    gridnumber = this.questions[i].label.split(".");
    gridnumber = gridnumber[gridnumber.length - 1];

    for (j = 0; j < ans.length; j++)
    {
     if (ans[j][0] == gridnumber)
     {
      break;
     }
    }

    for (k = 1; k < ans[j].length; k++)
    {
     if (ans[j][k].length > 0)
     {
      for (l = 0; l < this.questions[i].options.length; l++)
      {
       if (this.questions[i].options[l].value == ans[j][k])
       {
        this.questions[i].options[l].checked = true;
       }
      }
     }
    }
   }

   if (this.options.length < 5)
   {
    len = this.options.length;
   } else
   {
    len = 5;
   }

   this.bordersize = 0;

   sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 class=\"grid_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   if (this.text) sres += "<tr><td id=\"grid_question_text\">" + this.text + "</td></tr>";
   sres += "<tr><td align=\"center\">";

   switch (this.displaytype)
   {
    default:
    case 1:
     this.bordersize = 0;

     sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 class=\"grid_inner\">";
     if (this.gridcolumns.length > 1)
     {
      sres += "<tr>";
      for (j = 0; j < this.gridcolumns.length; j++)
      {
       if (this.questions.length > 0)
        sres +=
         "<td rowspan=\"2\">&nbsp;</td>" +
         "<td colspan=\"" + this.questions[0].options.length + "\">" +
         this.gridcolumns[j] +
         "</td>";

       if (j < (this.gridcolumns.length - 1))
       {
        sres += "<td style=\"width: 30px;\" rowspan=\"" + (2 + Math.ceil(this.questions.length / this.gridcolumns.length)) + "\">&nbsp;</td>";
       }
      }
      sres += "</tr>";
     }


     sres += "<tr>";
     if (this.gridcolumns.length <= 1)
     {
      sres += "<td class=\"grid_empty_cell\" nobr>&nbsp;</td>";
     }
     for (j = 0; j < this.gridcolumns.length; j++)
     {
      if (this.questions.length > 0)
      {
       for (i = 0; i < this.questions[0].options.length; i++)
       {
        sres +=
         "<td id=\"grid_answeroption_text_" + (i + 1) + "\" align=\"center\" class=\"grid_answeroption_text\">" +
         ((this.nolinebreak) ? "<nobr>" : "") +
         this.questions[0].options[i].text +
         ((this.nolinebreak) ? "</nobr>" : "") +
         "</td>";
       }
      }
     }
     sres += "</tr>";

     l = 0;
     for (i = 0; i < Math.ceil(this.questions.length / this.gridcolumns.length); i++)
     {
      if (this.questions[i].visible)
      {
       sres += "<tr>";
       for (j = 0; j < this.gridcolumns.length; j++)
       {
        theIndex = i + j * Math.ceil(this.questions.length / this.gridcolumns.length);

        if (l % 2 == 0)
        {
         oddOrEven = "grid_subquestion_even";
        }
        else
        {
         oddOrEven = "grid_subquestion_odd";
        }

        if (theIndex < this.questions.length)
        {
         sres +=
         "<td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text " + oddOrEven + "\">" +
         this.questions[theIndex].text +
         "</td>";

         for (k = 0; k < this.questions[theIndex].options.length; k++)
         {
          sres += this.questions[theIndex].options[k].getHTML(2).replace(/<td/i, "<td class=\"" + oddOrEven + "\"");
         }
        }
        else
        {
         sres += "<td colspan=\"" + (this.questions[0].options.length + this.gridcolumns.length) + "\">&nbsp;</td>";
        }
       }
       sres += "</tr>";

       l++;
      }
     }
     sres += "</table>";

     break;
    case 5:
     sres += "<table class=\"grid_outer\" border=" + this.bordersize + " >";
     for (i = 0; i < this.questions.length; i++)
     {
      if (i % 2 == 0)
      {
       oddOrEven = "grid_subquestion_even";
      }
      else
      {
       oddOrEven = "grid_subquestion_odd";
      }

      if (this.questions[i].visible)
      {
       sres += "<tr><td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text " + oddOrEven + "\">" + this.questions[i].text + "</td>";

       sres += "<td><select name=" + this.questions[i].label + " size=1>";
       sres += "<option></option>";
       for (j = 0; j < this.questions[i].options.length; j++)
       {
        sres += this.questions[i].options[j].getHTML(5).replace(/<td/i, "<td class=\"" + oddOrEven + "\"");
       }
       sres += "</select></td>";

       sres += "</tr>";
      }
     }
     sres += "</table>";
     break;
   }

   sres += "</td></tr>";
   sres += "</table>";
   break;
  case 7:
   for (i = 0; i < this.questions.length; i++)
   {
    gridnumber = this.questions[i].label.split(".");
    gridnumber = gridnumber[gridnumber.length - 1];

    for (j = 0; j < ans.length; j++)
    {
     if (ans[j][0] == gridnumber)
     {
      break;
     }
    }

    for (k = 1; k < ans[j].length; k++)
    {
     if (ans[j][k].length > 0)
     {
      for (l = 0; l < this.questions[i].options.length; l++)
      {
       if (this.questions[i].options[l].value == ans[j][k])
       {
        this.questions[i].options[l].checked = true;
       }
      }
     }
    }
   }

   if (this.options.length < 5)
   {
    len = this.options.length;
   } else
   {
    len = 5;
   }

   this.bordersize = 0;

   sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 class=\"grid_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   if (this.text)
   {
    sres += "<tr><td id=\"grid_question_text\">" + this.text + "</td></tr>";
   }
   sres += "<tr><td align=\"center\">";

   switch (this.displaytype)
   {
    default:
    case 1:
     this.bordersize = 0;

     sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 class=\"grid_inner\">";
     if (this.gridcolumns.length > 1)
     {
      sres += "<tr>";
      for (j = 0; j < this.gridcolumns.length; j++)
      {
       if (this.questions.length > 0)
        sres +=
         "<td rowspan=\"2\">&nbsp;</td>" +
         "<td colspan=\"" + this.questions[0].options.length + "\">" +
         this.gridcolumns[j] +
         "</td>";

       if (j < (this.gridcolumns.length - 1))
       {
        sres += "<td style=\"width: 30px;\" rowspan=\"" + (2 + Math.ceil(this.questions.length / this.gridcolumns.length)) + "\">&nbsp;</td>";
       }
      }
      sres += "</tr>";
     }

     sres += "<tr>";
     if (this.gridcolumns.length <= 1)
     {
      sres += "<td class=\"grid_empty_cell\" nobr>&nbsp;</td>";
     }
     for (j = 0; j < this.gridcolumns.length; j++)
     {
      if (this.questions.length > 0)
      {
       for (i = 0; i < this.questions[0].options.length; i++)
       {
        sres +=
         "<td id=\"grid_answeroption_text_" + (i + 1) + "\" align=\"center\" class=\"grid_answeroption_text\">" +
         ((this.nolinebreak) ? "<nobr>" : "") +
         this.questions[0].options[i].text +
         ((this.nolinebreak) ? "</nobr>" : "") +
         "</td>";
       }
      }
     }
     sres += "</tr>";

     l = 0;
     for (i = 0; i < Math.ceil(this.questions.length / this.gridcolumns.length); i++)
     {
      if (l % 2 == 0)
      {
       oddOrEven = "grid_subquestion_even";
      }
      else
      {
       oddOrEven = "grid_subquestion_odd";
      }

      if (this.questions[i].visible)
      {
       sres += "<tr>";
       for (j = 0; j < this.gridcolumns.length; j++)
       {
        theIndex = i + j * Math.ceil(this.questions.length / this.gridcolumns.length);

        if (theIndex < this.questions.length)
        {
         sres +=
         "<td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text " + oddOrEven + "\">" +
         this.questions[theIndex].text +
         "</td>";

         for (k = 0; k < this.questions[theIndex].options.length; k++)
         {
          sres += this.questions[theIndex].options[k].getHTML(4).replace(/<td/i, "<td class=\"" + oddOrEven + "\"");
         }
        }
        else
        {
         sres += "<td colspan=\"" + (this.questions[0].options.length + this.gridcolumns.length) + "\">&nbsp;</td>";
        }
       }
       sres += "</tr>";

       l++;
      }
     }

     sres += "</table>";
     break;
    case 5:
     sres += "<table border=" + this.bordersize + " cellspacing=\"0\" cellpadding=\"0\">";
     sres += "<tr>";
     for (i = 0; i < this.questions.length; i++)
     {
      if (i % 2 == 0)
      {
       oddOrEven = "grid_subquestion_even";
      }
      else
      {
       oddOrEven = "grid_subquestion_odd";
      }

      sres += "<td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text " + oddOrEven + "\">" + this.questions[i].text + "</td>";
     }
     sres += "</tr><tr>";
     for (i = 0; i < this.questions.length; i++)
     {
      if (this.questions[i].visible)
      {
       sres += "<td align=\"center\"><select name=" + this.questions[i].label + " size=" + len + " multiple>";
       for (j = 0; j < this.questions[i].options.length; j++)
       {
        sres += this.questions[i].options[j].getHTML(5);
       }
       sres += "</select></td>";
      }
     }
     sres += "</tr>";
     sres += "</table>";
     break;
   }

   sres += "</td></tr>";
   sres += "</table>";
   break;
  case 8:
   for (i = 0; i < this.questions.length; i++)
   {
    gridnumber = this.questions[i].label.split(".");
    gridnumber = gridnumber[gridnumber.length - 1];

    for (j = 0; j < ans.length; j++)
    {
     if (ans[j][0] == gridnumber)
     {
      this.questions[i].answer = ans[j][1];
      break;
     }
    }
   }

   this.bordersize = 0;

   sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 class=\"grid_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   if (this.text)
   {
    sres += "<tr><td id=\"grid_question_text\">" + this.text + "</td></tr>";
   }
   sres += "<tr><td>";
   sres += "<table border=" + this.bordersize + " width=\"100%\" cellspacing=0 cellpadding=0 class=\"grid_inner\">";

   if (this.gridcolumns.length > 1)
   {
    sres += "<tr>";
    for (i = 0; i < this.gridcolumns.length; i++)
    {
     sres += "<td></td>";
     sres += "<td align=\"center\">" + this.gridcolumns[i] + "</td>";

     if (i < this.gridcolumns.length)
     {
      sres += "<td style=\"width: 30px;\" rowspan=\"" + (Math.ceil(this.questions.length / this.gridcolumns.length) + 1) + "\"></td>";
     }
    }
    sres += "</tr>";
   }

   l = 0;
   for (i = 0; i < Math.ceil(this.questions.length / this.gridcolumns.length); i++)
   {
    if (l % 2 == 0)
    {
     oddOrEven = "grid_subquestion_even";
    }
    else
    {
     oddOrEven = "grid_subquestion_odd";
    }

    if (this.questions[i].visible)
    {
     sres += "<tr>";
     for (j = 0; j < this.gridcolumns.length; j++)
     {
      theIndex = i + j * Math.ceil(this.questions.length / this.gridcolumns.length);

      if (theIndex < this.questions.length)
      {
       sres +=
      "<td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text " + oddOrEven + "\">" +
      this.questions[theIndex].text +
      "</td>";

       sres += "<td valign=\"top\" width=\"1*\" class=\"" + oddOrEven + "\">";
       sres += "<input ";
       sres += "type=\"text\" ";
       sres += "name=\"" + this.questions[theIndex].label + "\" ";

       if (this.questions[i].size > 0)
       {
        sres += "size=" + this.questions[theIndex].size + " ";
       } else if (this.size > 0)
       {
        sres += "size=" + this.size + " ";
       }

       if (this.questions[i].maxlength > 0)
       {
        sres += "maxlength=" + this.questions[theIndex].maxlength + " ";
       } else if (this.maxlength > 0)
       {
        sres += "maxlength=" + this.maxlength + " ";
       }

       // If sub question is allow numeric and allow float then
       // based on user's culture, decimal seperator could be "," or "."
       if (this.questions[theIndex].answertype == 2 && this.questions[theIndex].allowfloat == true && this.numberDecimalSeparator == ",")
       {
        sres += "value=\"" + this.questions[theIndex].answer.trim().replace(".", ",") + "\">";
       }
       else
        sres += "value=\"" + this.questions[theIndex].answer + "\">";

       if (this.questions[i].unit != "")
       {
        sres += "&nbsp;" + this.questions[theIndex].unit + "&nbsp;";
       }
       else if (this.questions[theIndex].unit == "" && this.unit != "")
       {
        sres += "&nbsp;" + this.unit + "&nbsp;";
       }

       sres += "</td>";
      }
      else
      {
       sres += "<td colspan=\"2\">&nbsp;</td>";
      }
     }
     sres += "</tr>";
    }

    l++;
   }
   sres += "</table>";

   sres += "</td></tr>";
   sres += "</table>";
   break;
  default:
  case 9:
   sres += "<table border=" + this.bordersize + " class=\"question_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"page_question_text\">" + this.text + "</td></tr>";
   sres += "</table>";
   break;
  case 10:
   sres += "<table border=" + this.bordersize + " class=\"question_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";

   sres += "<tr><td class=\"multimedia_question_content\">";
   sres += this.mm.getHTML();
   sres += "</td></tr>";
   sres += "</table>";
   break;
  case 11:
   this.so.name = this.label + ".so";

   if (this.answer != "" && !isNaN(this.answer))
   {
    this.so.value = parseFloat(this.answer);
   }

   sres += "<table border=" + this.bordersize + " class=\"question_outer\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"question_text\">" + this.text + "</td></tr>";
   sres += "<tr>";
   sres += "<td align=\"center\" class=\"question_content\">" + this.so.toHTML() + "</td>";
   sres += "</tr>";
   sres += "</table>";
   break;
  case 12:
   for (i = 0; i < this.questions.length; i++)
   {
    gridnumber = this.questions[i].label.split(".");
    gridnumber = gridnumber[gridnumber.length - 1];

    for (j = 0; j < ans.length; j++)
    {
     if (ans[j][0] == gridnumber)
     {
      this.questions[i].answer = ans[j][1];
      this.questions[i].so.value = ans[j][1];
      break;
     }
    }

   }

   this.bordersize = 0;

   sres += "<table border=" + this.bordersize + " class=\"grid_outer\" cellspacing=\"0\" cellpadding=\"0\">";
   if (this.countdown > 0 && this.showcountdowndisplay)
   {
    sres += "<tr><td><div id=\"countdowndisplay\"></div></td></tr>";
   }
   sres += "<tr><td id=\"grid_question_text\">" + this.text + "</td></tr>";

   sres += "<tr><td>";
   sres += "<table border=" + this.bordersize + " cellspacing=0 cellpadding=0 width=\"100%\" class=\"grid_inner\">";

   if (this.so.textposition == SCALE_ABOVE_TEXTPOS)
   {
    sres += "<tr><td>&nbsp;</td>";
    sres += "<td>";
    sres += "<table border=0 width=\"100%\" cellspacing=0><tr>";
    sres += "<td width=\"50%\" align=\"left\"><nobr>" + this.so.minimumtext + "</nobr></td>";
    sres += "<td width=\"50%\" align=\"right\"><nobr>" + this.so.maximumtext + "</nobr></td>";
    sres += "</tr></table>";
    sres += "</td></tr>";
   }

   for (i = 0; i < this.questions.length; i++)
   {
    sres += "<tr>" +
         "<td id=\"grid_subquestion_text_" + (i + 1) + "\" class=\"grid_subquestion_text\">" + this.questions[i].text + "</td>" +
         "<td align=\"center\">" + this.questions[i].so.toHTML() + "</td>" +
      "</tr>";
   }
   sres += "</table>" +
      "</td></tr>" +
      "</table>";
   break;
 }

 if (this.sound)
 {
  sres += "<applet code=\"SoundPlayer2.class\"";
  sres += "    codebase=\"VoiceOverText/\"";
  sres += "    name   = \"SoundPlayer2\"";
  sres += "    id  = \"SoundPlayer2\"";
  sres += "    width  = 0";
  sres += "    height = 0";
  sres += "    mayscript>";
  sres += "<param name=\"files\" value=\"" + this.sound + "\">";
  sres += "<param name=\"path\" value=\"\">";
  sres += "<param name=\"callBackMethod\" value=\"\">";
  sres += "   No applet !!!";
  sres += "</applet>";
 }

 // A little answer retrieval hack ;)
 switch (this.type)
 {
  case 1:
  case 2:
  case 10:
  case 11:
   sres += "<input type=\"hidden\" name=\"" + this.label + "\" value=\"\">";
   break;
  case 5:
   //    sres += "<input type=\"hidden\" name=\""+this.label+".Closed\" value=\"\">";
   break;
  case 6:
  case 7:
  case 12:
   for (i = 0; i < quest.questions.length; i++)
   {
    sres += "<input type=\"hidden\" name=\"" + this.questions[i].label + "\" value=\"\">";
   }
   break;
 }

 // DEBUGINFO
 //sres += "<hr><textarea rows=\"8\" cols=\"55\">" + sres.replace(/textarea/ig, "ta") + "</textarea><hr>";

 return sres;
}

question.prototype.onCountdown = function()
{
 //this.next();
 if (this.countdown != null && this.countdown > 0)
 {
  this.countdown--;
  this.countDownObj.value--;
  this.countDownObj.render();
  if (this.countdown == 0)
  {
   // Disable the timed trigger
   window.clearInterval(this.countdownHandle);

   // Go to next question
   buttonsStatus(true);
   if (quest.nextvisible)
   {
    document["query"]["dir"].value = "next";
   }
   else if (quest.closevisible)
   {
    document["query"]["dir"].value = "close";
   }
   else
   {
    document["query"]["dir"].value = "next";
   }

   document["query"].submit();
  }
 }
}

question.prototype.onInit = function()
{
}

question.prototype.init = function()
{
 var i;
 // if (this.sound) SoundPlayer2.playFile("0");

 if (this.countdown >= 0)
 {
  // Enable the timed trigger
  this.countDownObj = new countDown(document.getElementById("countdowndisplay"), this.countdown);
  this.countDownObj.width = 400;
  this.countDownObj.typeWidthUnit = "px";
  this.countDownObj.height = 15;
  this.countDownObj.typeHeightUnit = "px";
  this.countDownObj.render();
  this.countdownHandle = window.setInterval(this.reference + ".onCountdown();", 1000);
 }

 switch (this.type)
 {
  case 1:
  case 2:
  case 9:
   if (quest.nextvisible)
   {
    document["query"]["next"].focus();
   }
   else if (quest.closevisible)
   {
    document["query"]["close"].focus();
   }
   break;
  case 3:
  case 4:
  case 5:
   if (!document["query"][this.label].disabled)
   {
    document["query"][this.label].focus();
   }
   break;
  case 8:
   if (this.questions.length > 0)
   {
    for (i = 0; i < this.questions.length; i++)
    {
     if (this.questions[i].visible)
     {
      document["query"][this.questions[i].label].focus();
      break;
     }
    }
   }
   break;
  case 10:
   this.mm.init();
   break;
  case 11:
   this.so.init();
   break;
  case 12:
   for (i = 0; i < this.questions.length; i++)
   {
    this.questions[i].so.init();
   }
   break;
  default:
   break;
 }

 try // Put try-catch here to cath "access denied" exception. When using questionnaire viewer in another site then parent.document can not be access.
   {
  if (parent.self != self) {
   if (typeof (parent.NewQuestionParsed) != "undefined") {
    parent.NewQuestionParsed(quest.label.substr(9));
   }

   var url = parent.document.location.toString();
   var url_parts = url.split("/"); url_parts = url_parts[url_parts.length - 1].split("?");
   var page = url_parts[0];
   var qlist = parent.document.getElementById("ddlQuestion");
   for (i = 0; i < qlist.length; i++)
   {
    if (quest.label == "QUESTION." + qlist[i].text)
    {
     qlist[i].selected = true;
     //Set status for button on Toolbar Navigation, should use correct check about last/firsr question better than quest.nextvisible / quest.backvisible.
     if (typeof (parent.setStatusForToolbarNavigation) != "undefined")
      parent.setStatusForToolbarNavigation(quest.nextvisible, quest.backvisible);
     break;
    }
   }
   //Update the language in Previewer-LanguageSelector if user cho language from Qnaire Viewer
   if (parent.document.getElementById("ddlLanguage") != null && self.document.getElementById("languageSelector") != null)
    parent.document.getElementById("ddlLanguage").value = self.document.getElementById("languageSelector").value;
  }
 }
 catch (e)
 {
  // This catch is allowed to be empty, because half open questions
  // have a textbox on the side 
 }

 this.onInit();
}

question.prototype.uninit = function()
{
 if (parent.self == self)
 {
  if (document["query"]["dir"].value == "" && this.end && this.redirectionurl != "")
  {
   openWindow(this.redirectionurl, "", 800, 600);
  }
 }

 switch (this.type)
 {
  case 10:
   this.mm.stop();
  default:
   break;
 }
}

/* -------------------------------------------------------------------------------------------- */

/**   event handlers */
function optclick(slbl, lidx, blnk)
{
 var qao, i, cb, o1, o2, o3, val;

 cb = new Array();
 o1 = document["query"][slbl];

 if (o1.type != "checkbox" && o1.type != "radio")
 {
  cb = o1;
 } else
 {
  cb[0] = o1;
 }

 if (quest.type <= 5)
 {
  qao = quest.options;
 }
 else
 {
  for (i = 0; i < quest.questions.length; i++)
  {
   if (quest.questions[i].label == slbl)
   {
    qao = quest.questions[i].options;
    break;
   }
  }
 }

 val = cb[lidx].value;
 o2 = document["query"][slbl + ".Open." + val];

 if (blnk)
 {
  if (cb[lidx].type == "checkbox")
  {
   cb[lidx].checked = !cb[lidx].checked;
  } else
  {
   cb[lidx].checked = true;
  }
 }

 if ((typeof o2) != "undefined") 
 {
    if (cb[lidx].checked) {
    o2.disabled = false;
    o2.focus();
    } else {
    o2.value = "";
    o2.disabled = true;
    }
 }

 // Open features
 if (quest.type == 5)
 {
  document["query"][quest.label].disabled = false;

  for (i = 0; i < cb.length; i++)
  {
   if (cb[i].checked)
   {
    if (!document["query"][quest.label].value == "")
    {
     document["query"]["ans"].value = document["query"][quest.label].value;
     document["query"][quest.label].value = "";
    }
    document["query"][quest.label].disabled = true;
    break;
   }
  }

  if (!document["query"][quest.label].disabled)
  {
   document["query"][quest.label].value = document["query"]["ans"].value;
   document["query"][quest.label].focus();
  }
 }

 // Singleoption
 for (i = 0; i < qao.length; i++)
 {
    o3 = document["query"][slbl + ".Open." + qao[i].value];
  if (qao[i].index == lidx)
  {
   if (qao[i].single && cb[lidx].checked)
   {
    for (j = 0; j < cb.length; j++)
    {
     if (j != lidx && cb[j].checked)
      cb[j].checked = false;
    }
   }
   else
   {
    for (j = 0; j < qao.length; j++)
    {
     if (qao[j].single)
      cb[qao[j].index].checked = false;
    }
   }
  }
  else if ((typeof o3) != "undefined" && quest.type == 1)
  {
   o3.value = "";
   o3.disabled = true;
  }   
 }
}

function questioncheck()
{
 var cnt, acnt, cont, acont, msg, mmin, mmax, tmp;

 cnt = 0;
 cont = false;

 ErrorMessages.getInstance().clearErrorMessages();
 switch (quest.type)
 {
  case 1:
  case 2:
   var ignoreMinNumberOfAnswerOptionCheck = false;
   if (typeof document["query"][quest.label].length != "undefined")
   {
    for (i = 0; i < document["query"][quest.label].length; i++)
    {
     if (document["query"][quest.label][i].checked) cnt++;
     cont |= document["query"][quest.label][i].checked;

     //Check if checked open answer option does not contain blank value.
     if (document["query"][quest.label][i].value != "") //check i f item is an answer option
      for (var j = 0; j < quest.options.length; j++)
     {
      if (document["query"][quest.label][i].value == quest.options[j].value //check input item and answer option item has the same value
      && typeof (quest.options[j].open) != "undefined"
      && typeof (quest.openanswerrequired) != "undefined" && quest.openanswerrequired == "true"
      && document["query"][quest.label][i].checked
      && document["query"][quest.options[i].label + ".Open." + quest.options[j].value].value == "")
      {

       ErrorMessages.getInstance().showErrorMessage(quest.requiredtext);
       return false;
      }
      //Check if user select an answer option which is active "No_multi" and question.properties has property "Minimum number of answer option"
      //If  No_multi answer option is checked then ignore minimum number of answer option
      if (document["query"][quest.label][i].value == quest.options[j].value
      && quest.options[j].single == true
      && document["query"][quest.label][i].checked)

       ignoreMinNumberOfAnswerOptionCheck = true;
     }
    }

   } else
   {
    cont = document["query"][quest.label].checked;
   }
   //Check min and max number of answer options.
   if (quest.type == 2)
   {
    if (quest.min != null && quest.min > cnt && !ignoreMinNumberOfAnswerOptionCheck)
    {
     ErrorMessages.getInstance().showErrorMessage(quest.minrequiredtext.replace(/\[\[x\]\]/ig, quest.min));
     return false;
    }
    else if (quest.max != null && quest.max < cnt)
    {
     ErrorMessages.getInstance().showErrorMessage(quest.maxrequiredtext.replace(/\[\[x\]\]/ig, quest.max));
     return false;
    }
   }

   break;
  case 3:
   var value = trim(document["query"][quest.label].value);
   if (value != "")
   {
    //Validate Number question , allow negative value
    var regex;
    if (quest.numberDecimalSeparator == ",")
     regex = /^\d+$|^\d+,\d{1,}$|^-\d+$|^-\d+,\d{1,}$/;
    else
     regex = /^\d+$|^\d+\.\d{1,}$|^-\d+$|^-\d+\.\d{1,}$/;

    if (document["query"][quest.label].value.match(regex) == null)
    {
     //alert(quest.numberrequiredtext);
     ErrorMessages.getInstance().showErrorMessage(quest.numberrequiredtext);
     return false;
    }

    if (value.indexOf(",") >= 0)
     value = value.replace(",", ".");

    cnt = parseFloat(value);

    if (quest.min != null && quest.min > cnt)
    {
     //alert(quest.minvalrequiredtext.replace(/\[\[x\]\]/ig, quest.min));
     ErrorMessages.getInstance().showErrorMessage(quest.minvalrequiredtext.replace(/\[\[x\]\]/ig, quest.min));
     return false;
    }
    else if (quest.max != null && quest.max < cnt)
    {
     //alert(quest.maxvalrequiredtext.replace(/\[\[x\]\]/ig, quest.max));
     ErrorMessages.getInstance().showErrorMessage(quest.maxvalrequiredtext.replace(/\[\[x\]\]/ig, quest.max));
     return false;
    }
    else if (cnt > 1E+14)
    {
     //alert(quest.numberoverflow);
     ErrorMessages.getInstance().showErrorMessage(quest.numberoverflow);
     return false;
    }

    if (!quest.allowfloat && Math.round(cnt) != cnt)
    {
     //alert(quest.nofloatvaltext);
     ErrorMessages.getInstance().showErrorMessage(quest.nofloatvaltext);
     return false;
    }

    cont = true;
   }

   break;
  case 4:
   cont = (trim(document["query"][quest.label].value) != "");

   //Validate email if user specified to check the question text. 
   if (typeof (quest.validateEmail) == "boolean" && quest.validateEmail == true)
   {
    var isEmailValid = false;

    if (typeof (quest.emailValidationRegex) == "string" && quest.emailValidationRegex != "")
     isEmailValid = validateEmail(document["query"][quest.label].value, quest.emailValidationRegex);
    else
     isEmailValid = validateEmail(document["query"][quest.label].value);

    if (!isEmailValid)
    {
     ErrorMessages.getInstance().showErrorMessage("Invalid email!!!");
     return false;
    }
   }

   break;
  case 5:
   cont = (trim(document["query"][quest.label].value) != "");

   if (quest.options.length > 0)
   {
    if (quest.options.length > 1)
    {
     cnt = 0;
     for (i = 0; i < document["query"][quest.label + ".Closed"].length; i++)
     {
      if (document["query"][quest.label + ".Closed"][i].checked)
       cnt++;

      cont |= document["query"][quest.label + ".Closed"][i].checked;
     }
    }
    else
    {
     cnt = 1;
     cont |= document["query"][quest.label + ".Closed"].checked;
    }
   }

   if (quest.min != null && quest.min > cnt)
   {
    //alert(quest.minrequiredtext.replace(/\[\[x\]\]/ig, quest.min));
    ErrorMessages.getInstance().showErrorMessage(quest.minrequiredtext.replace(/\[\[x\]\]/ig, quest.min));
    return false;
   }
   else if (quest.max != null && quest.max < cnt)
   {
    //alert(quest.maxrequiredtext.replace(/\[\[x\]\]/ig, quest.max));
    ErrorMessages.getInstance().showErrorMessage(quest.maxrequiredtext.replace(/\[\[x\]\]/ig, quest.max));
    return false;
   }

   break;
  case 6:
  case 7:
   acnt = new Array();
   acont = new Array();
   mmin = ""; mmax = ""; msg = "";

   for (i = 0; i < quest.questions.length; i++)
   {
    if (quest.questions[i].visible)
    {
     acnt[i] = 0;
     acont[i] = false;

     for (j = 0; j < document["query"][quest.questions[i].label].length; j++)
     {
      if (document["query"][quest.questions[i].label][j].checked) acnt[i]++;

      acont[i] |= document["query"][quest.questions[i].label][j].checked;
     }
    }
    else
    {
     acont[i] = true;
    }
   }

   cont = true;

   if (quest.type == 7)
   {
    tmp = "";

    for (i = 0; i < quest.questions.length; i++)
    {
     if (quest.questions[i].visible)
     {
      var ignoreMinNumberOfAnswerOptionCheck = false;
      for (var j = 0; j < quest.questions[i].options.length; j++)
      {
       if (quest.questions[i].options[j].single && document["query"][quest.questions[i].label][j].checked)
        ignoreMinNumberOfAnswerOptionCheck = true;
      }

      if (quest.questions[i].required && quest.questions[i].min != null && quest.questions[i].min > acnt[i] && !ignoreMinNumberOfAnswerOptionCheck)
      {
       tmp = quest.questions[i].text;
       tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
       tmp = tmp.replace(/&nbsp;/ig, " ");
       mmin += " - '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
       cont = false;
      }
      else if (quest.questions[i].required && quest.questions[i].max != null && quest.questions[i].max < acnt[i])
      {
       tmp = quest.questions[i].text;
       tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
       tmp = tmp.replace(/&nbsp;/ig, " ");
       mmax += " - '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
       cont = false;
      }

     }
    }

    if (mmin != "") msg += quest.miningridrequiredtext.replace(/\[\[x\]\]/ig, quest.questions[0].min) + "\n" + mmin;
    if (msg != "") msg += "\n";
    if (mmax != "") msg += quest.maxingridrequiredtext.replace(/\[\[x\]\]/ig, quest.questions[0].max) + "\n" + mmax;

    if (!cont)
    {
     //alert(msg);
     ErrorMessages.getInstance().showErrorMessage(msg);
     return false;
    }
   }

   msg = quest.ingridrequiredtext + "\n";
   for (i = 0; i < quest.questions.length; i++)
   {
    if (quest.questions[i].required && !acont[i])
    {
     tmp = quest.questions[i].text;
     tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
     tmp = tmp.replace(/&nbsp;/ig, " ");
     msg += " - '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
     cont = false;
    }
   }

   if (quest.checkansweruniqueness)
   {
    var singleValues = new Array();
    if (quest.answeruniquenessoptions != "")
     singleValues = quest.answeruniquenessoptions.split(",");

    // Method is defined in CatGlobe_Questionnaire_Utils.js
    if (!ValidateUniqueness(quest, singleValues))
    {
     cont = false;
     msg = quest.uniqueansweringridrequiredtext;
    }
   }

   if (!cont)
   {
    //alert(msg);
    ErrorMessages.getInstance().showErrorMessage(msg);
    return false;
   }

   break;
  case 8: // text grid
   acont = new Array();
   msg = "";
   cont = true;

   for (i = 0; i < quest.questions.length; i++)
    acont[i] = (trim(document["query"][quest.questions[i].label].value) != "");

   msg = quest.ingridrequiredtext + "\n";
   for (i = 0; i < quest.questions.length; i++)
   {
    // If the sub question is not visible or answering this
    // sub question is not answered and not required to be
    // then we continue with the next sub question
    if (!quest.questions[i].visible || (!quest.questions[i].required && !acont[i]))
     continue;

    if (quest.questions[i].required && !acont[i])
    {
     tmp = quest.questions[i].text;
     tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
     tmp = tmp.replace(/&nbsp;/ig, " ");
     msg += " - '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
     cont = false;
     continue;
    }

    // Check Numerical and Decimal answer for sub question
    if ((quest.questions[i].answertype == 2 || quest.questions[i].allowfloat))
    {
     var regex;
     if (quest.numberDecimalSeparator == ",")
      regex = /^\d+$|^\d+,\d{1,}$|^-\d+$|^-\d+,\d{1,}$/;
     else
      regex = /^\d+$|^\d+\.\d{1,}$|^-\d+$|^-\d+\.\d{1,}$/;

     if (document["query"][quest.questions[i].label].value.match(regex) == null)
     {
      tmp = quest.questions[i].text;
      tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
      tmp = tmp.replace(/&nbsp;/ig, " ");
      msg += " - " + quest.illegaltype + " '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
      cont = false;
      continue;
     }
    }

    //Check Numerical without Decimal allow
    cnt = parseFloat(document["query"][quest.questions[i].label].value);
    if (quest.questions[i].answertype == 2 && !quest.questions[i].allowfloat
    && !isNaN(document["query"][quest.questions[i].label].value)
    && (Math.round(cnt) != cnt && !quest.questions[i].allowfloat))
    {
     tmp = quest.questions[i].text;
     tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
     tmp = tmp.replace(/&nbsp;/ig, " ");
     msg += " - " + quest.nofloatvaltext + " '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
     cont = false;
    }
   }

   if (!cont)
   {
    //alert(msg);
    ErrorMessages.getInstance().showErrorMessage(msg);
    return false;
   }

   //Validate email if user specified to check the question text.  
   if (typeof (quest.validateEmail) == "boolean" && quest.validateEmail == true
   && typeof (quest.subQuestionToValidateEmail) == "number"
   && typeof (document["query"][quest.questions[quest.subQuestionToValidateEmail].label]) != "undefined") //Check if the index of question is valid of not
   {
    var isEmailValid = false;
    if (typeof (quest.regexString) == "string" && quest.regexString != "")
     isEmailValid = validateEmail(document["query"][quest.questions[quest.subQuestionToValidateEmail].label].value, quest.regexString);
    else
     isEmailValid = validateEmail(document["query"][quest.questions[quest.subQuestionToValidateEmail].label].value);

    if (!isEmailValid)
    {
     ErrorMessages.getInstance().showErrorMessage("Invalid email!!!");
     return false;
    }
   }

   break;
  default:
  case 9:
   cont = true;
   break;
  case 11:
   cont = quest.so.isChecked();
   break;
  case 12:
   msg = "";
   cont = true;

   msg = quest.ingridrequiredtext + "\n";
   for (i = 0; i < quest.questions.length; i++)
   {
    if (!quest.questions[i].so.isChecked() && quest.questions[i].required)
    {
     tmp = quest.questions[i].text;
     tmp = tmp.replace(/(<!\-\-|\-\->)/ig, "");
     msg += " - '" + trim(tmp.replace(/<[^>]*>/ig, "")) + "'\n";
     cont = false;
    }
   }

   if (!cont)
   {
    //alert(msg);
    ErrorMessages.getInstance().showErrorMessage(msg);
    return false;
   }

   break;
 }

 // The simple question types ends here, grids have their own question check
 if (!cont && quest.required)
 {
  //alert(quest.requiredtext);
  ErrorMessages.getInstance().showErrorMessage(quest.requiredtext);
 }

 return (cont || !quest.required);
}

function goreset()
{
 var i, j, o;

 ErrorMessages.getInstance().clearErrorMessages();

 switch (quest.type)
 {
  default:
  case 1:
  case 2:
   if (document["query"][quest.label].type == "select-one")
   {
    document["query"][quest.label].selectedIndex = 0;
   } else if (document["query"][quest.label].type == "select-multiple")
   {
    for (i = 0; i < document["query"][quest.label].length; i++)
    {
     document["query"][quest.label][i].selected = false;
    }
   } else
   {
    for (i = 0; i < document["query"][quest.label].length; i++)
    {
     document["query"][quest.label][i].checked = false;
    }
   }

   break;
  case 5:
   if (quest.options.length > 1)
   {
    for (i = 0; i < document["query"][(quest.label + "c")].length; i++)
    {
     document["query"][(quest.label + "c")][i].checked = false;
    }
   } else if (quest.options.length == 1)
   {
    document["query"][(quest.label + "c")].checked = false;
   }
  case 3:
  case 4:
   document["query"][quest.label].value = "";
   if (document["query"][quest.label].disabled)
   {
    document["query"][quest.label].disabled = false;
   }
   document["query"][quest.label].focus();
   break;
  case 6:
  case 7:
   for (i = 0; i < quest.questions.length; i++)
   {
    if (document["query"][quest.questions[i].label].type == "select-one")
    {
     document["query"][quest.questions[i].label].selectedIndex = 0;
    } else if (document["query"][quest.questions[i].label].type == "select-multiple")
    {
     for (j = 0; j < document["query"][quest.questions[i].label].length; j++)
     {
      document["query"][quest.questions[i].label][j].selected = false;
     }
    } else
    {
     for (j = 0; j < quest.questions[i].options.length; j++)
     {
      document["query"][quest.questions[i].label][j].checked = false;
     }
    }
   }
   break;
  case 8:
   for (i = 0; i < quest.questions.length; i++)
   {
    document["query"][quest.questions[i].label].value = "";
   }
   document["query"][quest.questions[0].label].focus();
   break;
  case 9:
  case 10:
   break;
  case 11:
   //alert("Reset not implemented for scale questions");
   ErrorMessages.getInstance().showErrorMessage("Reset not implemented for scale questions");
   break;
  case 12:
   //alert("Reset not implemented for scalegrid questions");
   ErrorMessages.getInstance().showErrorMessage("Reset not implemented for scalegrid questions");
   break;
 }
}

function buttonsStatus(bstate)
{
 if (quest.backvisible)
 {
  document["query"]["back"].disabled = bstate;
 }

 if (quest.nextvisible)
 {
  document["query"]["next"].disabled = bstate;
 }

 if (quest.resetvisible)
 {
  document["query"]["reset"].disabled = bstate;
 }

 if (quest.closevisible)
 {
  document["query"]["close"].disabled = bstate;
 }
}

function goclose()
{
 var bcont;

 switch (quest.type)
 {
  case 11:
   document["query"][quest.label].value = quest.so.getValue();

   break;
  case 12:
   for (i = 0; i < quest.questions.length; i++)
   {
    document["query"][quest.questions[i].label].value = quest.questions[i].so.getValue();
   }

   break;
  default:
   break;
 }

 quest.normalClose = true;

 buttonsStatus(true);
 document["query"]["dir"].value = "close";

 bcont = questioncheck();

 if (!bcont)
 {
  buttonsStatus(false);
 }
 else
 {
  document["query"].submit();
 }
}

function goback()
{
 var res, i;

 switch (quest.type)
 {
  case 11:
   document["query"][quest.label].value = quest.so.getValue();

   break;
  case 12:
   for (i = 0; i < quest.questions.length; i++)
   {
    document["query"][quest.questions[i].label].value = quest.questions[i].so.getValue();
   }

   break;
  default:
   break;
 }

 buttonsStatus(true);
 document["query"]["dir"].value = "back";
 document["query"].submit();
}

function gonext()
{
 var bcont, res, i;
 switch (quest.type)
 {
  case 11:
   document["query"][quest.label].value = quest.so.getValue();

   break;
  case 12:
   for (i = 0; i < quest.questions.length; i++)
   {
    document["query"][quest.questions[i].label].value = quest.questions[i].so.getValue();
   }

   break;
  default:
   break;
 }

 buttonsStatus(true);
 document["query"]["dir"].value = "next";

 bcont = questioncheck();
 if (!bcont)
 {
  buttonsStatus(false);
 }


 // Based on user's culture, decimal seperator could be "," or "." (decimal seperator is changed when calling quest.getHTML() )
 // but in database decimal seperator must be invariant culture which is ".";
 if (bcont && quest.type == 8)
  for (var i = 0; i < quest.questions.length; i++)
  {
   if (quest.questions[i].answertype == 2 || quest.questions[i].allowfloat)
    document["query"][quest.questions[i].label].value = document["query"][quest.questions[i].label].value.replace(",", ".");
  }

 return bcont;
}

function changelanguage()
{
 switch (quest.type)
 {
  case 11:
   document["query"][quest.label].value = quest.so.getValue();
   break;
  case 12:
   for (i = 0; i < quest.questions.length; i++)
   {
    document["query"][quest.questions[i].label].value = quest.questions[i].so.getValue();
   }
   break;
  default:
   break;
 }
 document["query"]["dir"].value = "changelanguage";
 document["query"].submit();
}

// This object below is used for generate a "randomize" number
// Project VN2399QNR 
function randomMaker(_seed, _min, _max)
{
 this.seed = _seed;
 this.m = 233280;
 this.c = 49297;
 this.a = 9301;
 this.min = _min;
 this.max = _max;
 var n = this.max - this.min + 1;
 this.result = new Array(n);
}

randomMaker.prototype.run = function()
{
 var count = this.max - this.min + 1;
 var i = 0;
 var t;
 while (i < count)
 {
  this.seed = (this.seed * this.a + this.c) % this.m;
  t = this.seed / this.m;
  t = Math.floor(t * this.get10factor());
  if (t >= this.min && t <= this.max && !arrayContains(this.result, t))
  {
   this.result[i] = t;
   i++;
  }
 }
}

randomMaker.prototype.get10factor = function()
{
 var t = 10;
 while (t < this.max)
 {
  t = t * 10;
 }
 return t + 1;
}

function arrayContains(a, value)
{
 for (var i = 0; i < a.length; i++)
 {
  if (a[i] == value)
   return true;
 }
 return false;
}

function realignFFTable()
{
 // hacking to support layout in firefox
 if (cg_shared.IsFireFox)
 {
  var tables = $(".question_outer");
  tables.each(function()
  {
   var parent = $(this).parent();
   if (parent[0].tagName == "DIV")
    $(this).attr("align", parent.css("text-align"));
  });

  tables = $(".grid_outer");
  tables.each(function()
  {
   var parent = $(this).parent();
   if (parent[0].tagName == "DIV")
    $(this).attr("align", parent.css("text-align"));
  });
 }
}
