///////////////////////////////////////////////////////////////////////
// Study:        All
// Protocol:     N/A
//
// Program:      $Archive: /betaweb-jsite/sweb/studies/jslib/General/util.js $
// Programmer:   
// Date:
// Version:      $Revision: 10 $
//
// Purpose:      General javascript functions for all studies
//
// Modification History
// ---------------------------------------------------------------------
//
//  $Log: /betaweb-jsite/sweb/studies/jslib/General/util.js $
//
//10    3/10/06 10:24a Sconstantine
//code review changes
//  $NoKeywords: $
///////////////////////////////////////////////////////////////////////

function statusBar(msg) {
  window.status = msg;
  return true;
}

function goBack() {
  history.back();
}


// -- String Functions ----------------------------------------------------------------

String.prototype.LTrim = function() { return this.replace(/^\s+/,''); }

String.prototype.RTrim = function() { return this.replace(/\s+$/,''); }

String.prototype.Trim = function() { return this.replace(/^\s+/, '').replace(/\s+$/, ''); }

String.prototype.cleanHTML =
new Function('var str=this.replace(/<([a-z])/gi,"< $1");str=str.replace(/<(\\/)/g,"< /");return str;');


// -- Determine what fields have changed ----------------------------------------------

function js_whatsChanged(form) {
    //array to store names of edited fields
    changedFields = new Array();

    //since each element of the radio buttons that are part of the same group have
    //the same name, store which groups have been checked so as we loop thru all
    //form elements, we only check each group once
    var radioChecked = new Array();

    //loop through array of fields and determine if value has changed from the
    //default value -- method to get value varies depending on type of form field
    for (var i=0; i < form.elements.length; i++) {
      var fieldObj = form.elements[i];

    // HJS 12/24/03 not including variables whose name end in 'NoWhatsChanged'
    var fieldName = fieldObj.name ? new String(fieldObj.name) : new String('');
      if ((fieldName.lastIndexOf('_') >= 0) &&
           fieldName.substr(fieldName.lastIndexOf('_')+1) == 'NoWhatsChanged')
        continue;

      //if field type is a drop-down menu
      if (fieldObj.type.indexOf('select') > -1) {
        //determine if element is part of a date
        var isDatePart = 0;
        var arrParts = form.elements[i].name.split('_');
        if (arrParts[1] == 'mm' || arrParts[1] == 'dd' ||
          arrParts[1] == 'yyyy') {
          isDatePart = 1;
        }

        //If element is part of date save old date value
        if (isDatePart == 1) {
          if (!fieldObj.options[fieldObj.selectedIndex].defaultSelected) {
            var inChange = 0;
            for(var d=0; d < changedFields.length; d++) {
              if (changedFields[d] == arrParts[0]) {
                inChange = 1;
              }
            }
            if (inChange == 0) {
              changedFields[changedFields.length] = arrParts[0];
            }
          }
        } else {
          // if the current selection is not the default
          if (!fieldObj.options[fieldObj.selectedIndex].defaultSelected) {
            // loop through options to determine which one was default
            for(var i2 = 0; i2 <= fieldObj.options.length - 1; i2++) {
              if (fieldObj.options[i2].defaultSelected) {
                changedFields[changedFields.length] = fieldObj.name;
              }
            }
          }
        }
      }

    //if field type is a radio button & radio group has not already been checked
    // hjs 08/04/04 - updated next two lines to handle a radio button whose name 
    //                is a substring of the name of a previously checked radio button
    var checkedRadios = "~"+radioChecked.join("~")+"~";
    if (fieldObj.type.indexOf('radio') > -1 && checkedRadios.indexOf("~"+fieldObj.name+"~") == -1) {
      var groupName = fieldObj.name;
      radioChecked[radioChecked.length] = groupName;
      var allFalse = 1;
      for (var k = 0; k < form[groupName].length; k++) {
        if (form[groupName][k].defaultChecked) {
          allFalse = 0;
        }
      }

      for (var i3 = 0; i3 < form[groupName].length; i3++) {
        if (allFalse == 1) {
          if (form[groupName][i3].checked) {
             changedFields[changedFields.length] = fieldObj.name;
          }
        } else {
          if (form[groupName][i3].defaultChecked) {
             if (!form[groupName][i3].checked) {
                changedFields[changedFields.length] = fieldObj.name;
             }
          }
        }
      }
    }

    //if field type is a checkbox
    if (fieldObj.type.indexOf('checkbox') > -1) {
     if (fieldObj.checked != fieldObj.defaultChecked) {
        changedFields[changedFields.length] = fieldObj.name;
     }
    }

    //if field type is text
    //BDB - added replace for new line because of Netscape 7 handling differently
    //HJS - modified to do a global substitution before check
    if (fieldObj.type.indexOf('text') > -1) {
      if (fieldObj.defaultValue.replace(/\r/g, '') != fieldObj.value.replace(/\r/g,'') && !(fieldObj.disabled==true && fieldObj.readOnly==true)) {
        changedFields[changedFields.length] = fieldObj.name;
     }
    }
   }
  return changedFields;
}


// -- Gets number of radio button selected --------------------------------------------

function js_getSelectedRadio(radioGroup) {

    for ( var i=0; i < radioGroup.length; i++ ) {
      if ( radioGroup[i].checked ) {
        return i;
      }
    }
    return null;
}

// -- Resets radio group buttons ----------------------------------------------------

function resetRadio(radioGroup) {
   for ( var i=0; i < radioGroup.length; i++ ) {
        radioGroup[i].checked  = false;
   }
}


// -- Resets radio individual radio button ----------------------------------------------------

function js_resetRadio(obj)
{
  if(typeof(obj.last_value)=="undefined" || obj.last_value==null)
  {
    obj.last_value=obj.checked;
  }
  else
  {
    if(obj.last_value)
    {
      obj.checked=false;
    }
    else
    {
      obj.checked=true;
    }	
    var rad,r=0, grp = obj.form[obj.name];
    while (rad = grp[r++])
      rad.last_value=null;
  }  
}

// -- Log out  ----------------------------------------------------------------------

function logout(href) {
   if(confirm("Click OK to log out of website.\nClick CANCEL to continue working."))
        location.href=href;
}

/*
Start textarea Object
*/
function textarea(objName,formname,name,cols,rows,maxlen,value,tabindex,answerIndent)
{
        this.objName        = objName;
        this.formname        = formname;
        this.name        = name;
        this.id                = name;
        this.countName        = name + '_counter';
        this.cols                = cols;
        this.rows                = rows;
        this.maxlen                = maxlen;
        this.value                = value;
        this.lastKey        = -1;
        this.wrap                = "physical";
        this.code10                = 0;
        this.tabindex            = (typeof(tabindex) == 'undefined') ? '' : tabindex;
        this.answerIndent      = (typeof(answerIndent) == 'undefined') ? '' : answerIndent;
				

    /*
    * Public Methods
    */
        this.writeHTML         = textarea_writeHTML;
        /**
        *priveate methods
        */
        this.count                = textarea_count;
        this.calcLength        = textarea_calcLength;
        this.length                = this.value.length;
}

function textarea_writeHTML()
{
        var strmaxlen=this.maxlen+'';
        this.calcLength();
        document.write('<textarea name="' + this.name + '" id="' + this.id + '" cols="' + this.cols + '" rows="' + this.rows + '" tabindex="' + this.tabindex + '" onKeyUp="' + this.objName + '.count(event,this);" wrap="' + this.wrap + '">');
        document.write(this.value);
        document.write('</textarea><br>');
        document.write(this.answerIndent);
        document.write('Max Size: ' + this.maxlen + '&nbsp;&nbsp;&nbsp;&nbsp; Remaining: <input name="' + this.countName + '" type="text" value="' +  (this.maxlen - this.showLength) + '" size="' + strmaxlen.length + '" maxlength="' + strmaxlen.length + '" readonly disabled>');
}

function textarea_calcLength()
{
        this.showLength=0;
        this.code10=0;
        for (var i=0; i < this.value.length; i++)
        {
                var code = this.value.charCodeAt(i);
                //if it is 10 then add 2 to account for possible 13
                if(code==10)
                {
                        this.showLength++;
                        this.code10++;
                }
                //if it is 13 then dont count it was taken care of by the 10 above
                if(code!=13)
                        this.showLength++;
        }
}

function textarea_count(eventObj, obj)
{
/*make sure the legnth changed as a result of the key press
this is a netscape thing where an alert will refire the key press if they hit enter for example
*/
        if(eventObj.keyCode!=8 && obj.value.charCodeAt(obj.value.length-1)==60)
        {
                obj.value=obj.value + ' ';
        }
        if(obj.value.length != this.length)
        {
                this.value=obj.value;
                this.calcLength();
                if(this.showLength>this.maxlen)
                {
                        obj.value=obj.value.Trim();
                        this.value=obj.value;
                        this.calcLength();
                        if(this.showLength>this.maxlen)
                        {
                                alert("You have exceeded the maximum length allowed for this field.\nThe maximum length is " + this.maxlen + " characters");
                                obj.value=obj.value.substring(0,this.maxlen-this.code10).Trim();
                        }
                }
                this.value=obj.value;
        }
        this.length=this.value.length;
        this.calcLength();
        eval('document.' + this.formname + '.' + this.countName + '.value=' +  (this.maxlen - this.showLength));
}



//------------------------------------------------------------------------------
// Shows/Hides section of forms - takes ID name of div tag as argument
// Expects corresponding image
//------------------------------------------------------------------------------

 function showHide(divID) {

//    alert("got to here");
     var object = document.getElementById(divID);
     var img = document.getElementById(divID + 'Img');

     if( object.style.display == 'none') {
        object.style.display = 'block';
        img.src = "/images/openFolder.gif";
     } else {
        object.style.display = 'none';
        img.src = "/images/closedFolder.gif";
     }
   }


//------------------------------------------------------------------------------
// Called when form loads to add locations to description fields - L.Lester 2/27/2004
//------------------------------------------------------------------------------

function addLocations(form) {
    for( fieldName in locations ) {
       var descFld = fieldName + "_description";
       if(form[descFld])
         form[descFld].value = locations[fieldName] + " " + form[descFld].value
    }
}

//------------------------------------------------------------------------------
// Displays a popup box with content from url passed in - R.Pritchard 1/11/2006
//------------------------------------------------------------------------------

function js_popupInstruct(url, name)
{
 window.open( url, name,'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=500,height=350,left=30,top=30');       
}