function trim(s) {
  var str = new String(s);
  if(str != '')
	 return(str.replace(/^\s+|\s+$/g, ''));
	else
	 return '';
}

function is_numeric(s) {
	var str = new String(s);
	var result = !isNaN(str);
	return result;
}

function is_integer(s) {
	var str = new String(s);
	var result = (str.indexOf('.') != -1);
	return result;
}

function to_number(s) {
  if(is_numeric(s))
    return Number(s);
  else
    return 0;
}

function is_empty(val) {
  var result = (val == null) || (trim(val) == '');
  return result;
}

function multicoded_checks(aValue) {
  // For a multicoded, the getQuestionResponse functions retrieves a string 
  // with each options checked comma separated. So, finding how many
  // options they have checked is solved by counting the values 
  // that getQuestionResponses retreives..  
  var fromIndex = 0;
  var cantCommas = 0;
  if(aValue == null) return 0;
  while(aValue.indexOf(',', fromIndex) != -1) {
    cantCommas++;
    fromIndex = aValue.indexOf(',', fromIndex) + 1;
  }
  return cantCommas + 1;
}

function response_length(val) {
  var str = new String(val);
  str = trim(str);  
  return str.length;
}

function getRadioValue(aQuestion) {
  var i = 1;
  var radioInput;
  while(radioInput = document.getElementById(aQuestion + '__' + i)) {
    if(radioInput.checked)
      return radioInput.value;
    i++;
  }
  return null;
}

var questionElements = new Array();

function addQuestionElement(aQuestion, qField, aType) {
	if(aType == 'checkbox_leveled') {
		if(questionElements[aQuestion] == null) {			
			questionElements[aQuestion] = new Array();
			questionElements[aQuestion]['field'] = new Array();
			questionElements[aQuestion]['field'][0] = qField;
		}
		else {
			questionElements[aQuestion]['field'][questionElements[aQuestion]['field'].length] = qField;
		}
	}
	else {
		questionElements[aQuestion] = new Array();
		questionElements[aQuestion]['field'] = qField;
	}		
	questionElements[aQuestion]['type'] = aType;
}

function getQuestionResponseFromElement(aQuestion) {  
	var fldType = questionElements[aQuestion]['type'];
	var fld = questionElements[aQuestion]['field'];
	if(fldType == 'checkbox')
		return fld.checked;
	else if(fldType == '') { 
		if(fld.value == '')
			return null;
		else if(is_numeric(fld.value)) {
		  // ToDo: This check should be done for every type...
      if(displayContainerVisible('container_' + fld.name))
			 return Number(fld.value);
			else
			 return 0;
		}
		else
			return fld.value;
	}
	else if(fldType == 'radio') {
		return getRadioValue(aQuestion);
	}
	else if(fldType == 'radio_leveled') {
		return getRadioValue(questionElements[aQuestion]['field']);
	}
	else if(fldType == 'checkbox_leveled') {
		var checkBoxValues = '';
		var i;
		var frmElement;
		for(i = 0; i < fld.length; i++) {
			frmElement = fld[i];
			if(frmElement.checked) {
				if(checkBoxValues != '')
					checkBoxValues = checkBoxValues + ', ';
				checkBoxValues = checkBoxValues + frmElement.value; 
			}            			
		}

      if(checkBoxValues != '')
        return checkBoxValues;		
	}	
	return null;
}

function getQuestionResponse(aQuestion) {
	
  var qField;   
  
  if(questionElements[aQuestion] != null)
  	return getQuestionResponseFromElement(aQuestion);
  
  
  
  qField = document.getElementById(aQuestion);  
  if(qField && qField.id == aQuestion) {        
    if(qField.getAttribute('type') == 'checkbox') {     
	  addQuestionElement(aQuestion, qField, 'checkbox');
      return qField.checked;
    }
    else if(trim(qField.value) == '') {
	   addQuestionElement(aQuestion, qField, '');
      return null;
    }
    else if(is_numeric(qField.value)) {
      addQuestionElement(aQuestion, qField, '');
      // ToDo: This check should be done for every type...
      if(displayContainerVisible('container_' + qField.name))
			 return Number(qField.value);			      	         
			else
			 return 0;
    }
    else {
	  addQuestionElement(aQuestion, qField, '');
      return qField.value;
    }
  }
  else {    
    qField = document.getElementById(aQuestion + '__1');
    if(qField) {       
	  addQuestionElement(aQuestion, qField, 'radio');
      return getRadioValue(aQuestion);     
    }
    else {
      /////////////////////////////////////////////////////////////////////////////////////////////
      var i, currentId, checkBoxValues, frmElement, aQuestionWithoutLevels, splitQuest, validField;
           
      checkBoxValues = '';      
      splitQuest = aQuestion.split('||');      
      aQuestionWithoutLevels = splitQuest[0];      
      for(i=0; i< document.forms[0].elements.length; i++) {
         frmElement = document.forms[0].elements[i];
         currentId = frmElement.id;
         validField = currentId.substring(0, aQuestionWithoutLevels.length + 1) == (aQuestionWithoutLevels + '|');
         if(validField && splitQuest.length == 2) {
           if(currentId.indexOf('||' + splitQuest[1]) == -1)
            validField = false;
         }         
         if(validField) {
           if(frmElement.getAttribute('type') == 'radio') {
             // A los radio, independientemente de los levels en los que se encuentre, se le identifica
             // con un id que numera de 1 a n sus elementos, con el unico fin de obtener el valor de
             // respuesa.
             // Entonces, para un radio determinado la primera vez que se entre aqui va a ser para el id
             // del primer elemento, entonces puedo retornar el valor en base a esto
             // Ej. a1||Stedicor|1__1, quitando los ultimos 3 caracteres tengo el prefijo de id para llamar
             // al getRadioValue
			 addQuestionElement(aQuestion, frmElement.id.substring(0, frmElement.id.length - 3), 'radio_leveled');
             return getRadioValue(frmElement.id.substring(0, frmElement.id.length - 3));
           }
           else if((frmElement.getAttribute('type') == 'checkbox')) {			
			addQuestionElement(aQuestion, frmElement, 'checkbox_leveled');
            if(frmElement.checked) {
              if(checkBoxValues != '')
                   checkBoxValues = checkBoxValues + ', ';
              checkBoxValues = checkBoxValues + frmElement.value; 
            }            
           }
           else {
			addQuestionElement(aQuestion, frmElement, '');
            return frmElement.value;
		   }
         }
      }
      if(checkBoxValues != '')
        return checkBoxValues;
           
      /////////////////////////////////////////////////////////////////////////////////////////////*/
	  
      return null;
    }
  }
}


function focusQuestion(aQuestion) {
  var qField;
  qField = document.getElementById(aQuestion);
  if(qField) {   
    if(qField.type == 'hidden')
  	  return true;
    qField.focus();
  }
  else {
    qField = document.getElementById(aQuestion + '__1');
    if(qField)
      return qField.focus();
  }
}


function clearCheckbox(e_id, item, e_levels) {
  if(document.getElementById(e_id + '|' + item + e_levels).checked) {
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;
      unCheck = ((currentId.substring(0, e_id.length + 1) == (e_id + '|')) 
                && (currentId.indexOf(e_levels) != -1)    
                ) 
                && 
                (currentId.substring(0, e_id.length + item.length + e_levels.length + 1) != (e_id + '|' + item + e_levels));      
      if(unCheck)    
        frmElement.checked = false;
    }
  }
}

// Hide and Show functionality

var displayContainers = new Array();
var lastContainer = '';

var _display_show;
if(navigator.appVersion.indexOf('MSIE') != -1)
		_display_show = 'block';
	else
		_display_show = 'table-row';

function displayShow() {
	return _display_show;
}

function addDisplayContainer(container, parent_container) {
  displayContainers[container] = new Array();
  displayContainers[container]['parent'] = parent_container;
  if(parent_container != '')
  	displayContainers[parent_container]['children'][displayContainers[parent_container]['children'].length] = container;
  displayContainers[container]['children'] = [];  
  displayContainers[container]['visible'] = true;   
  displayContainers[container]['elements'] = [];  
  lastContainer = container;
}

function addElementToLastDisplayContainer(lContainer,elementName,elementID) {	
	if(!displayContainers[lContainer]) {
		alert(lContainer);
	}
	//if(lastContainer != '') {
		var newEl = new Array();
		newEl['name'] = elementName;
		newEl['id'] = elementID;				
		displayContainers[lContainer]['elements'][displayContainers[lContainer]['elements'].length] = newEl;		
	//}
}

function cleanContainerElements(container) {
	var i, anElement;
	for(i = 0; i < displayContainers[container]['elements'].length; i++) {	
			anElement = document.getElementById(displayContainers[container]['elements'][i]['id']);
			//alert(anElement.id + " " + container);
			if(anElement.type == 'radio') {
				anElement.checked = false;
			}
			else if(anElement.type == 'checkbox') {
				anElement.checked = false;
			}
			else if(anElement.type == 'select-one') {				
				anElement.options[0].selected = true;
			}
			else {				
				anElement.value = '';
			}
		}
}

function enableDisabledElements() {
	var i, container, anElement;
	for(var container in displayContainers) {
		for(i = 0; i < displayContainers[container]['elements'].length; i++) {	
			anElement = document.getElementById(displayContainers[container]['elements'][i]['id']);
			if(anElement.disabled)
				anElement.disabled = false;
		}
	}
}

function cleanChildrenContainerElements(container) {
	var i;
	for(i = 0; i < displayContainers[container]['children'].length; i++) {		  		
  		cleanContainerElements(displayContainers[container]['children'][i]);
  		cleanChildrenContainerElements(displayContainers[container]['children'][i]);
  	}
}

function toggleDisplayContainer(container, showContainer) {
  var i;
  if(displayContainers[container] == null) {	  
	  return false;
  }

  
	  displayContainers[container]['visible'] = showContainer;
	  if(showContainer)
		document.getElementById(container).style.display = displayShow();
	  else {
	  	document.getElementById(container).style.display = 'none'; 
	  	if(!pageLoading) {
		  	cleanChildrenContainerElements(container);
			cleanContainerElements(container);
	  	}
	  }
  
}

function displayContainerVisible(container) {
  // The visibility is not given by the visibility of the container itself but also by
  // the visibility of parent containers  
  var actualContainer = displayContainers[container];
  /*
  if(actualContainer == null) {
  	 alert(container);  	
  }
  */
  var isVisible = actualContainer['visible'];
  while(isVisible && (actualContainer['parent'] != '')) {
  	actualContainer = displayContainers[actualContainer['parent']];  	
	  isVisible = actualContainer['visible'];
  }
  return isVisible;   
}

function populateHInfo() {
	//var startTime = new Date(); // timing
	var i;
	document.getElementById('hinfo').value = '';	
	for(var container in displayContainers) {		
		if(!displayContainerVisible(container)) {
			for(i = 0; i < displayContainers[container]['elements'].length; i++) {				
				document.getElementById('hinfo').value = document.getElementById('hinfo').value + displayContainers[container]['elements'][i]['name'] + ";";
			}
		}
	}
	//var endTime=new Date(); // timing
	//alert((endTime-startTime)); // timing
}

var question_in_loop_buffer = new Array();

function repetition_in_loop(q_id) {
  var i, j, foundEqual;
  
  if(q_id.indexOf('||') != -1) {
    q_id = q_id.substr(0, q_id.indexOf('||'));
  }  
  
  if(question_in_loop_buffer[q_id] == null) {
    question_in_loop_buffer[q_id] = new Array();
    question_in_loop_buffer[q_id]['elements'] = new Array();
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;      
      if(currentId.substr(0, q_id.length) == q_id) {            
        question_in_loop_buffer[q_id]['elements'][question_in_loop_buffer[q_id]['elements'].length] = frmElement;
      }
    }
  }
  
  foundEqual = false;
  
  for(i=0; i < question_in_loop_buffer[q_id]['elements'].length - 1; i++) {       
    for(j=i+1; j < question_in_loop_buffer[q_id]['elements'].length; j++) {      
      if(question_in_loop_buffer[q_id]['elements'][i].value == question_in_loop_buffer[q_id]['elements'][j].value)
        foundEqual = true;
    }
  }
  
  return foundEqual;
}

function empty_in_loop(q_id) {
  var i, j, foundEqual;
  var empty = true;
  
  if(q_id.indexOf('||') != -1) {
    q_id = q_id.substr(0, q_id.indexOf('||'));
  }  
  
  if(question_in_loop_buffer[q_id] == null) {
    question_in_loop_buffer[q_id] = new Array();
    question_in_loop_buffer[q_id]['elements'] = new Array();
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;      
      if(currentId.substr(0, q_id.length) == q_id) {            
        question_in_loop_buffer[q_id]['elements'][question_in_loop_buffer[q_id]['elements'].length] = frmElement;
      }
    }
  }
  
  foundEqual = false;
  
  for(i=0; i < question_in_loop_buffer[q_id]['elements'].length - 1; i++) {           
    if(trim(question_in_loop_buffer[q_id]['elements'][i].value) != '')
      empty = false;
  }
  
  return empty;
}

function answers_in_loop(q_id, aValue) {
  var i, j;
  var cant = 0;
  
  if(q_id.indexOf('||') != -1) {
    q_id = q_id.substr(0, q_id.indexOf('||'));
  }  
  
  if(question_in_loop_buffer[q_id] == null) {
    question_in_loop_buffer[q_id] = new Array();
    question_in_loop_buffer[q_id]['elements'] = new Array();
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;      
      if(currentId.substr(0, q_id.length) == q_id) {            
        question_in_loop_buffer[q_id]['elements'][question_in_loop_buffer[q_id]['elements'].length] = frmElement;
      }
    }
  }
      
  for(i=0; i < question_in_loop_buffer[q_id]['elements'].length; i++) {               
    if(trim(question_in_loop_buffer[q_id]['elements'][i].value) == aValue) {
      if(question_in_loop_buffer[q_id]['elements'][i].type == 'radio') {
        if(question_in_loop_buffer[q_id]['elements'][i].checked)
          cant++;
      }
      else
        cant++;
    }
  }
  
  return cant;  
}

function repetition_in_loop_not_empty(q_id) {
  var i, j, foundEqual;
  
  if(q_id.indexOf('||') != -1) {
    q_id = q_id.substr(0, q_id.indexOf('||'));
  }  
  
  if(question_in_loop_buffer[q_id] == null) {
    question_in_loop_buffer[q_id] = new Array();
    question_in_loop_buffer[q_id]['elements'] = new Array();
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;      
      if(currentId.substr(0, q_id.length) == q_id) {            
        question_in_loop_buffer[q_id]['elements'][question_in_loop_buffer[q_id]['elements'].length] = frmElement;
      }
    }
  }
  
  foundEqual = false;
  
  for(i=0; i < question_in_loop_buffer[q_id]['elements'].length - 1; i++) {       
    for(j=i+1; j < question_in_loop_buffer[q_id]['elements'].length; j++) {      
      if((question_in_loop_buffer[q_id]['elements'][i].value == question_in_loop_buffer[q_id]['elements'][j].value) && (trim(question_in_loop_buffer[q_id]['elements'][i].value) != ''))
        foundEqual = true;
    }
  }
  
  return foundEqual;
}

function levels_sum(q_id) {
  var sum = 0;
  var leveled = false;
  var equals = false;
  
  if(q_id.indexOf('||') != -1) {
    q_id = q_id.substr(0, q_id.indexOf('||'));
    leveled = true;
  }  
  
  if(question_in_loop_buffer[q_id] == null) {
    question_in_loop_buffer[q_id] = new Array();
    question_in_loop_buffer[q_id]['elements'] = new Array();
    for(i=0; i< document.forms[0].elements.length; i++) {
      frmElement = document.forms[0].elements[i];
      currentId = frmElement.id;      
      /*if(!leveled)
        equals = currentId.substr(0, q_id.length) == q_id;
      else*/
        equals = currentId.substr(0, q_id.length + 2) == q_id + '||';
      if(equals) {            
        question_in_loop_buffer[q_id]['elements'][question_in_loop_buffer[q_id]['elements'].length] = frmElement;
      }
    }
  }
  
  for(i=0; i < question_in_loop_buffer[q_id]['elements'].length; i++) {          
    sum = sum + to_number(question_in_loop_buffer[q_id]['elements'][i].value);
  } 
  return sum;
}

function date_compare(d2, m2, y2, d1, m1, y1) {
  /*
    Compares two dates and returns:
    >0 if date1 < date2
    =0 if date1 = date2
    <0 if date1 > date2
  */

  date1 = new Date(y1, m1, d1);
  date2 = new Date(y2, m2, d2);

  return date2 - date1;
}

function date_today_day() {
  var dateNow = new Date();
  return dateNow.getDate();
}

function date_today_month() {
  var dateNow = new Date();
  return dateNow.getMonth() + 1;
}

function date_today_year() {
  var dateNow = new Date();
  return dateNow.getFullYear();
}

function checkVal(showAlert, alertText, focusElement) {
  if(showAlert) {
    alert(alertText);
    focusQuestion(focusElement);
  }
  return showAlert;
}
