function getEnclosingDiv(element) {
  var parent = element.parents("div[id='itemArea']");
  if (parent != null) {

    var errorArea = $(parent).find("div[name='errorArea']");
    return errorArea;
  }
}
function getEnclosingDiv1(element) {

  var parent = element.parent();
  if (parent.attr("id") == "itemArea") {
    return $(parent).find("div[name='errorArea']");
  }
  else {
    return getEnclosingDiv(parent);
  }
}

function isEmpty(inputStr) {
	if(inputStr == null || inputStr == "") {
    return true;
  }
  var isSpace = true;
	for(var i = 0; i < inputStr.length; i++) {
		var oneChar = inputStr.charAt(i);
		if(oneChar == ' ' || oneChar == '\n' || oneChar == '\t') {
			continue;
		}
    isSpace = false;
    break;
	}
  if(isSpace == true) {
    return true;
  }

	return false;
}

function isNumeric(inputVal) {
    oneDecimal = false;
    var inputStr = "";
    if(!isEmpty(inputVal) && undefined != inputStr ){
        inputStr = trim(inputVal.toString());
    }
    if(isEmpty(inputStr)){
        return true;
    }
    for(var i = 0; i < inputStr.length; i++) {
        var oneChar = inputStr.charAt(i);
        if(i == 0 && oneChar == ".") {
            oneDecimal = true;
            continue;
        }
        if(i == 0 && (oneChar == "-" || oneChar == "+")) {

            if(inputStr.length == 1)
                return false;

            continue;
        }
        if(oneChar == "." && !oneDecimal) {
            oneDecimal = true;
            continue;
        }
        if(oneChar < "0" || oneChar > "9") {
            return false;
        }
    }
    if(inputStr.length == 1 && inputStr == ".") {
        return false;
    }

    return true;
}




function isInteger(inputVal) {

  inputStr = trim(inputVal.toString());
  if(isEmpty(inputStr)){
    return true;
    }
    else{
	for(var i = 0; i < inputStr.length; i++) {

		var oneChar = inputStr.charAt(i);
		if(i == 0 && (oneChar == "-" || oneChar == "+")) {

			continue;
		}
		if(oneChar < "0" || oneChar > "9") {
			return false;
		}
	}
	}
	return true;
}


function isNullField( field ){
    if( null != field || "" != field ){
        return false;
    }
    return true;
}

function isRankOrderValueBetween(field, lower, upper) {

    var fieldId = field.name;
    if( isNullField( fieldId ) ){
        return false;
    }

    var trNode = document.getElementById( fieldId );
    if ( isNullField( trNode ) ){
        return false;
    }

    var tbody = trNode.parentNode;
    if ( isNullField( tbody ) ){
        return false;
    }

    var rows = tbody.children;
    var limitCounter = 0;
    for( var i = 0; i < rows.length; i++ ){
        if( rows[i].style.display == 'none' ){
            continue;
        }
        limitCounter++;
    }

    // Set the upper bound to the limit counter ONLY if the number of displayed
    // fields is less than the originally set MAX Limit
    if (limitCounter < upper) {
        upper = limitCounter;
    }

    if(isEmpty(field.value)){
        return true;
    }
    else{
        if(!isNumeric(field.value)) {
            return false;
        }
        else {
            var fieldVal = parseFloat(field.value);
            if((fieldVal >= lower) && (fieldVal <= upper)) {
                field.value = fieldVal;
                return true;
            }
            else {
                field.value ='';
                field.focus();
                alert('Please provide a value between'+ lower +' and '+ upper + '.' );
                return false;
            }
        }
    }
    return true;
}

function isValueBetween(field, lower, upper) {

    if(isEmpty(field.value)){
        return true;
    }
    else{
        if(!isNumeric(field.value)) {
            return false;
        }
        else {
            var fieldVal = parseFloat(field.value);
            if((fieldVal >= lower) && (fieldVal <= upper)) {
                field.value = fieldVal;
                return true;
            }
            else {
		      //field.value ='';
                return false;
            }
        }
    }
    return true;
}


// This method is for Rank Order question type.
// For every options check if value entered is
// integer.
function checkInteger(form, val) {

	  var arr = getTokens(val);
	  var rankVal = new Array(arr.length);
	  var rankQ = new Array(arr.length);
	  for (var i = 0; i < arr.length; i++) {
          rankVal[i] = (form.elements[arr[i]]);
          if (rankVal[i] === undefined) {
              continue;
          }
          rankQ[i] = parseFloat(rankVal[i].value);
         if(isNaN(rankVal[i].value) && isInteger(rankQ[i]) == false){
               rankVal[i].value='';
	       return false;
        }
    }
    return true;

}

// This method is for validation of Upper and Lower limit
// of Rank Order options.
function checkRankOrder(form, val, lower, heigher) {

	 var arr = getTokens(val);
	 var rankQ = new Array(arr.length);
	  for (var i = 0; i < arr.length; i++) {
          rankQ[i] = (form.elements[arr[i]]);
          if (rankQ[i] === undefined) {
              continue;
          };
        if(isValueBetween(rankQ[i],lower,heigher) == false){
                rankQ[i].value='';
	        return false;
        }
    }
   return true;
}

// isRequired functions...
function getRadioButtonValue(radio) {
  if (eval(radio.value))  {
    if(radio.checked)  {
	  return radio.value;
	}
  } else {
    for (var i = 0; i < radio.length; i++) {
      if (radio[i].checked) {
        return radio[i].value;
      }
    }
  }
  return "";
}

// isRequired functions...
function getRadioButtonForFillBlankValue(radio,choiceNum) {
  if( radio == undefined ){
  	return choiceNum;
  }
  if (eval(radio.value))  {
    if(radio.checked)  {
	  return radio.value;
	}
  } else {
    for (var i = 0; i < radio.length; i++) {
      if (radio[i].checked) {
        if(i+1 == choiceNum){
      	  return radio[i].value;
      	  }
      }
    }
  }
  return "";
}

function getCheckBoxValue(form,val,sz) {
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (form.elements[val + '_' + (i+1)].checked) {

      	return ("selected " + i);

    }

  }
  return "";
}


function getCheckBoxValueForPiping(form,val,sz,elName) {
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (form.elements[val + '_' + (i+1)].checked) {
       if ('form.'+val+'_'+(i+1) == elName ){
      		return (i+1);
      }
    }

  }
  return "";
}

function getMatrixValue(form,val,sz) {
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if(getRadioButtonValue(form.elements[val + '_' + (i+1)]) == "")
      return "";
  }
  return "selected";
}

// This method is for evaluation Required (*) condition.
// If all options are empty then only show error
// otherwise, don't.
function getGroupRankValue(form,val) {
  // each blank must be filled in
  var arr = getTokens(val);
  var submittedValues =  new Array();
  for (var i = 0; i < arr.length; i++) {
	var qVal = arr[i];
    if (form.elements[qVal] === undefined) {
        continue;
    }    
    if(!isEmpty(form.elements[qVal].value)){
        submittedValues[i] = qVal;
    }
  }
   if( submittedValues.length == 0 ){
        return "";
    }
  return "selected";
}

function getFirstVisibleElement(form,val) {
    var arr = getTokens(val);
    for (var i = 0; i < arr.length; i++) {

        var elem = form.elements[arr[i]];
        if ((elem === undefined) || (elem.style.display === 'none')){
            continue;
        }
        return elem;
    }
}
function isUniqueGroupRankValue(form,val) {

  // each blank must have a unique value
  var arr = getTokens(val);
  var values = new Array(arr.length);
  for (var i = 0; i < arr.length; i++) {
    if (form.elements[arr[i]] === undefined) {
        continue;
    }
    values[i] = parseFloat(form.elements[arr[i]].value);
  }
  // for each value check if there is any duplicate
  for(var i = 0; i < arr.length; i++) {
    for(var j = 0; j < arr.length; j++) {
      if ((i == j) || (values[i] === undefined) || (values[j] === undefined)) {
        continue;
      }
      if(values[i] == values[j])
        return false;
    }

  }
  return true;
}

function getTokens(val) {
  var c = val.split(/,/g);// returns an array of comma separated tokens
  return c;// returns an array
}

function checkMaxSelection(form,val,sz,maxLimit) {
  var total = 0;
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (document.getElementById(val + '_' + (i+1)).checked) {
      total++;
    }
  }
  if(total > parseFloat(maxLimit)) {
    // limit exceeded
    return false;
  }

  return true;
}

function checkListMaxSelection(form,val,sz,maxLimit) {
  var total = 0;
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (form.elements[val][i].selected) {
      total++;
    }
  }
  if(total > parseFloat(maxLimit)) {
    // limit exceeded
    return false;
  }

  return true;
}

function checkMinSelection(form,val,sz,minLimit) {
  var total = 0;
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (document.getElementById(val + '_' + (i+1)).checked) {
      total++;
    }
  }
  if(total < parseFloat(minLimit)) {
    return false;
  }

  return true;
}

function checkListMinSelection(form,val,sz,minLimit) {
  var total = 0;
  var eSize = parseFloat(sz);
  for (var i = 0; i < eSize; i++) {
    if (form.elements[val][i].selected) {
      total++;
    }
  }
  if(total < parseFloat(minLimit)) {
    return false;
  }

  return true;
}

// This method is used for min limit validation.
// Show the error alert only if Rank Order question
// has Required(*) condition set.
function checkRankMinSelection(form,val,minLimit) {
  // each blank must have a unique value
  var arr = getTokens(val);
  var values = new Array(arr.length);
  var cnt = 0;
  for (var i = 0; i < arr.length; i++) {
      if (form.elements[arr[i]] === undefined) {
          continue;
      }
    if(isEmpty(form.elements[arr[i]].value))
	  continue;
    values[i] = parseFloat(form.elements[arr[i]].value);
	cnt++;
  }
  if( (cnt != 0) && (cnt < parseFloat(minLimit)) ){
      return false;
  }
  return true;
}


// This method is used for max limit validation.
// Show the error alert only if Rank Order question
// has Required(*) condition set.
function checkRankMaxSelection(form,val,maxLimit,isRequired) {
  // each blank must have a unique value
  var arr = getTokens(val);
  var values = new Array(arr.length);
  var cnt = 0;
  for (var i = 0; i < arr.length; i++) {
      if (form.elements[arr[i]] === undefined) {
          continue;
      }
    if(isEmpty(form.elements[arr[i]].value))
	  continue;
    values[i] = parseFloat(form.elements[arr[i]].value);
	cnt++;
  }
  if( (cnt != 0) && ( cnt > parseFloat(maxLimit)) ){
	  return false;
  }
  return true;
}

function showSum(form, val, sz) {
  var eSize = parseFloat(sz);
  var value = 0;
  for (var i = 0; i < eSize; i++) {
    var fieldValue = form.elements[val + '_' + (i+1)].value;
    if(isEmpty(fieldValue) == false) {
      if(isNumeric(fieldValue)) {
        value += parseFloat(fieldValue);
      }
    }
  }// for ends

	var sumField = val + "_SHOWSUM";
	form.elements[sumField].value = value;
}

function checkDate(sDay, sMonth, sYear) {

 if(!checkrange(sMonth,0,12))
 {
   return false;
 }
 if(!checkrange(sYear,0,9999))
   return false;

 if(!checkday(sYear,sMonth,sDay))
   return false;

 return true;

}

function checkrange(val, minval, maxval)
{
  if(minval != null)
  {
    if(val < minval)
      return false;
  }
  if(maxval != null)
  {
    if(val > maxval)
      return false;
  }

  return true;
}

function checkday(checkyear,checkmonth,checkday)
{
  maxday = 31;
  if(checkmonth == 4 || checkmonth == 6 || checkmonth == 9 || checkmonth == 11)
  {
    maxday = 30;
  }
  else if(checkmonth == 2)
  {
    if(checkyear % 4 > 0)
      maxday = 28;
    else
      maxday = 29;
  }

  return checkrange(checkday,1,maxday);
}

function getDropdownValue(obj)
{
   for (i = 0; i < obj.length; i++)
      if (obj[i].selected == true)
	    return obj[i].value;
}

function checkTimeValues(form, val, which) {
  var hourObj = eval("form." + val + "_HOUR");
  var minObj = eval("form." + val + "_MIN");
  var ampmObj = eval("form." + val + "_AMPM");
  if(which == 'hour' || which == 'min') {
    if(getDropdownValue(hourObj) == '12' && getDropdownValue(minObj) == '0' && getDropdownValue(ampmObj) == 'AM') {
	    ampmObj.selectedIndex = 4;
	}
    else if(getDropdownValue(hourObj) == '12' && getDropdownValue(minObj) == '0' && getDropdownValue(ampmObj) == 'PM') {
	    ampmObj.selectedIndex = 3;
	}
	else if (getDropdownValue(ampmObj) == 'Midnight') {
	  ampmObj.selectedIndex = 1;
	}
	else if(getDropdownValue(ampmObj) == 'Noon') {
	  ampmObj.selectedIndex = 2;
	}
  }
  else if(which == 'ampm') {
    if(getDropdownValue(ampmObj) == 'Midnight' || getDropdownValue(ampmObj) == 'Noon') {
	    hourObj.selectedIndex = 12;
		minObj.selectedIndex = 1;
	}
    if(getDropdownValue(hourObj) == '12' && getDropdownValue(minObj) == '0' && getDropdownValue(ampmObj) == 'AM') {
	    ampmObj.selectedIndex = 4;
	}
    else if(getDropdownValue(hourObj) == '12' && getDropdownValue(minObj) == '0' && getDropdownValue(ampmObj) == 'PM') {
	    ampmObj.selectedIndex = 3;
	}
  }
}

function getCookie(name) {
	var bikky = document.cookie;

    var index = bikky.indexOf(name + "=");
    if (index == -1) return null;
    index = bikky.indexOf("=", index) + 1; // first character
    var endstr = bikky.indexOf(";", index);
    if (endstr == -1) endstr = bikky.length; // last character
    return unescape(bikky.substring(index, endstr));
}

function setCookie(name, value) {
    var bikky = document.cookie;
	var today = new Date();
    var expiry = new Date(today.getTime() + 28 * 24 * 60 * 60 * 1000); // plus 28 days

    if (value != null && value != "")
      document.cookie=name + "=" + escape(value) + "; expires=" + expiry.toGMTString();
}

function setCookie1(name, value, path, maxage) {
    var bikky = document.cookie;
	var today = new Date();
    var expiry = new Date(today.getTime() + maxage);

    if (value != null && value != "")
      document.cookie=name + "=" + escape(value) + "; expires=" + expiry.toGMTString() +
                        "; path=" + escape(path) + ";";
}

function deleteCookie(name) {
    var bikky = document.cookie;
	var today = new Date();
    var expired = new Date(today.getTime() - 28 * 24 * 60 * 60 * 1000); // less 28 days

    document.cookie=name + "=null; expires=" + expired.toGMTString();
}

function newWin(link, name, width, height) {
	newwin(link, name, width, height);
}
function newwin(link, name, width, height) {

    var newWindow;
	var ur = "menubar=no,toolbar=no,location=no,directories=no,status=no,scrollbars=no,resizable=no,copyhistory=no,width=" + width + ",height=" + height;
	openWindow(link, name, ur);
}

function newWin(link, name, width, height, menubar, toolbar, locationbar, dir, status, scrollbar, resize, copyhistory) {
	newwin(link, name, width, height, menubar, toolbar, locationbar, dir, status, scrollbar, resize, copyhistory);
}

function newwin(link, name, width, height, menubar, toolbar, locationbar, dir, status, scrollbar, resize, copyhistory) {

    var newWindow;
	var ur = "menubar=" + menubar + ",toolbar=" + toolbar + ",location=" + locationbar + ",directories=" + dir + ",status=" + status + ",scrollbars=" + scrollbar + ",resizable=" + resize + ",copyhistory=" + copyhistory + ",width=" + width + ",height=" + height;
	openWindow(link, name, ur);
}

function openWindow(link, name, url) {
    newWindow=window.open(link, name,url);
    if (newWindow.opener == null) {

      newWindow.opener=window;
    }
    else {

      newWindow.focus();
    }
}

function submitFormNoDuplicates(index, surveyId) {
    createDuplicateResponseCookie(surveyId); 
    submitForm(index);   
}
function submitForm(index) {
	if(eval("document.surveyForm.javelin_do_time_secs"))
		document.surveyForm.javelin_do_time_secs.value = the_count;
    if(index == '0') {
		document.surveyForm.javelin_next.value = "Next >>";
		document.surveyForm.javelin_previous.value = "";
		document.surveyForm.javelin_resume.value = "";
		document.surveyForm.javelin_submit.value = "";
	}
	else if(index == '1') {
		document.surveyForm.javelin_previous.value = "<< Previous";
		document.surveyForm.javelin_next.value = "";
		document.surveyForm.javelin_resume.value = "";
		document.surveyForm.javelin_submit.value = "";
	}
	else if(index == '2') {
		document.surveyForm.javelin_resume.value = "Resume Later";
		document.surveyForm.javelin_next.value = "";
		document.surveyForm.javelin_previous.value = "";
		document.surveyForm.javelin_submit.value = "";
	}
	else if((index == '3') || (index == '4')) {
		document.surveyForm.javelin_submit.value = "Submit";
		document.surveyForm.javelin_next.value = "";
		document.surveyForm.javelin_previous.value = "";
		document.surveyForm.javelin_resume.value = "";
	}
	else if(index == '6') {
      	document.surveyForm.javelin_lang.value = "Language";
		document.surveyForm.javelin_submit.value = "";
		document.surveyForm.javelin_next.value = "";
		document.surveyForm.javelin_previous.value = "";
		document.surveyForm.javelin_resume.value = "";
	}
    if ((index == '0') || (index == '3')) {
       $("#surveyForm").validate();
       if ($("#surveyForm").valid()) {
          buildDom();
          document.surveyForm.submit();
      } 
    }
    else {
      document.surveyForm.submit();
    }

}

function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
} // Ends the "trim" function

var the_count = -1;
var the_timeout;
function setTimer(count)
{
	the_count = count;
	doTimer();
}

function doTimer() {
	if(the_count < 0)
		return;
	window.status="Time Remaining:" + the_count + " seconds";
	the_count -= 1;
	if(the_count >= 0)
	  the_timeout = setTimeout("doTimer();", 1000);
	else {
	  cancelTimer();
	  submitForm(2);
	}
}

function cancelTimer() {
  clearTimeout(the_timeout);
}


/************************************************
DESCRIPTION: Validates that a string contains a
  valid email pattern.

 PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

REMARKS: Accounts for email with country appended
  does not validate that email contains valid URL
  type (.com, .gov, etc.) or valid country suffix.
*************************************************/

function isEmail( inputVal) {
  inputStr = trim(inputVal.toString());
  if(isEmpty(inputStr)){
    return true;
  }else{
    var objRegExp  =
    /(^[a-z]([a-z_\.]*)@([a-z_\.]*)([.][a-z]{3})$)|(^[a-z]([a-z_\.]*)@([a-z_\.]*)(\.[a-z]{3})(\.[a-z]{2})*$)/i;

    //check for valid email
    return objRegExp.test(inputStr);
  }
}

function createDuplicateResponseCookie(surveyId) {

    var cookieSub = document.cookie;
    if (cookieSub.indexOf("duplicate_response_") > -1) {
        return ;
    }
    else {
        document.cookie = "duplicate_response_" + surveyId + "path=/; expires=01-Jan-2020 00:00:01 GMT;";
        return ;
    }
}

