function timesheet_sizer()
{
if (navigator.appName == "Microsoft Internet Explorer")
  {
    if ($('TimeSheetBody').offsetHeight > 300)
      {
      $('TimeSheetContainer').style['height'] = 315;
      }
    else
      {
      $('TimeSheetContainer').style['height']  = $('TimeSheetTable').offsetHeight+15;
      }
  }
else
  {
  if ($('TimeSheetBody').scrollHeight > $('TimeSheetBody').offsetHeight)
    {
    if ($('TimeSheetBody').scrollHeight > 300)
      {
      $('TimeSheetBody').style.height = 300;
      $('TimeSheetContainer').style.height = $('TimeSheetTable').offsetHeight+15;
      }
    else
      {
      $('TimeSheetBody').style.height = $('TimeSheetBody').scrollHeight;
      $('TimeSheetContainer').style.height = $('TimeSheetTable').scrollHeight+15;
      }
    }
  }
}



function createProjectTask(project_id,url) {
  set_max_size('fade');
  div_toggle([],['fade','task_box'],true);
  new Ajax.Updater('task_div',url,{asynchronous:true,evalScripts:true,
                            onComplete:function(request){Element.hide('loading_indicator');Element.show('task_details')},
                            onLoading:function(request){Element.show('loading_indicator');Element.hide('task_details')},
                            parameters:'id='+project_id+'&task_action=new_root'});
  return false;
}

function loadTask(task_id,url){
  $("task_id").value=task_id;
  set_max_size('fade');
  div_toggle([],['fade','task_box'],true);
  new Ajax.Updater('task_div', url, {asynchronous:true, evalScripts:true, 
  onComplete:function(request){Element.hide('loading_indicator');Element.show('task_details')}, 
  onLoading:function(request){Element.show('loading_indicator');Element.hide('task_details')},
  parameters:Form.serialize(document.forms[0])});
  return false;
}
function day_sum_update(jd){
var i, sum
sum = 0
for (i =0; i<tids.length;i++)
  {
    //alert(tids[i])
    if(!isNaN(parseFloat($(tids[i]+"_"+jd).innerHTML)))
    {
      sum += parseFloat($(tids[i]+"_"+jd).innerHTML);
    }
    if(!isNaN(parseFloat($(tids[i]+"_"+jd).value)))
    {
      sum += parseFloat($(tids[i]+"_"+jd).value);
    }
  }
$("d_"+jd).innerHTML = (sum>0)?sum.toFixed(2):"";
return sum;
}
function project_sum_update(project_id){
var i, sum
sum = 0
for (i =0; i<days.length;i++)
  {
    //alert(tids[i])
    if(!isNaN(parseFloat($(project_id+"_"+days[i]).innerHTML)))
    {
      sum += parseFloat($(project_id+"_"+days[i]).innerHTML);
    }
    if(!isNaN(parseFloat($(project_id+"_"+days[i]).value)))
    {
      sum += parseFloat($(project_id+"_"+days[i]).value);
    }
  }
$(project_id+"_sum").innerHTML = (sum>0)?sum.toFixed(2):"";
return sum;
}

function calc_ts_old()
{
/*
if (typeof(days)== 'object' && typeof(tids)== 'object')
{
*/
var i, sum
sum = 0;
for (i=0;i<days.length;i++)
  {
    //alert("Calling day "+days[i]);
    sum +=day_sum_update(days[i]);
  }
  $("total_hours").innerHTML = sum.toFixed(2);
for (i=0;i<tids.length;i++)
  {
    sum +=project_sum_update(tids[i]);
  }
  
//}
}

function calc_ts(task,day)
{
    var hours = 0;
    if(!isNaN(parseFloat($(task+"_"+day).innerHTML)))
    {
      hours = parseFloat($(task+"_"+day).innerHTML);
    }
    if(!isNaN(parseFloat($(task+"_"+day).value)))
    {
      hours = parseFloat($(task+"_"+day).value);
    }
    //alert (ts_elements[task+'_'+day]);
    ts_elements[task+'_'+day] = hours;
    //alert (ts_elements['\''+task+'_'+day+'\'']);
    //update grand total
    ts_total();
    day_and_task_totals(day,task);
}

//calculates ts grand total
function ts_total()
{
  var sum = 0;
  for (var i in ts_elements)
  {
    sum += ts_elements[i]
  }
  $("total_hours").innerHTML = sum.toFixed(2);
}

//updates day total
function day_and_task_totals(day,task)
{
  var day_total =0;
  var task_total = 0;
  for (var i in ts_elements)
  {
    var x = i.split(/_/);
    day_total += x[1]==day ? ts_elements[i] : 0;
    task_total += x[0]==task ? ts_elements[i] : 0;
  }
  $(task+"_sum").innerHTML = (task_total>0)?task_total.toFixed(2):"";
  $("d_"+day).innerHTML = (day_total>0)?day_total.toFixed(2):"";
}

//calculates all totals and shows them; intended to be used on initial load
function ts_setup()
{
  var sum = 0;
  var day_total = new Object();
  var task_total = new Object();
  
  //initialize day_sum
  for (var i = 0; i < days.length; i++)
  {
    day_total[days[i]] = 0;
  }
  
  //initialize task_sum
  for (var i = 0; i < tids.length; i++)
  {
    task_total[tids[i]] = 0;
  }
  
  //calc all totals
  for (var i in ts_elements)
  {
    var x = i.split(/_/);
    sum += ts_elements[i];
    day_total[x[1]] += ts_elements[i];
    task_total[x[0]] += ts_elements[i];    
  }

  //show day calcs
  for (var i = 0; i < days.length; i++)
  {
    $("d_"+days[i]).innerHTML = (day_total[days[i]]>0)?day_total[days[i]].toFixed(2):"";
  }
  
  //show task calcs
  for (var i = 0; i < tids.length; i++)
  {
    $(tids[i]+"_sum").innerHTML = (task_total[tids[i]]>0)?task_total[tids[i]].toFixed(2):"";
  }
  
  //show ts total
  $("total_hours").innerHTML = sum.toFixed(2);

}


//call calculation for ts
//addEvent(window,"load",calc_ts);

//this set is for highlighting an active row in a table
lastclass =''
lastclass2 =''
lastclass3 =''

function setRow(EL)
   {
      lastclass = EL.className ;
      EL.className='actionrow';
   }
   function clearRow(EL)
   {
      EL.className=lastclass;
   }
function setCol(jd)
   {
      lastclass = $("d_"+jd).className ;
      $("d_"+jd).className='actionrow';
      lastclass2 = $("wd_"+jd).className ;
      $("wd_"+jd).className='actionrow';
      lastclass3 = $("wdd_"+jd).className ;
      $("wdd_"+jd).className='actionrow';
   }
   function clearCol(jd)
   {
      $("d_"+jd).className=lastclass;
      $("wd_"+jd).className=lastclass;
      $("wdd_"+jd).className=lastclass;
   }
   
//Cookie extension to Prototype
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire+"; path=/");
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
}


//this function shows message if a timesheet has been edited but not saved
//except when it's to be exported
function unsaved_timesheet()
{
  if (timesheet_changed && $("rout_action").value != "export_excel" && $("rout_action").value != "print_me")
  {
  //div_toggle([],['fade','message_box'],false);
  return "You made chages to the Timesheet that were not saved. If you navigate away they will be lost!";
  //$('fade').style['display'] = 'block';
  //$('message_box').style['display']='block';
  }
}

// setStyleByClass: given an element type and a class selector,
// style property and value, apply the style.
// args:
//  t - type of tag to check for (e.g., SPAN)
//  c - class name
//  p - CSS property
//  v - value
var ie = (document.all) ? true : false;

function setStyleByClass(t,c,p,v){
	var elements;
	if(t == '*') {
		// '*' not supported by IE/Win 5.5 and below
		elements = (ie) ? document.all : document.getElementsByTagName('*');
	} else {
		elements = document.getElementsByTagName(t);
	}
	for(var i = 0; i < elements.length; i++){
		var node = elements.item(i);
		for(var j = 0; j < node.attributes.length; j++) {
			if(node.attributes.item(j).nodeName == 'class') {
				if(node.attributes.item(j).nodeValue == c) {
					eval('node.style.' + p + " = '" +v + "'");
				}
			}
		}
	}
}

//this function designed for company users list
//it hides entries based on the class (A or D) 
// it also adjusts expand/collapse menu
function showUsers(status)
{
  switch (status)
  {
  case 'active':
    setStyleByClass('TR','A','display','');
    setStyleByClass('TR','D','display','none');
    $('users_all').style.display = '';
    $('active_users').style.display = 'none';
    $('inactive_users').style.display = '';
    $('list_title').innerHTML = 'Active Users';
    break;
  case 'inactive':
    setStyleByClass('TR','A','display','none');
    setStyleByClass('TR','D','display','');
    $('users_all').style.display = '';
    $('active_users').style.display = '';
    $('inactive_users').style.display = 'none';
    $('list_title').innerHTML = 'Inactive Users';
    break;
  case 'all':
    setStyleByClass('TR','A','display','');
    setStyleByClass('TR','D','display','');
    $('users_all').style.display = 'none';
    $('active_users').style.display = '';
    $('inactive_users').style.display = '';
    $('list_title').innerHTML = 'All Users';
    break;
  }
}

//validates that timesheet has values that are between 0 and 24 hours
//if there are exceptions then highlights them and provides user with message
function TS_Validate()
{
var valid = true;
var DayArray = document.getElementsByTagName("input");
for (var i=0; i<DayArray.length; i++)
  {
  var DayValue = DayArray[i];
  if (DayValue.type == 'text' && DayValue.value !='')
    {
      if (isNaN(DayValue.value))
        {
          DayValue.style.color = 'red';
          valid = false;
        }
      else
        {
          if (DayValue.value < 0 || DayValue.value > 24)
            {
              DayValue.style.color = 'red';
              valid = false;
            }
          else
            {
              timesheet_changed = false;
            }
          }
    }
  }
if (!valid)
  {
    alert("Timesheet entries highlighted in red are not valid. Please correct!");
  }
return valid;
}

//validates minimum hours restriction before main validation process;
//0 means no validation required
//intendent to be used for submit for approval only

function TS_Validate_submit()
{
  if (submit_min_hours > 0 && parseFloat($("total_hours").innerHTML)<submit_min_hours) 
  {
    alert("Timesheet could not be submitted for approval. Minimum of "+submit_min_hours+" hours should be reported.");
    return false;
  }
  return TS_Validate()
}

//issue a warning if timesheet was modified, but not saved before export
function ts_export(action)
{
  $("rout_action").value = action
  if (timesheet_changed)
  {
  return confirm("Timeseet was modified, but not saved. Changes will not be exported. Proceed?");
  }
}
//helper function to show context help window
function show_context_help(url,topic,e)
{
Element.show('help_container');
new Ajax.Updater('help_content', url, {asynchronous:true, evalScripts:true,
                            onComplete:function(request){Element.hide('loading_help');Element.show('help_content')},
                            onLoading:function(request){Element.show('loading_help');Element.hide('help_content')},
                            parameters:'topic='+topic});
cursor = getPosition(e);
$('help_container').style['top']=cursor.y;
$('help_container').style['left']=cursor.x+10;
}

//helper function to hide context help window
function hide_context_help()
{
  $('help_container').style['display']='none';
}

//returns mouse position based on the trigered event
function getPosition(e) {
    e = e || window.event;
    var cursor = {x:0, y:0};
    if (e.pageX || e.pageY) {
        cursor.x = e.pageX;
        cursor.y = e.pageY;
    } 
    else {
        var de = document.documentElement;
        var b = document.body;
        cursor.x = e.clientX + 
            (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
        cursor.y = e.clientY + 
            (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
    }
    return cursor;
}

//adds client to the company 
function addClient(url)
{
  set_max_size('fade');
  div_toggle([],['fade','client_box'],true);
  new Ajax.Updater('client_div', url, {asynchronous:true, evalScripts:true, 
  onComplete:function(request){Element.hide('loading_indicator');Element.show('client_details')}, 
  onLoading:function(request){Element.show('loading_indicator');Element.hide('client_details')},
  parameters:'new=yes'});
  return false;
}
//refreshes client drop-down list on the project page
function refresh_clients(id,name)
{
  div_toggle(['fade','client_box'],[],false);
  var option = document.createElement("OPTION");
  option.text = name;
  option.value = id;
  option.selected = true;
  try
  {
    $('project_client_id').add(option, null);
  }
  catch(ex)
  {
    // For IE.
    $('project_client_id').add(option);
  }
}



//edits task item notes
function edit_task_note(task_id,day)
{
  note_task = task_id;
  note_day = day;
  set_max_size('fade');
  div_toggle([],['fade','task_note_box'],true);
  $('task_name').innerHTML = '"'+$('t_'+task_id).innerHTML+'" task note for '+$('wdd_'+day).innerHTML;
  $('task_note').value = $('note_'+task_id+'_'+day).value;
}

//shows task item notes
function show_task_note(task_id,day)
{
  note_task = task_id;
  note_day = day;
  set_max_size('fade');
  div_toggle([],['fade','task_note_box'],true);
  $('task_name').innerHTML = '"'+$('t_'+task_id).innerHTML+'" task note for '+$('wdd_'+day).innerHTML;
  $('task_note').innerHTML = $('note_'+task_id+'_'+day).value;
}

//hides note box and updates task note value
function save_task_note()
{
  $('n_'+note_task+'_'+note_day).src = ($('task_note').value == '')? '../images/make_note.png' : '../images/note.png';
  div_toggle(['fade','task_note_box'],false);
  $('note_'+note_task+'_'+note_day).value = $('task_note').value;
  timesheet_changed = true;
}
function hide_task_note()
{
  div_toggle(['fade','task_note_box'],false);
}