// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Prototype functions to extend nextSibling and previousSibling so that they ignore white space.
function nextSiblingElement(elem) {
  do {
    elem = elem.nextSibling;
  } while (elem && elem.nodeType == 3);
  return elem;
}

function previousSiblingElement(elem) {
  do {
    elem = elem.previousSibling;
  } while (elem && elem.nodeType == 3);
  return elem;
}

// MIMI Javascript

function selectLetter(letter_link)
{
  links = $('alphabet_container').getElementsByTagName("a");
  for(i = 0; i < links.length; i++){links[i].className = ""};
  if(letter_link){letter_link.className = "current"};
}

function updateStatus(val, update)
{
	if (val)
		$(update).update('<img src="/images/ok.png" />')
	else
		$(update).update('<img src="/images/bad.png" />')
	return val
}

function checkLength(el, update, length)
{
	return updateStatus($F(el).length >= length, update)
}

function checkMatch(el1, el2, update)
{
	return updateStatus($F(el1) == $F(el2), update)
}

//regex=/^[A-Z]{4}[A-Z0-9_]*$/i; (This regex would check for valid login)
function checkRegex(elmnt, update, regex)
{
	return updateStatus(($F(elmnt).match(regex)), update)
}

function checkSelected(elmnt, update)
{
	len = $(elmnt).length
	i = 0
	selected = false

	for (i = 0; i < len; i++) {
		if (!$(elmnt)[i].selected) {
			selected = true
			break
		}
	}
	
	alert(selected)

	return updateStatus(selected,update)
}

function selectServiceForWorkflow(name, value)
{
	if (value != '~'){
		new_el = '<li class="workflow-service" style="display:list-item"><image class="handle" src="/images/move.png" style="float:right;"/><img src="/images/delete.gif" style="cursor:pointer;float:right;padding: 2px 0"" onclick="this.parentNode.remove()" />' + name + '<input type="hidden" id="services[]" name="services[]" value="'+ value +'"/><div class="clear"></div></li>'
		$('workflow_services').insert(new_el ,{ position: 'bottom' })
	}	
	Sortable.create("workflow_services", {onUpdate:"nothing()", only:'workflow-service', tag:'li', handle:'handle'})
}

function newFieldOption()
{
	new_el = '<li class="field-option" style="display:list-item"><image class="handle" src="/images/move.png" style="float:right;"/><img src="/images/delete.gif" style="float:right;padding:4px 0;cursor:pointer;" onclick="this.parentNode.remove()" /><input type="text" name="options[]" /><div class="clear"></div> </li>'
	$('field_options').insert(new_el ,{ position: 'bottom' })
	Sortable.create("field_options", {onUpdate:"nothing()", only:'field-option', tag:'li', handle:'handle'})
}

function newPhoneNumber()
{
  phone_i = $('contact_phones_counter').value
  $('contact_phones_counter').value = parseInt($('contact_phones_counter').value, 10) + 1
  new_el = '<li class="phone_number" style="display:list-item"><image class="handle" src="/images/move.png" style="float:right;"/><img src="/images/delete.gif" style="float:right;padding:4px 0;cursor:pointer;" onclick="this.parentNode.remove()" /><input id="contact_phone_'+phone_i+'" type="text" name="numbers[]" /> <select name="number_types[]" style="width:150px;"><option value="Lab Phone" selected="selected">Lab Phone</option><option value="Work Phone">Work Phone</option><option value="Cell Phone">Cell Phone</option><option value="Home Phone">Home Phone</option><option value="Secretary Phone">Secretary Phone</option><option value="Other Phone">Other Phone</option></select> <span id="contact_phone_'+phone_i+'_status"></span><div class="clear"></div></li>'
	$('phone_numbers').insert(new_el ,{ position: 'bottom' })
	$('phone_numbers').insert('<script type="text/javascript">\n\nnew Form.Element.Observer(\'contact_phone_'+phone_i+'\', 0.25, function(element, value) {checkRegex(\'contact_phone_'+phone_i+'\', \'contact_phone_'+phone_i+'_status\', /^(.)*\\d{3}(.)*\\d{3}(.)*\\d{4}(.)*$/)})\n\n</script>',{ position: 'bottom' })
  Sortable.create("phone_numbers", {onUpdate:"nothing()", only:'phone_number', tag:'li', handle:'handle'})
}

function newEmailAddress()
{
  email_i = $('user_emails_counter').value
  $('user_emails_counter').value = parseInt($('user_emails_counter').value, 10) + 1
  new_el = '<li class="email_address" style="display:list-item"><image class="handle" src="/images/move.png" style="float:right;"/><img src="/images/delete.gif" style="float:right;padding:4px 0;cursor:pointer;" onclick="this.parentNode.remove()" /><input id="user_email_'+email_i+'" type="text" name="emails[]" /> <select name="email_types[]" style="width:150px;"><option value="Secretary Email" selected="selected">Secretary Email</option><option value="Work Email">Work Email</option><option value="Other Email">Other Email</option></select> <span id="user_email_'+email_i+'_status"></span><div class="clear"></div></li>'
  $('email_addresses').insert(new_el ,{ position: 'bottom' })
  $('email_addresses').insert('<script type="text/javascript">\n\nnew Form.Element.Observer(\'user_email_'+email_i+'\', 0.25, function(element, value) {checkRegex(\'user_email_'+email_i+'\', \'user_email_'+email_i+'_status\', /^( )*[A-Z0-9._%-]+@([A-Z0-9-]+\\.)+[A-Z]{2,4}( )*$/i)})\n\n</script>',{ position: 'bottom' })
  Sortable.create("email_addresses", {onUpdate:"nothing()", only:'email_address', tag:'li', handle:'handle'})  
}

function selectField(con, name, value, hidden)
{
	if (value != '~'){
		new_el = '<li class="custom-fields" style="display:list-item"><image class="handle" src="/images/move.png" style="float:right;"/><img src="/images/delete.gif" style="float:right;padding: 2px 0;cursor:pointer" onclick="this.parentNode.remove()" />' + name + '<input type="hidden" id="request_fields[]" name="'+hidden+'" value="'+ value +'"/><div class="clear"></div></li>'
		$(con).insert(new_el ,{ position: 'bottom' })
	}	
	Sortable.create(con, {onUpdate:"nothing()", only:'custom-fields', tag:'li', handle:'handle'})
}

function nothing()
{}

function showPricingOptions(value, id, itemID)
{
	switch(value)
	{
	case 0://flat
		$('price_1_'+itemID).hide()
		$('price'+id+'[tier_price]').hide()
		$('price_2_'+itemID).hide()
		$('price'+id+'[tier_threshold]').hide()
		$('price_3_'+itemID).hide()
		break
	case 1://per sample
		$('price_1_'+itemID).update('per sample')
		$('price_1_'+itemID).show()
		$('price'+id+'[tier_price]').hide()
		$('price_2_'+itemID).hide()
		$('price'+id+'[tier_threshold]').hide()
		$('price_3_'+itemID).hide()		
		break
	case 2://per hour
		$('price_1_'+itemID).update('per hour, $')
		$('price_1_'+itemID).show()
		$('price'+id+'[tier_price]').show()
		$('price_3_'+itemID).show()
		$('price_3_'+itemID).update('max per 24 hours')
		$('price'+id+'[tier_threshold]').hide()
		$('price_2_'+itemID).hide()				
		break
	case 3://tiered samples
		$('price_1_'+itemID).update('for first')
		$('price_1_'+itemID).show()
		$('price'+id+'[tier_price]').show()
		$('price_2_'+itemID).show()
		$('price_2_'+itemID).update('samples, $')
		$('price'+id+'[tier_threshold]').show()
		$('price_3_'+itemID).show()
		$('price_3_'+itemID).update('for each additional sample')
		break
	case 4://tiered times
		$('price_1_'+itemID).update('for first hour, $')
		$('price_1_'+itemID).show()
		$('price'+id+'[tier_price]').show()
		$('price_3_'+itemID).show()
		$('price_3_'+itemID).update('per 1/2 hour')
		$('price'+id+'[tier_threshold]').hide()
		$('price_2_'+itemID).hide()				
		break
	}
}

function showLoading(){if($('loading')) $('loading').show()}

function hideLoading(){if($('loading')) $('loading').hide()}

function selectItemField(con, name, value, hidden)
{
	if (value != '~' && !$(hidden+'_'+value)){
		new_el = '<li id="'+hidden+'_'+value+'">'+name+' <img src="/images/delete.gif" style="vertical-align:middle;cursor:pointer"onclick="$(\''+hidden+'_'+value+'\').remove()" /><input type="hidden" name="'+hidden+'[]" value="'+value+'" /></li>'
		$(con).insert(new_el ,{ position: 'bottom' })
	}	
}

function selectItemFieldWithPrice(con, name, value, hidden, priceBlock, checked)
{
	if (value != '~' && !$(hidden+'_'+value)){
		new_el = '<li id="'+hidden+'_'+value+'">'+name+' <img src="/images/delete.gif" style="vertical-align:middle;cursor:pointer"onclick="$(\''+hidden+'_'+value+'\').remove()" /><input type="hidden" name="'+hidden+'[]" value="'+value+'" /> <label for="'+hidden+'_'+value+'_priced">priced</label><input id="'+hidden+'_'+value+'_priced" type="checkbox" name="price_equipment['+value+']"  onclick="$$(\'.price_row_'+value+'\').invoke(this.checked ? \'show\' : \'hide\') " '+(checked ? 'checked="checked"' : '')+'/></li>'
		$(con).insert(new_el ,{ position: 'bottom' })
		$(hidden+'_'+value).insert('<table>'+priceBlock.gsub(/\~unq_id\~/, value)+'</table>', { position: 'bottom'})
	}	
}

function showMenu(container, menu, menuID)
{
	if ($(menuID))
		$(menuID).show()
	else
		$(container).insert(menu ,{ position: 'bottom' })
}

function updateTotalOld()
{
	total = 0.0
	$$('.service-cost').each(function (item) {
		if (!item.disabled)
			total += parseFloat(item.value)
	})
	$('total_cost').value = total
}

// This one is used in conjunction with the discounts
function updateTotal()
{
	total = 0.0
	$$('.discounted-service-cost').each(function (item) {
		if (!item.disabled)
			total += parseFloat(item.value)
	})
	$('total_cost').value = total
}

function updateDiscountCost(position, price_element){
  element = $('invoice_items_'+position+'_discounted_cost');
  span_element = $('discounted_cost_'+position)
  price = price_element.value
  discount = $('invoice_items_'+position+'_discount').value
  discounted_cost = Math.round((price * (1.0 - discount))*100)/100;
  element.value = discounted_cost
  span_element.innerHTML = discounted_cost;
}

// Collect all the project_ids and study_ids
// Then for each unique project_id|study_id put those notes into the project_notes|study_notes container
// Then fill the session_group_notes container, and the session_notes container
function updateNotes(){
  var project_ids = new Array();
  var study_ids = new Array();
  $$('.project_id').each(function (item) {
		if (!item.disabled){
		  session_group_id = item.id.substring(14).substring(0, item.id.substring(14).indexOf('_'));
		  project_notes = $('session_group_'+session_group_id+'_project_notes').value
		  project_ids.push('<div class="project_id_'+item.value+'_notes">' + project_notes + '</div>')
		}
	});
  project_ids = project_ids.uniq();
	$$('.study_id').each(function (item) {
		if (!item.disabled){
		  session_group_id = item.id.substring(14).substring(0, item.id.substring(14).indexOf('_'));
		  study_notes = $('session_group_'+session_group_id+'_study_notes').value
		  study_ids.push('<div class="study_id_'+item.value+'_notes">' + study_notes + '</div>')
		}
	});
  study_ids = study_ids.uniq();
  
  all_project_notes = '';
  project_ids.each(function(project_tuple) {
    all_project_notes += project_tuple
  });
  
  all_study_notes = '';
  study_ids.each(function(study_tuple) {
    all_study_notes += study_tuple
  });
  
  all_session_group_notes = '';
  $$('.session_group_notes').each(function (item) {
		  all_session_group_notes += '<div>' + item.value + '</div>'
	});
  
  all_session_notes = '';
  $$('.session_notes').each(function (item) {
		  all_session_notes += '<div>' + item.value + '</div>'
	});
  
  $('project_notes').innerHTML = all_project_notes;
  $('study_notes').innerHTML = all_study_notes;
  $('session_group_notes').innerHTML = all_session_group_notes;
  $('session_notes').innerHTML = all_session_notes;
  
}

function serializeInvoiceItem(i)
{
	params = ''
	params += 'service_id=' + $F('invoice_items['+i+'][service_id]')
	if ($('invoice_items['+i+'][equipment_id]'))
		params += '&equipment_id=' + $F('invoice_items['+i+'][equipment_id]')
	if ($('invoice_items['+i+'][operator_id]'))
		params += '&operator_id=' + $F('invoice_items['+i+'][operator_id]')
	params += '&numsamples=' + $F('invoice_items['+i+'][numsamples]')
	params += '&duration=' + $F('invoice_items['+i+'][duration]')
	return params
}

function deleteItem(i)
{
	els = ['service_id','equipment_id','operator_id','numsample','duration','cost']
	if ($F('invoice_items['+i+'][deleted]') == 'true') {
		$('item_'+i).removeClassName('deleted')
		$('invoice_items['+i+'][deleted]').value = 'false'
		els.each(function (s) {
			if ($('invoice_items['+i+']['+s+']'))
				$('invoice_items['+i+']['+s+']').enable()
		})
	}else{
		$('item_'+i).addClassName('deleted')
		$('invoice_items['+i+'][deleted]').value = 'true'
		els.each(function (s) {
			if ($('invoice_items['+i+']['+s+']'))
				$('invoice_items['+i+']['+s+']').disable()
		})
	}
	updateTotal()
}

function addAllAttributes()
{
	$('available_attributes').childElements().each(function (e){
		$('selected_attributes').insert(e)
	})
	
}

function resetReport()
{
	$('selected_anchors').childElements().each(function (e){
		$('available_anchors').insert(e)
	})
  if($('selected_attributes')){
	  $('selected_attributes').childElements().each(function (e){
  		$('available_attributes').insert(e)
  	}) 
  }
  $('status_pending').checked = false
  $('status_approved').checked = false
  $('status_completed').checked = false
  $('status_invoiced').checked = false
  $('status_audited').checked = false
	updateAnchors();
}

function updateAnchors()
{
  $('selected_anchors').childElements().each(function (a){
    $(a).childElements().each(function (e){ 
      if(e.innerHTML == "+"){
        e.style.display = "none";
      }else if(e.innerHTML == "-"){
        e.style.display = "inline";
      }
    });
  });
  $('available_anchors').childElements().each(function (a){
    $(a).childElements().each(function (e){ 
      if(e.innerHTML == "+"){
        e.style.display = "inline";
      }else if(e.innerHTML == "-"){
        e.style.display = "none";
      }
    });
  });
}

// For User Report Page
function addSingleAnchor(anchor)
{
  $('selected_anchors').innerHTML += "<div class=\"anchor report-item\" id=\"selected_" + anchor + "\">" + $(anchor).innerHTML + "</div>";
  $(anchor).innerHTML = anchor.substring(7);
  selected_anchor = 'selected_' + anchor;
  $(selected_anchor).childElements().each(function(e){
    if(e.innerHTML == "+"){
      e.style.display = "none";
    }
    else if(e.innerHTML == "-"){
      e.style.display = "inline";
    }
  });
  $(anchor).childElements().each(function(e){
    if(e.innerHTML == "+"){
      e.style.display = "none";
    }
    else if(e.innerHTML == "-"){
      e.style.display = "inline";
      e.style.color = "#fff";
    }
  });
  makeAnchorsSortable();
  $(anchor).parentNode.style.background = "#cfe2f6";
  $(anchor).style.background = "#205593";
  $(anchor).style.color = "#fff";
}

// For User Report Page
function removeSingleAnchor(anchor)
{
  selected_anchor = 'selected_' + anchor;
  $(anchor).innerHTML = $(selected_anchor).innerHTML;
  $(anchor).childElements().each(function(e){
    if(e.innerHTML == "+"){
      e.style.display = "inline";
    }
    else if(e.innerHTML == "-"){
      e.style.display = "none";
      e.style.color = "#205593";
    }
  });
  $(selected_anchor).remove();
  $(anchor).parentNode.style.background = "#fff";
  $(anchor).style.background = "#efefef";
  $(anchor).style.color = "#3f3f3f";
}

// For User Report Page
function addUserAnchors(anchors)
{
  anchors.each(function (a){
    addSingleAnchor(a);
	});
  makeAnchorsSortable();
}

function makeAnchorsSortable()
{
  Sortable.create('selected_anchors', {only:'anchor', tag:'div', containment:['selected_anchors'], dropOnEmpty: true});
}

function resetUserReport()
{
  $('selected_anchors').childElements().each(function (e){
    removeSingleAnchor(e.id.substring(9));
	});
}

// For Reports Page (not user report)
function addAnchors(anchors)
{
	anchors.each(function (a){
		$('selected_anchors').insert($(a))
	})
	updateAnchors();
}

function removeAnchors(anchors)
{
  anchors.each(function (a){
    $('available_anchors').insert($(a))
  })
  updateAnchors();
}

function addAttributes(attributes)
{
	attributes.each(function (a){
		$('selected_attributes').insert($(a))
	});	
}

function addSessionStatus(sessions)
{
  sessions.each(function (a){
    $(a).checked = true;
  });
}

function getName()
{
  $('overwrite').value = "true"
  if($('user_report_configuration_id').selectedIndex == 0){
    var name = prompt ("Enter a name for your configuration:","");
    if(name == null) return;
    $('name').value = name;    
  }
  else{
    var answer = confirm ("Overwrite the selected configuration?")
    if (answer){
      $('overwrite').value = "true"
    }
    else{
      $('overwrite').value = "false"
      return;
    }
  }
}

function getCaseID()
{
  var caseid = prompt ("Enter a the Case ID:","");
  if(caseid == null) return;
  $('switch_to_caseid').value = caseid;
}

function goto(s)
{
	url = window.location.href
	if (url.indexOf('#')>-1)
		url = url.substring(0,url.indexOf('#'))
	window.location = url + '#' + s
}

function invoiceCheckBoxes()
{
	first = $$('.session_group_box').find(function(b) {return b.checked})
	if (first != undefined){
		sp_class = first.classNames().find(function(s) {return s.match(/^sp_/)})
		$$('.session_group_box').each(function (el){ el.hasClassName(sp_class) ? el.enable() : el.disable()	})
	}else{
		$$('.session_group_box').invoke('enable')
	}	
}

function showStudies(pid)
{
	$('studies_'+pid).toggle(); 
	$('arrow_'+pid).src = ($('studies_'+pid).visible() ? '/images/downarrow.png' : '/images/rightarrow.png');
	return $('studies_'+pid).visible()
}

function disableCaseID()
{
  if(($('user_login').value == '' || $('user_login').value == null) && ($('user_password').value == '' || $('user_password').value == null) && ($('user_password_confirmation').value == '' || $('user_password_confirmation').value == null) )
  {
    $('user_caseid').disabled = '';
  }
  else
  {
    $('user_caseid').disabled = 'disabled';
    $('caseid_status').update('');
  }
}

function disableLogin()
{
  if($('user_caseid').value == '')
  {
    $('user_login').disabled = '';
    $('user_password').disabled = '';
    $('user_password_confirmation').disabled = '';
  }
  else
  {
    $('user_login').disabled = 'disabled';
    $('user_password').disabled = 'disabled';
    $('user_password_confirmation').disabled = 'disabled';
    $('login_status').update('');
    $('password_status').update('');
    $('password_confirmation_status').update('');
    
  } 
}

function checkCaseIDLogin(){
  disableLogin();
  disableCaseID();
}

function disableSubmit(disable)
{
  $('session_group_submit').disabled = disable;
}

function updateSubmit()
{
  disable = '';
  if($('selected_services').childElements().length == 0)
  {
    disable = 'disabled';
  }
  $('selected_services').childElements().each(function (item) {
    uniq_id = item.id.substring(8);
    if($('session_'+uniq_id+'_time_interval') && $('session_'+uniq_id+'_time_interval').value == '')
    {
//      alert('session'+uniq_id + '_time_interval'+' has not been scheduled.');
      disable = 'disabled';
    }
	})
	if(!($('session_group_study_id').value)){
	  disable = 'disabled'
	}
	$('session_group_submit').disabled = disable;
}

function updateProgram()
{
  disable = '';
  if(!$('user_membership').checked)
  {
    disable = 'disabled';
    // $('user_program_id').selectedIndex = 0;
    // $('user_membership_type').selectedIndex = 0;
  }
  $('user_program_id').disabled = disable;
  $('user_program_secondary_id').disabled = disable;
  $('user_membership_type').disabled = disable;
}

function getHours(time_string){
  if(time_string.substring(5) == "PM"){
    if(time_string.substring(0, 2) == "12"){
	  hours = 12;
	}
	else{
	  hours = parseInt(time_string.substring(0, 2), 10) + 12;
	}
  }
  else if(time_string.substring(0, 2) == "12"){
    hours = 0;
  }
  else{
    hours = parseInt(time_string.substring(0, 2), 10);
  }
  alert("HOURS_TimeString: "+time_string+"\nhours: "+hours);
  return hours;
}

function getMinutes(time_string){
  minutes = '49'
  alert("MINUTES_TimeString: "+time_string+"\nminutes: "+minutes);
  return minutes;
}

function sortSessions(){

  if($('workflowList')){
    $('workflowList').selectedIndex = 0;
  }
  
  rows = $('selected_services').childNodes;
	prevDate = nextDate = misplaced_index = misplaced_date = null;
	
	for (i = 0; i < rows.length; i++) {
		dateTime_input = $('session_' + rows[i].id.substring(8) + '_time_interval');
		if (dateTime_input && dateTime_input.value.length) {
			date_time = dateTime_input.value;
			if (prevDate) {
        nextDate = getStartDate(date_time);
				if (nextDate - prevDate < 0) {
				  for(j = 0; j < misplaced_index; j++){
					  dateTime_input = $('session_' + rows[j].id.substring(8) + '_time_interval');
		        if (dateTime_input && dateTime_input.value.length) {
              tempDate = getStartDate(dateTime_input.value);
					    if (prevDate - tempDate <= 0) {
						    misplaced_date = prevDate;
						    break;
					    }
				    }
				  }
				  if(!misplaced_date){
				    for(j = i+1; j < rows.length; j++){
					    dateTime_input = $('session_' + rows[j].id.substring(8) + '_time_interval');
		          if (dateTime_input && dateTime_input.value.length) {
                tempDate = getStartDate(dateTime_input.value);
					      if (tempDate - prevDate <= 0) {
					        misplaced_date = prevDate;
					  	    break;
					      }
				      }
				    }
				  }
          if(!misplaced_date){
				    misplaced_index = i;
            misplaced_date = getEndDate($('session_' + rows[misplaced_index].id.substring(8) + '_time_interval').value);
				  }
				  for(j = 0; j < rows.length; j++){
				  	if(j != misplaced_index){
					  dateTime_input = $('session_' + rows[j].id.substring(8) + '_time_interval');
		          if (dateTime_input && dateTime_input.value.length) {
                tempDate = getStartDate(dateTime_input.value)
					      if (misplaced_date - tempDate <= 0) {
					  	    $('selected_services').insertBefore(rows[misplaced_index], rows[j]);
						      return;
					      }
				      }
					  }
				  }
				  $('selected_services').insertBefore(rows[misplaced_index], rows[rows.length-1].nextSibling);
				  return;			
				}
			}
      prevDate = getEndDate(date_time);
			misplaced_index = i;
		}
	}
	sessionsUpdatePositions();
}

function markAll(tbody, isChecked){
  if(tbody){
    tbody.childElements().each(function(el){
      if(tr_el = el.childElements()[0]){
        if(td_el = tr_el.childElements()[0]){
          if(td_el.tagName == "INPUT"){
            td_el.checked = isChecked;
          }
        }
      };
    }); 
  }
}

function markStudies(element)
{
  input_fields = element.parentNode.getElementsByTagName("input")
  project_id = parseInt(element.id.substring(12));
  for(j = 0; j < input_fields.length; j++){
    if(parseInt(input_fields[j].getAttribute("project_id")) == project_id){
      input_fields[j].checked = element.checked
    }
  }
}

function markProject(element)
{
  project_id = element.getAttribute("project_id")
  project_element = $("project_ids_"+project_id)
  allClear = true
  input_fields = project_element.parentNode.getElementsByTagName("input")
  for(j = 0; j < input_fields.length; j++){
   // if(parseInt(input_fields[j].getAttribute("project_id")) == project_id && !input_fields[j].checked){
   //    allMarked = false
   //  }
    if(parseInt(input_fields[j].getAttribute("project_id")) == project_id && input_fields[j].checked){
      allClear = false
    }
  }
  if(element.checked){
    project_element.checked = true
  }
  if(allClear){
    project_element.checked = false
  }
}

function updateOperatingHourRows(day){
  if($('facility_'+day+'_closed_all_day').checked){
    $(day+'_td_1').hide()
    $(day+'_td_2').hide()
    $(day+'_td_3').hide()    
  }else{
    $(day+'_td_1').show()
    $(day+'_td_2').show()
    $(day+'_td_3').show()
  }
}

function updateSpecialDayRows(){
  if($('special_day_closed_all_day').checked){
    $('td_1').hide()
  }else{
    $('td_1').show()
  }
}

function insertSession(element, link, title, status, add_padding){
  element.className = 'appointment '+status;
  element.onclick = function() {location.href = link}
  element.title = title
  if(add_padding){
    element.style.marginRight = '2px';
  }
// <div id="equipment_<%= equipment.id %>_timeslot_<%= halfhour %>_<%= @day.wday %>" class="appointment"
//   <% if equipment_session and equipment_session.authorized_users.include?(current_user) %>
//     <%= "title='#{equipment_session.hover_name}'" %>
//     <%= "onclick='location.href=\"#{session_path(equipment_session)}\"'" %>
//     onmouseover='this.style.backgroundColor="#404040";'
//     onmouseout='this.style.backgroundColor="";'
//   <% end %>
// >
// </div>
}

function presetValue(selectBox, val){
  for(i=0;i<selectBox.length;i++){
    if(selectBox.options[i].value==val){
      selectBox.selectedIndex=i
    }
  }
}

function setWeekValue(date_string){
  var currentDate = new Date()
  selectedDate = new Date(date_string)
  // Now offset currentDate to the beginning of the week
  var ONE_DAY = 1000 * 60 * 60 * 24
  beginningOfWeek = new Date( currentDate.getTime() - (ONE_DAY * currentDate.getDay()) );
  
  $("week").value = Math.floor(days_between(selectedDate, beginningOfWeek)/7)*7
}

function selectCurrentMonth(){
  var currentDate = new Date()
  var ONE_DAY = 1000 * 60 * 60 * 24
  var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  beginningOfMonth = new Date( (currentDate.getMonth() + 1) + '/1/' + currentDate.getFullYear() );
  beginningOfNextMonth = new Date( (currentDate.getMonth() + 2) + '/1/' + currentDate.getFullYear() );
  endOfMonth = new Date( beginningOfNextMonth.getTime() - ONE_DAY)
  $('report_start').value = monthname[beginningOfMonth.getMonth()] + ' ' + beginningOfMonth.getDate() + ', ' + beginningOfMonth.getFullYear();
  $('report_end').value = monthname[endOfMonth.getMonth()] + ' ' + endOfMonth.getDate() + ', ' + endOfMonth.getFullYear();
}

function selectCurrentWeek(){
  var currentDate = new Date()
  var ONE_DAY = 1000 * 60 * 60 * 24
  var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  beginningOfWeek = new Date( currentDate.getTime() - (ONE_DAY * currentDate.getDay()) );
  endOfWeek = new Date( beginningOfWeek.getTime() + (ONE_DAY * 6))
  $('report_start').value = monthname[beginningOfWeek.getMonth()] + ' ' + beginningOfWeek.getDate() + ', ' + beginningOfWeek.getFullYear();
  $('report_end').value = monthname[endOfWeek.getMonth()] + ' ' + endOfWeek.getDate() + ', ' + endOfWeek.getFullYear();
}

function selectAnyDate(){
  $('report_start').value = '';
  $('report_end').value = '';
}

function selectToday(){
  var currentDate = new Date()
  var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  $('report_start').value = monthname[currentDate.getMonth()] + ' ' + currentDate.getDate() + ', ' + currentDate.getFullYear();
  $('report_end').value = monthname[currentDate.getMonth()] + ' ' + currentDate.getDate() + ', ' + currentDate.getFullYear();
}

function selectCurrentYear(){
  var currentDate = new Date()
  var ONE_DAY = 1000 * 60 * 60 * 24
  var monthname = new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  beginningOfYear = new Date( '1/1/' + currentDate.getFullYear() );
  beginningOfNextYear = new Date( '1/1/' + (currentDate.getFullYear() + 1) );
  endOfYear = new Date( beginningOfNextYear.getTime() - ONE_DAY)
  $('report_start').value = monthname[beginningOfYear.getMonth()] + ' ' + beginningOfYear.getDate() + ', ' + beginningOfYear.getFullYear();
  $('report_end').value = monthname[endOfYear.getMonth()] + ' ' + endOfYear.getDate() + ', ' + endOfYear.getFullYear();
}

function days_between(date1, date2) {
    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24
    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()
    // Calculate the difference in milliseconds
    var difference_ms = date1_ms - date2_ms
    // Convert back to days and return
    // alert("difference days: " + difference_ms/ONE_DAY + "\nRounded: "+ Math.round(difference_ms/ONE_DAY) + "\nCeil: "+ Math.ceil(difference_ms/ONE_DAY) + "\nFloor: "+ Math.floor(difference_ms/ONE_DAY))
    return Math.ceil(difference_ms/ONE_DAY)
}

function toggleElementVisibility(element){
  if(element.visible()){
    Effect.BlindUp(element)
  }else{
    Effect.BlindDown(element)
  }
}

function showSubMenu(menu_name){
  sub_menus = document.getElementsByClassName('sub-menu');
  for(var i = 0; i < sub_menus.length; i++){
    if( menu_name+'-menu' == sub_menus[i].id && !$(menu_name+'-menu').visible() )
      $(menu_name+'-menu').show();
    else
      sub_menus[i].hide();
  }
}

function windowWidth(){
  var myWidth = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
  } else if( document.documentElement && document.documentElement.clientWidth ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
  } else if( document.body && document.body.clientWidth ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
  }
  
  return myWidth;
}

function windowHeight(){
  var myHeight = 0;
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    myHeight = window.innerHeight;
  } else if( document.documentElement && document.documentElement.clientHeight ) {
    //IE 6+ in 'standards compliant mode'
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && document.body.clientHeight ) {
    //IE 4 compatible
    myHeight = document.body.clientHeight;
  }
  
  return myHeight;
}

function shiftDateForCalendarDateSelect(day_shift){
  $('week').value = parseInt($('week').value) + day_shift;
  
  var ONE_DAY = 1000 * 60 * 60 * 24
  
  $('daily_sessions_day_selection').calendar_date_select.selected_date = new Date($('daily_sessions_day_selection').calendar_date_select.selected_date - (ONE_DAY * -day_shift));
  $('daily_sessions_day_selection').calendar_date_select.refresh();
  
  var monthname=new Array("January","February","March","April","May","June","July","August","September","October","November","December")
  
  $('daily_sessions_day_selection').value = monthname[$('daily_sessions_day_selection').calendar_date_select.selected_date.getMonth()] + ' ' + $('daily_sessions_day_selection').calendar_date_select.selected_date.getDate() + ', ' + $('daily_sessions_day_selection').calendar_date_select.selected_date.getFullYear();
  
}

function setSessionStatus(session_id, status){
  var status_array = new Array('pending', 'approved', 'completed', 'invoiced', 'audited');
  var status_found = false;
  
  $('sessions_'+session_id+'_status').value = status;
  for (i=0;i<status_array.length;i++)
  {
    element = $('session_'+session_id+'_'+status_array[i]+'_status_box')
    if(status_found == true){
      if(element){removeClass(element, status_array[i]);}
    }else{
      if(element){addClass(element, status_array[i]);}
    }
    if(status_array[i] == status){status_found = true}
  }
  
}

function sessionStatusBoxMouseOver(session_id, status){
  element = $('session_'+session_id+'_'+status+'_status_box')
  if(element){addClass(element,'highlight');}
}

function sessionStatusBoxMouseOut(session_id, status){
  element = $('session_'+session_id+'_'+status+'_status_box')
  if(element){removeClass(element, 'highlight');}
}

/*
function setProjectStatus(project_id, status){
  var status_array = new Array('pending', 'approved', 'closed', 'suspended', 'denied');
  var status_found = false;
  
  $('projects_'+project_id+'_status').value = status;
  for (i=0;i<status_array.length;i++)
  {
    element = $('project_'+project_id+'_'+status_array[i]+'_status_box')
    if(status_found == true){
      if(element){removeClass(element, status_array[i]);}
    }else{
      if(element){addClass(element, status_array[i]);}
    }
    if(status_array[i] == status){status_found = true}
  }
  
}

function projectStatusBoxMouseOver(project_id, status){
  element = $('project_'+project_id+'_'+status+'_status_box')
  if(element){addClass(element,'highlight');}
}

function projectStatusBoxMouseOut(project_id, status){
  element = $('project_'+project_id+'_'+status+'_status_box')
  if(element){removeClass(element, 'highlight');}
}

*/

function setObjectStatus(object_id, status, object_model_name, status_array){
  var status_found = false;
  
  $(object_model_name+'s_'+object_id+'_status').value = status;
  for (i=0;i<status_array.length;i++)
  {
    element = $(object_model_name+'_'+object_id+'_'+status_array[i]+'_status_box')
    if(status_found == true){
      if(element){removeClass(element, status_array[i]);}
    }else{
      if(element){addClass(element, status_array[i]);}
    }
    if(status_array[i] == status){status_found = true}
  }
}

function objectStatusBoxMouseOver(object_id, status, object_model_name){
  element = $(object_model_name+'_'+object_id+'_'+status+'_status_box')
  if(element){addClass(element,'highlight');}
}

function objectStatusBoxMouseOut(object_id, status, object_model_name){
  element = $(object_model_name+'_'+object_id+'_'+status+'_status_box')
  if(element){removeClass(element, 'highlight');}
}


function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
		var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

function selectStatusForForm(status){
  checkbox_element = $('status_'+status)
  input_element = $(status+'_status_box')
  if(checkbox_element.checked){
    removeClass(input_element, status);
    checkbox_element.checked = false;
  }else{
    addClass(input_element, status);
    checkbox_element.checked = true;
  }
}

/*
function sessionStatusBoxFormMouseOver(status){
  element = $(status+'_status_box')
  if(element){addClass(element,'highlight');}
}

function sessionStatusBoxFormMouseOut(status){
  element = $(status+'_status_box')
  if(element){removeClass(element, 'highlight');}
}
*/

function objectStatusBoxFormMouseOver(status){
  element = $(status+'_status_box')
  if(element){addClass(element,'highlight');}
}

function objectStatusBoxFormMouseOut(status){
  element = $(status+'_status_box')
  if(element){removeClass(element, 'highlight');}
}

function findGrantIdentifier(grant_id){
  result = null;
  grant_id_elements = $$('.grant_id');
  for (i=0;i<grant_id_elements.length;i++){
    if(grant_id_elements[i].innerHTML == grant_id){
      return grant_id_elements[i].id;
    }
  }
  return result;
}

function selectGrantForInvoice(grant_id){
  grant_element_id = findGrantIdentifier(grant_id)
  if(grant_element_id){
    $('grant_name').value = $(grant_element_id + '_name').innerHTML;
    $('grant_number').value = $(grant_element_id + '_number').innerHTML;
    $('grant_billing_number').value = $(grant_element_id + '_billing_number').innerHTML;
    $('grant_contract_number').value = $(grant_element_id + '_contract_number').innerHTML;
    $('billing_user_id').value = $(grant_element_id + '_billing_user_name').innerHTML;
    $('invoice_grant_name').value = $(grant_element_id + '_name').innerHTML;
    $('invoice_grant_number').value = $(grant_element_id + '_number').innerHTML;
    $('invoice_grant_billing_number').value = $(grant_element_id + '_billing_number').innerHTML;
    $('invoice_grant_contract_number').value = $(grant_element_id + '_contract_number').innerHTML;
    $('invoice_billing_user_id').value = $(grant_element_id + '_billing_user_id').innerHTML;
    $('invoice_program_id').value = $(grant_element_id + '_program_id').innerHTML;
    $('selected_grant_start_date').innerHTML = $(grant_element_id + '_start_date').innerHTML;
    $('selected_grant_end_date').innerHTML = $(grant_element_id + '_end_date').innerHTML;
    $('selected_grant_date_info').innerHTML = getGrantDateInfo(grant_element_id);
  }else{
    $('grant_name').value = null;
    $('grant_number').value = null;
    $('grant_billing_number').value = null;
    $('grant_contract_number').value = null;
    $('billing_user_id').value = null;
    $('invoice_grant_name').value = null;
    $('invoice_grant_number').value = null;
    $('invoice_grant_billing_number').value = null;
    $('invoice_grant_contract_number').value = null;
    $('invoice_billing_user_id').value = null;
    $('invoice_program_id').value = null;
    $('selected_grant_start_date').innerHTML = null;
    $('selected_grant_end_date').innerHTML = null;
    $('selected_grant_date_info').innerHTML = null;
  }
}

function getGrantDateInfo(grant_element_id){
  result = '';
  grant_start_date = new Date($(grant_element_id + '_start_date').innerHTML);
  grant_end_date = new Date($(grant_element_id + '_end_date').innerHTML);
  
  session_min_date = getMinDate();
  session_max_date = getMaxDate();
  today = new Date();
  
  if((grant_start_date <= min_date && grant_end_date >= max_date) && (grant_start_date <= today && grant_end_date >= today)){
    result = 'Grant is currently running, and the session dates fall inside the grant window.';
  }else if(grant_start_date <= min_date && grant_end_date >= max_date){
    result = 'The session dates fall inside the grant window, <span style="color:#F0AA20;">however the invoice date (today) is outside of the grant!</span>';
  }else if(grant_start_date <= today && grant_end_date >= today){
    result = 'Grant is currently running, <span style="color:#F0AA20;">however the session dates fall outside of the grant window!</span>';
  }else{
    result = '<span style="color:#FF0000;">Invalid Grant. The invoice date (today) and the session dates are not inside the grant window. Please select another grant.</span>'
  }
  return result;
}

function gatherDates(class_name){
  session_date_elements = $$('.'+class_name)
  var session_dates = new Array();
  for (i=0;i<session_date_elements.length;i++){
    session_dates.push(new Date(session_date_elements[i].innerHTML));
  }
  return session_dates;
}

function getMinDate(){
  session_dates = gatherDates('session_date');
  min_date = null;
  for (i=0;i<session_dates.length;i++){
    if(session_dates[i] < min_date || min_date == null){
      min_date = session_dates[i]

    }
  }
  // alert('Min Date: ' + min_date)
  return min_date;
}

function getMaxDate(){
  session_dates = gatherDates('session_date');
  max_date = null;
  for (i=0;i<session_dates.length;i++){
    if(session_dates[i] > max_date || max_date == null){
      max_date = session_dates[i]
    }
  }
  // alert('Max Date: ' + max_date)
  return max_date;
}

// Given Grant Start and End Dates, Determine which grant can be used
// for invoicing and place it in the select drop down list 
function updateAvailableGrants(){
  grant_id_elements = $$('.grant_id');
  var grant_positions = new Array();
  
  // Check that the chosen grant start and end date encompass the session mindate and maxdate
  // or that the chosen grant start and end date encompasses today (the invoice date)
  
  min_date = getMinDate();
  max_date = getMaxDate();
  today = new Date();
  
  for (i=0;i<grant_id_elements.length;i++){
    
    // alert(grant_id_elements[i].id + '_end_date')
    grant_start_date = new Date($(grant_id_elements[i].id + '_start_date').innerHTML);
    grant_end_date = new Date($(grant_id_elements[i].id + '_end_date').innerHTML);
    
    if((grant_start_date <= min_date && grant_end_date >= max_date) || (grant_start_date <= today && grant_end_date >= today)){
      if(grant_start_date <= min_date && grant_end_date >= max_date){
        // alert('The grant contains the Min and Max Date:\nGrant Start Date: '+grant_start_date + '\nGrant End Date: '+grant_end_date + '\nMin Date: ' + min_date + '\nMax Date: ' + max_date);
      }
      if(grant_start_date <= today && grant_end_date >= today){
        // alert('The grant contains the Today\'s Date:\nGrant Start Date: '+grant_start_date + '\nGrant End Date: '+grant_end_date + '\nToday\'s Date: ' + today);
      }
      grant_positions.push(grant_id_elements[i].id)
    }else{
      // alert('The grant DOES NOT contain the Min and Max Date: ' + grant_id_elements[i].id + '\nGrant Start Date'+grant_start_date + '\nGrant End Date: '+grant_end_date + '\nMin Date: ' + min_date + '\nMax Date: ' + max_date);
    }
    
    // grant_positions.push(grant_id_elements[i].id);
  }
  // Save current selected grant
  selected_grant_id = $('invoice_grant_id').value

  // Clear Select List
  while($('invoice_grant_id').length > 1){
    $('invoice_grant_id').options[$('invoice_grant_id').length - 1] = null; 
  }
  
  // Add All Grants Back into selection as long as they haven't already been added previously.
  var grant_id_array = new Array();
  for(i=0;i<grant_positions.length;i++){
    txt = $(grant_positions[i] + '_billing_number').innerHTML + " - " + $(grant_positions[i] + '_name').innerHTML;
    val = $(grant_positions[i]).innerHTML;

    if(!grant_id_array.include(val)){
      // alert('Adding '+val+' to array.');
      grant_id_array.push(val);
      $('invoice_grant_id').options.add(new Option(txt, val));      
    }else{
      // alert(val+' already exists in array.')
    }
  }
  
  // Reload the last selected grant if it exists
  $('invoice_grant_id').value = selected_grant_id;
  // alert("selected_grant_id: " + selected_grant_id + "\nselection_box_val: " + $('invoice_grant_id').value);
  selectGrantForInvoice($('invoice_grant_id').value);
}

function getFileNames(){
  result = new Array();
  $$('.file_input').each(function (item) {
    if(item.parentNode.getElementsByTagName("input")[0].checked){
      result.push(item.innerHTML);
    }
  });
  return result.join(',');
}

function updateInvoiceSubmit(){
  disable = '';
  if($('invoice_grant_id').selectedIndex == 0){
    disable = 'disabled';
  }
  $('invoice_submit').disabled = disable;
}