function clearErr( item )
{
  if (item != null) {
	  item.style.backgroundColor = '';
	  item.style.color = '';
	  //item.style.fontWeight='normal';
	  item.title = '';
   }	  
}

function putErr( item, msg )
{
  item.style.backgroundColor = '#FF5B5B' ;
  item.style.color='#fff';
  //item.style.fontWeight='bold';
 // item.title = msg;
}

function clearContents(item)
{
  if (item != null) {
  	item.value = '';
  }	
}

function clearBackColor(item)
{
  if (item != null) {
  	item.style.backgroundImage="none";
  }	
}


function isLeapYear(year)
{
  if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
  {
    return true;
  }
  else
  {
    return false;
  }
}

function isValidDay(month, day, year) {
  if (month == 2) {
    if (isLeapYear(year))
    {
      if (day <= 29)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
    else {
      if (day <= 28)
      {
        return true;
      }
      else
      {
        return false;
      }
    }
  }
  else if (month == 4 || month == 6 || month == 9 || month == 11) {
    if (day <= 30)
      return true;
    else
      return false;
  }
  else
    return true;
}


function popup(mylink, windowname, type)
{
  if (!window.focus)
  {
    return true;
  }

  var href;
  if (typeof(mylink) == 'string')
  {
    href=mylink;
  }
  else
  {
    href=mylink.href;
  }
  if(type==1)
  {
    window.open(href, windowname, "width=700, scrollbars=yes");
  }
  else if(type==2)
  {
    window.open(href, windowname, "width=800, height=600, scrollbars=yes, resizable=yes");
  }
  else
  {
    window.open('content/SampleBanner.html', windowname, 'width=600, height=380, scrollbars=no, resizable=no');
  }
  return false;
}

// Extend the string object with
// trim function.
String.prototype.trim = function() {
  return this.replace(/^\s+|\s+$/g,"");
};

/*
function checkWithCheckBox(itemDOMRef, checkDOMRef)
{
	if (check(itemDOMRef))
	{
		checkDOMRef.disabled = false;
		return true;
	}
	else {
		return false;
	}
}
*/


function check( itemDOMRef )
{
  // regex to use known by id
  var id = itemDOMRef.id ;
  var regex = regexes[ id ] ;
  if (regex == null){
	 alert("Null of reg exp of " + id);
  }
  var str = (String(itemDOMRef.value)).trim() ;   // ensure is a string, not number.
  
  //alert('using ' + regex + ' on ' + itemDOMRef.value );
  
//  if( !str.match( regex ) )
  if( str.match( regex )==null )
  {
    // failed to match.
    //alert( id + ' failed to match ' );
    putErr( itemDOMRef, errorMessages[ id ] );
    return false;
  }
  else
  {
    return true;
  }
}

//linda add
function checkSecondEmail( itemDOMRef,itemEmail )
{
  // regex to use known by id
  var id = itemDOMRef.id ;
  var regex = regexes[ id ] ;
  var str = (String(itemDOMRef.value)).trim() ;   // ensure is a string, not number.
  var str1=(String(itemEmail.value)).trim();
  //alert('using ' + regex + ' on ' + itemDOMRef.value );
  
  if( (str!=str1)&& str.match( regex ) )
  {
	  return true;
   }
  else
  {
	  putErr( itemDOMRef, errorMessages[ id ] );
	    return false;
  }
}
// linda end

function checkWithReg( itemDOMRef , id)
{
  // regex to use known by id
  var regex = regexes[ id ] ;
  var str = (String(itemDOMRef.value)).trim() ;   // ensure is a string, not number.
  
  //alert('using ' + regex + ' on ' + itemDOMRef.value );
  
  if( !str.match( regex ) )
  {
    // failed to match.
    //alert( id + ' failed to match ' );
    putErr( itemDOMRef, errorMessages[ id ] );
    return false;
  }
  else
  {
    return true;
  }
}

function checkBirth() {
  // Now check date of birth
  var yyyy = document.getElementById('birthYear');
  var mm = document.getElementById('birthMonth');
  var dd = document.getElementById('birthDay');
 
  if( yyyy.selectedIndex == 0 ||  mm.selectedIndex == 0 || dd.selectedIndex == 0 || !isValidDay( mm, dd, yyyy ) )  {
    putErr( yyyy, '' );
    putErr( mm, '' );
    putErr( dd, '' );
//    probs += '  - Invalid birthday\n';
    return false;
  }
  

  // Checking for valid day include leap years
  if (!isValidDay(mm.value,dd.value,yyyy.value)){
  	putErr( yyyy, '' );
  	putErr( mm, '' );
  	putErr( dd, '' );
//  	probs += '   -Invalid Birthday \n';
  	return false;
  }
   
    
  // Checking for years 
  var fullDate = new Date();
  var year = fullDate.getFullYear();
  var month = 1+fullDate.getMonth();
  var date = fullDate.getDate();
  
//   alert(yyyy.value+mm.value+dd.value +' / ' +year+month+date); 
  
  if ((year-yyyy.value) < 13)	{
  	putErr( yyyy, 'Must be older than 13 years' );
  	putErr( mm, 'Must be older than 13 years' );
  	putErr( dd, 'Must be older than 13 years' );
//  	probs += '   -Invalid Birthday (Must be older than 14 years)\n';
  	return false;
  }
  else  if ((year-yyyy.value) == 13)  {
   	if ((month - mm.value) < 0)	{
	  	putErr( yyyy, 'Must be older than 13 years' );
	  	putErr( mm, 'Must be older than 13 years' );
	  	putErr( dd, 'Must be older than 13 years' );
//  		probs += '   -Invalid Birthday (Must be older than 14 years)\n';
  		return false;
  	}
  	else if ((month - mm.value) == 0)	{
	  	if ((date - dd.value) < 0){
		  	putErr( yyyy, 'Must be older than 13 years' );
		  	putErr( mm, 'Must be older than 13 years' );
		  	putErr( dd, 'Must be older than 13 years' );
	//  		probs += '   -Invalid Birthday (Must be older than 14 years)\n';
	  	 	return  false;
		}
  	 	
  	}

  }

 
  return true;

}

function checkChoice(field, i) {
  //"All" checkbox selected.
  if (i == 0) {
    if (field[0].checked == true) {
      for (i = 1; i < field.length; i++)
        field[i].checked = false;
       }
  }
  //A checkbox other than "Any" selected.
  else {
    if (field[i].checked == true) {
      field[0].checked = false;
    }
  }
}

function checkChars( eta ) {
  var charsRem = 1000 - eta.value.length ;
  var charsremspan = document.getElementById('charsRemaining');
  var msg = '';
  if( charsRem < 0 ) {
    // overshot, data truncation will occur
    msg = charsRem + ' chars remaining.  <b style="color:red">Data truncation will occur.</b>';
  }
  else {
    msg = charsRem + ' chars remaining.';
  }
  charsremspan.innerHTML = msg;
}

function initTextArea(control,value) {
  // Initialize a text area field
  if(value == "") return;
      control.value = value;
}

function initCheckBox(control,value) {
  // Initialize a check box
  control.checked = (value == control.value);
}

function initRadio(control,value) {
  // Initialize a radio button
  for (var i = 0; i < control.length; i++) {
      if (control[i].value == value) {
          control[i].checked = true;
          break;
      }
  }
}

function initSelect(control,value) {
  // Initialize a selection list (single valued)
  if (value == "") return;
  for (var i = 0; i < control.length; i++) {
      if (control.options[i].value == value) {
          control.options[i].selected = true;
          break;
      }
  }
}

function initSelectMulti(control,value) {
  // Initialize a selection list (multi valued)
  if (value == "") return;
  var a = value.split(","); // make array
  for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < control.length; j++) {
          if (control.options[j].value == a[i]) {
              control.options[j].selected = true;
              break;
          }
      }
  }
}

function initCheckBoxMulti(control,value) {
  // Initialize a list of check boxes
  if (value == "") return;
  var a = value.split(","); // make array
  for (var i = 0; i < a.length; i++) {
      if (typeof(control.length) == "undefined") {
          if (control.value == a[i]) {
              control.checked = true;
              return;
          }
      }
      for (var j = 0; j < control.length; j++) {
          if (control[j].value == a[i]) {
              control[j].checked = true;
              break;
          }
      }
  }
}
  
function checkIfTaken( DOMREFUpdate, whatToCheck, nameValue )
{
  var windowRoot =  window.root;
  if(windowRoot == null){
	  windowRoot = "";
  }
  new Ajax.Request(
  windowRoot + '/servlet/CheckTaken',
  {
    'method':'post',
    'parameters': {
      'requestType':'checkExists',
      'whatToCheck':whatToCheck,
      'valueToCheckExists':nameValue
  },
      
  'onSuccess':function(transport)
  {
    var resp = (String(transport.responseText)).trim();
    if( resp == 'Yes' )
    {
    // taken, so too bad
      DOMREFUpdate.innerHTML='<span><b style="color:#f00">It\'s in use by someone</b></span>';
      DOMREFUpdate.style.display='block';
      window.taken[ whatToCheck ] = 'taken'; 
    }
    else
    {
      DOMREFUpdate.innerHTML='<span><b style="color:green">available!</b></span>';
      DOMREFUpdate.style.display='block';
      window.taken[ whatToCheck ] = 'available';
    }
  },
      
  'onFailure':function(transport)
  {
    //alert('fail');
    }
  });
}


function checkIfTaken2( DOMREFUpdate, whatToCheck, nameValue )
{
  //alert(whatToCheck + ' checkIfTaken! '+ nameValue + 'window.root: ' + window.root + '/servlet/CheckTakenMM');
  new Ajax.Request(
   window.root + '/servlet/CheckTakenMM',
  {
    'method':'post',
    'parameters': {
      'requestType':'checkExists',
      'whatToCheck':whatToCheck,
      'valueToCheckExists':nameValue
  },
      
  'onSuccess':function(transport)
  {
    var resp = (String(transport.responseText)).trim();
    //alert(whatToCheck);
    
    
    if( resp == 'Yes' )
    {   
        if (whatToCheck == 'orgOfficialName'){
            DOMREFUpdate.innerHTML='organization name already in use.';
            window.taken[ whatToCheck ] = 'taken'; 
        }
        else if (whatToCheck == 'organization_name'){
            DOMREFUpdate.innerHTML='organization name already in use.';
            window.taken[ whatToCheck ] = 'taken'; 
        }
        else if (whatToCheck == 'notification_email'){
			DOMREFUpdate.innerHTML='email already in use.';
			window.taken[ whatToCheck ] = 'taken'; 
        }
        else if (whatToCheck == 'email'){
            if (document.getElementById('email').value == ''){
                    DOMREFUpdate.innerHTML='&nbsp;';
                    document.getElementById('CheckEmail').value = '';          
            }else{
		            DOMREFUpdate.innerHTML='email already in use.';
		            document.getElementById('CheckEmail').value = 'Yes';
            }
        }

    }else{
        
        if (whatToCheck == 'orgOfficialName'){
            DOMREFUpdate.innerHTML='<font color=green>Name is available.</font>';
            window.taken[ whatToCheck ] = 'available'; 
        }
        else if (whatToCheck == 'organization_name'){
            DOMREFUpdate.innerHTML='<font color=green>organization name available.</font>';
            window.taken[ whatToCheck ] = 'available'; 
        }
        else if (whatToCheck == 'notification_email'){
         	DOMREFUpdate.innerHTML='<font color=green>email available.</font>';
         	window.taken[ whatToCheck ] = 'available'; 
        }
        else if (whatToCheck == 'email'){
            if (document.getElementById('email').value == ''){
                    DOMREFUpdate.innerHTML='&nbsp;';
                    document.getElementById('CheckEmail').value = '';          
            }else{
		            DOMREFUpdate.innerHTML='<font color=green>email available.</font>';
		            document.getElementById('CheckEmail').value = 'No';
            }
        }
        

    }
  },
      
  'onFailure':function(transport)
  {
    alert('fail');
  }
  });
}


function goCheckOrganizationPassword()
{

  // what's the pw?
  var orgPassEl = $('organizationPassword');
  var orgPass = orgPassEl.value;
  
  var mm_element = $('organizationNameDropDown');
  var orgName = '';
  
  if( mm_element != null )
  {
    orgName = mm_element.options[ mm_element.selectedIndex ].innerHTML;
  }
  
  if( orgName == '' )
  {
    var enterYourself = $('organizationNameTextEntry').value;
    if( enterYourself == '')
    {
      return; // no org selected, so don't bother checking
    }
    else
    {
      orgName = enterYourself; // use the text entered self
    }
  }
    
  //alert("checking if " + orgName + " has pw " + orgPass );
  if( window.root == null ){ alert('Cannot contact server!'); }
  
  new Ajax.Request(
    
    window.root + '/servlet/CheckTaken',
    {
      'method':'post',
      'parameters': {
        'requestType':'check_MM_Org_Password',
        'mm_org_name':orgName,
        'mm_pass'    :orgPass
      },
      
      'onSuccess':function(transport)
      {
        //alert("ok " + transport.responseText );
        var resp = String( transport.responseText );
        resp = resp.trim();
        
        if( resp == 'Yes' )
        {
          $('orgPassMsg').innerHTML='<span><i>correct password</i></span>';
          // clear any errors
          clearErr( orgPassEl );
          window.taken['orgPass'] = 'correct';
        }
        else
        {
          $('orgPassMsg').innerHTML='<span style="color:red"><b>incorrect password</b></span>';
          window.taken['orgPass'] = 'wrong';
          putErr( orgPassEl, 'The password you entered was wrong' );
        }
      },
      'onFailure':function(transport)
      {
        new AlertBox({'title':'Sorry!','body':'Could not contact server!'});
        putErr( orgPassEl, 'The password you entered was wrong' );
        window.taken['orgPass'] = 'wrong';
      }
    }
  
  );
}


function toggleChildCheckbox( el )
{
  var i = el.getElementsByTagName("input")[0];
  if( i.checked ) i.checked = null;
  else i.checked="checked";
}

function cancelBubble( event )
{
  event.cancelBubble = true;
}

window.taken = {
//  'id':'available',   // use 'use_id' instead of this
  'user_id':'available',
  'alias':'available',
  'email':'available',
  'orgPass':'correct',
/*  'personalEmail':'available',
  'businessEmail':'available',
  'notification_email':'available',
*/
  'organization_name':'available',
  
  'orgOfficialName':'available'

};
  


function orgEnterYourselfChanged( eta )
{
  $('organizationNameDropDown').selectedIndex = 0; // push this back to blank
  if( eta.value == '' )
  {
    // clear the error that has to do with org pass
    window.taken['orgPass'] = 'correct';
    clearErr( $('organizationPassword') );
    $('organizationPassword').value = ''; // clear out any entered password
    $('orgPassMsg').innerHTML='';
  }
  else
  {
    // change the name to use.. use the text entry field
    $('organizationNameTextEntry').name = 'mm_parent_org_name';
    $('organizationNameDropDown').name = '';
    goCheckOrganizationPassword();
  }
}

function clearSelect(dropdown)
{
//	var item = dropdown; 
	for (i=dropdown.length; i>0; i--)
	{
		dropdown.remove(i);
	}
}

function selectedOrganizationTypeChanged(dropdown) 
{
	selectedOrganizationTypeChanged(dropdown, "");
}

function selectedOrganizationTypeChanged(dropdown, disableOrgName) 
{
	var mm_element = $('organizationTypeDropDown');
	  var item = document.getElementById('organizationNameDropDown');
	  var orgType = '';
	  
	  clearSelect(item);
	  if( mm_element != null )
	  {
	  	if (mm_element.selectedIndex == 0) {
	  		return;
	  	}
	    orgType = mm_element.options[ mm_element.selectedIndex ].innerHTML;
	  }
	  

	  if( window.root == null ){ alert('Cannot contact server!'); }
	  
	  new Ajax.Request(
	    
	    window.root + '/servlet/GetMasterMemberName',
	    {
	      method:'post',
	      parameters: {'requestType':'orgNameList','value':orgType },
	      asynchronous:false,
	      onSuccess:function(transport)
	      {
	        var resp = String( transport.responseText );
	        resp = resp.trim();
	        var orgNames = new Array();
	        orgNames=resp.split(",");
	        
	        for (i=0; i<orgNames.length; i++){
	        	
	        	var newItem=document.createElement('option');
	        	newItem.text=orgNames[i];
	        	
	        	if (orgNames[i] == disableOrgName){		// disable if it's user's orgName
		        	newItem.disabled = true;
	        	}
	        	
	        	try {
	        		item.add(newItem, null);	// standard compliant
	        	}
	        	catch(e){
	        		item.add(newItem);			// IE only
	        	}
	        }
	      },
	      onFailure:function(transport)
	      {
	        new AlertBox({'title':'Sorry!','body':'Could not contact server!'});
	       }
	    }
	  );
	
}

function selectedOrganizationIndexChanged( dropdown )
{
  if( dropdown.selectedIndex != 0 )
  {
    // use the dropdown, NOT text area
    $('organizationNameTextEntry').value = ''; // clear out manually entered stuff
    $('organizationNameTextEntry').name = '';
    $('organizationNameDropDown').name = 'mm_parent_org_name';
    
    goCheckOrganizationPassword();
  }
  else if( $('organizationNameTextEntry').value == '' )
  {
    // they picked the 0 element
    window.taken['orgPass'] = 'correct';
    clearErr( $('organizationPassword') );
    $('organizationPassword').value = ''; // clear out any entered password
    $('orgPassMsg').innerHTML='';
  }
}



function updateAvailableCountries( idOfSelectElCountry, idOfSelectElProvince, idOfManualEntry, nameforsubmission )
{
  var selectElProvince = $( idOfSelectElProvince );
  var selectElCountry =  $( idOfSelectElCountry );
  var manualEntry = $( idOfManualEntry );
  
  // now we want to add some more elements to the
  // select element.
  selectElProvince.update('');
  
  // first option always a blank
  // with value 0
  var newOption = new Element
      ('option', { 'value': '0' }).update( '' );
  selectElProvince.insert( newOption );
      
  var newOptions = window.countryProvinces[ selectElCountry.value ]; // index that object.
  
  if( newOptions != null ) // if exists... switch to 'automatic' mode.
  {
    clearErr( manualEntry ); //clear if any err
    //manualEntry.disabled = 'disabled' ;
    //selectElProvince.disabled = null;
    
    $('automaticProvinceEntryDiv').show();
    $('manualProvinceEntryDiv').hide();
    selectElProvince.name = nameforsubmission; 
    manualEntry.name = null;  // don't post this back now.
    
    // fill that selectProvince with shit
    for ( var i = 0 ; i < newOptions.length ; i++ )
    {
      var newOption = new Element ('option', { 'value': newOptions[i] }).update( newOptions[i] );
      selectElProvince.insert( newOption );
    }
  }
  else
  {
    // there are no province options available.
    // enable the text field
    $('automaticProvinceEntryDiv').hide();
    $('manualProvinceEntryDiv').show();
    selectElProvince.name = null; // don't post this back now.
    manualEntry.name = nameforsubmission;
    
    clearErr( selectElProvince ); //clear if any err
    //manualEntry.disabled = null ; // erase that attribute.
    //selectElProvince.disabled = 'disabled';
  }
  
  // 
}



function updateAvailableProvinces( idOfSelectElCountry, 
  idOfSelectedProvince, idOfSelectElProvince, idOfManualEntry, nameforsubmission )
{
  if($('selectedProvinceEntryDiv') != null){
     $('selectedProvinceEntryDiv').style.display = "none";
  }
  if($('inputedProvinceEntryDiv') != null){
     $('inputedProvinceEntryDiv').style.display = "none";
  }
  var selectElProvince = $( idOfSelectElProvince );
  var selectElCountry =  $( idOfSelectElCountry );
  var manualEntry = $( idOfManualEntry );
  
  // now we want to add some more elements to the
  // select element.
  selectElProvince.update('');
  
  // first option always a blank
  // with value 0
  var newOption = new Element
      ('option', { 'value': '0' }).update( '' );
  selectElProvince.insert( newOption );
      
  var newOptions = window.countryProvinces[ selectElCountry.value ]; // index that object.
  
  if( newOptions != null ) // if exists... switch to 'automatic' mode.
  {
    clearErr( manualEntry ); //clear if any err
    //manualEntry.disabled = 'disabled' ;
    //selectElProvince.disabled = null;
    
    $('automaticProvinceEntryDiv').show();
    $('manualProvinceEntryDiv').hide();
    selectElProvince.name = nameforsubmission; 
    manualEntry.name = null;  // don't post this back now.
    
    // fill that selectProvince with shit
    for ( var i = 0 ; i < newOptions.length ; i++ )
    {
      var newOption = new Element
      ('option', { 'value': newOptions[i] }).update( newOptions[i] );
      selectElProvince.insert( newOption );
    }
  }
  else
  {
    // there are no province options available.
    // enable the text field
    $('automaticProvinceEntryDiv').hide();
    $('manualProvinceEntryDiv').show();
    selectElProvince.name = null; // don't post this back now.
    manualEntry.name = nameforsubmission;
    
    clearErr( selectElProvince ); //clear if any err
    //manualEntry.disabled = null ; // erase that attribute.
    //selectElProvince.disabled = 'disabled';
  }
  // 
}

