function update_info_pane(text){
  $('info_pane').update(text).addClassName("strong").show()
}

function track_setHandlers(){
  console.log("track_setHandlers() called");
  $('commitment_end_date_1i').onchange= update_info_pane;
  
}

function prototype_options_test(select_list, filter_string){
  matches=0;
  no_matches=0;
  console.log("prototype_options_test called for " + select_list + " with filter: " + filter_string);

  $A($("itemlist").options).each(function(option,i){
    if(option.text.indexOf(item_filter_string) >=0 ){
      // console.log("filterItems match value="+option.value + ", index=" + i + ", text=" + option.text );
      matches = matches + 1;
    }else{
      // console.log("filterItems didn't match value="+option.value + ", index=" + i + ", text=" + option.text );
      no_matches= no_matches +1;
    }
  });
  console.log("matches = " + matches + ", no_matches = " + no_matches);
}


jQuery.fn.sort = function() {
  console.log("sort called");
  return this.pushStack( [].sort.apply( this, arguments ), []);
  // if problems with above, try:
  // return this.pushStack( jQuery.merge( [].sort.apply( this, arguments ), []), [] );  
  // return this.pushStack( jQuery.makeArray( [].sort.apply( this, arguments )) );
};

function sortSelect(select_id) {
    // note: used appendTo to put back in DOM.
    jQuery(jQuery(select_id).options).sort(function(a,b){
      // return a.value > b.value ? 1 : -1;
      console.log("a.text=" + a.text + " ,b.text=" + b.text);
      return a.text > b.text ? 1 : -1;
    });
}

// use a filter to move select options to and from a hidden list
function process_options(filter_string, select_list, hidden_list){
  var sort_list=false
  filter_string=filter_string.toLowerCase();
  console.log("process_options called for " + select_list + " with filter_string= " + filter_string);
  $j( select_list + " option").each(function(){
    if(this.text.toLowerCase().indexOf(filter_string) < 0 && this.text != "[all]" && this.text != ""){
      // no match
      // console.log("no match for " + this.text);
      $j(this).remove().appendTo(hidden_list);
    }
  });  

  // any to send back?
  $j( hidden_list + " option").each(function(){
    if(this.text.toLowerCase().indexOf(filter_string) >= 0){
      // a match
      // console.log("match for " + this.text);
      $j(this).remove().appendTo(select_list);
      sort_list=true
    }
  });

  if(sort_list){
    console.log("process_items: about to sort list")

    $j( select_list + " option").sort(function(a,b){
        // console.log("a.text= " + a.text + ", b.text=" + b.text);
        if(a.text=="[all]"){
          return -1;
        }
        return a.text.toLowerCase() > b.text.toLowerCase() ? 1 : -1;
    }).appendTo(select_list);

  }
}

// call for initial sorting
function sort_select_list(select_list){
  console.log("sort_select_list")

  $j( select_list + " option").sort(function(a,b){
      // console.log("a.text= " + a.text + ", b.text=" + b.text);
      if(a.text=="[all]"){
        return -1;
      }
      return a.text.toLowerCase() > b.text.toLowerCase() ? 1 : -1;
  }).appendTo(select_list);
  $j(select_list).show(); // hide on intial show to avoid resort view
}
//jQuery.fn.sort_all=sort_select_list(this);


var select_filters=[];
select_filters["itemlist"]="";
select_filters["foodlist"]="";
select_filters["typelist"]="";

var TrackBench = {
  
  filterOptions: function(select_list, element, value)
  {
    var filter_string=value;
    var jselect_list="#" + select_list; // default for jQuery vs. Prototype
    var jhidden_list="#hidden_" + select_list; // default for jQuery vs. Prototype

    // check if different from prior
    if(select_filters[select_list]==filter_string){
      console.log( "filterOptions: no change to filter_string for " + select_list);
      return;
    }

    // todo: time check- has user stopped typing?
    select_filters[select_list]=filter_string;
    console.log("filterOptions (" + select_list + ") has new filter, value=" + value);

    // prototype_options_test(select_list, select_filters[select_list]);
    process_options(select_filters[select_list], jselect_list, jhidden_list);
  },

  displayMessage: function(){
      alert("displayMessage called");
  }

}

function changeLocation(date) {
		year = date.getFullYear();
		month = date.getMonth() + 1;
		day = date.getDate();
		if (month < 10) {
			month = "0" + month;
		}
		if (day < 10) {
			day = "0" + day;
		}
		location.href = '/track/' + year + '/' + month + '/' + day;
}



var UnitTable = {
    last_row: function(table_id){
      var rows = $(table_id).rows;
      var lastRow = rows[rows.length -1];
    },

    add_row: function(table_id){
        var rows=$(table_id).rows;
    },
    
    // this is from the net
    add_link_to_table: function(table, link){
        var r = table.insertRow(table.rows.length);
        var c = r.insertCell(0);
        $(c).insert(link);
    }
}

function roundify(selector){
    jQuery(selector).corner();
}

function element_exists(css_selector){
  return $j(css_selector).length() > 0;
}

var show_count=0;
//function set_level_on_click(level){
//  show_count=level;
  // expand/fold will work on structure manually created by clicking
  // todo: implement
//}
var prior_show_level=0;
var repeat_count=0;
function set_history_level(show_level, direction){
  console.log("set_history_level show_level=" + show_level + ", direction=" + direction + ", repeat_count=" + repeat_count );
  if(show_level == 0){
    $j(".history_week_body").hide();    
    $j(".history_day_body").hide();      
  }
  if(show_level == 1){
    if(direction ==1){
      $j(".history_week_body").show();
    }else{
      $j(".history_day_body").hide();      
    }
  }
  if(show_level ==2){
    if(direction==1){
      $j(".history_day_body").show();
    }else{
      $j(".history_meal_body").hide();
    }
  }
  if(show_level ==3){
    repeat_count++;
    $j(".history_meal_body").show();
    if(show_level == prior_show_level){
      // if keep hitting expand expand other areas that aren't
      // expand logic stays in a tree until fully expanded
      if(repeat_count==1){
        $j(".history_week_body").show();
      }
      if(repeat_count == 2){
        $j(".history_week_body").show();
        $j(".history_day_body").show();
      }
      if(repeat_count == 3){
        $j(".history_meal_body").show();
      }
    }
  }else{
    repeat_count=0
  }
  prior_show_level=show_level;
}

// if a use manually expands to a level, make Expand work from that level
function capture_history_level(element){
  console.log("capture_history_level")
  if(element.hasClass(".history_week_body")){
    show_count=1
  }

  if(element.hasClass(".history_day_body")){
    show_count=2
  }

  if(element.hasClass(".history_meal_body")){
    show_count=3    
  }
  console.log("capture_history_level show_count=" + show_count);
}

function collapse_history(){
  if(show_count >0){
    show_count--;
  }
  // $j('.load_hidden').hide();
  set_history_level(show_count, 0);
}
// week=level 1, day=2, meal=3
function expand_history(){
  if(show_count < 3){
    show_count++;
  }
  set_history_level(show_count, 1);
  // $j('.load_hidden').show();
}

function toggle_history_div(element_selector){
  element=$j(element_selector);
  element.toggle();
  prior_show_count=show_count;

  if(element.hasClass(".history_week_body")){
    show_count=1;
  }

  if(element.hasClass(".history_day_body")){
    show_count=2;
  }

  if(element.hasClass(".history_meal_body")){
    show_count=3;
  }

  if(!element.is(":visible")){
    // alternative:
    // element.css('display')=='none'

    // just closed this level
    show_count--;  
  }
  if(prior_show_count-show_count > 1){
    // there was another branch expanded out further- use that as level
    show_count = prior_show_count;
  }

}

function expand_commitment(){
  $j('#commitment_pane .dashboard_body').show();
}

function collapse_commitment(){
  $j('#commitment_pane .dashboard_body').hide();
}

function toggle_div(element_selector){
  $j(element_selector).toggle();
}

function show_parent_all(child_element_selector){
  show_parent(child_element_selector, ".history_week_body");
  // all collapsable div bodys are .roundify?
}

function show_parent(child_element_selector, parent_element_selector){
  console.log("show_parent called for " + child_element_selector + " and " + parent_element_selector);
  var child_element=$j(child_element_selector);
  element=child_element.show().parents(parent_element_selector).show();
  capture_history_level(child_element);
}

// not used...
function show_child(parent_element_selector, child_element_selector ){
  console.log("show_child called for " + parent_element_selector + " and " + child_element_selector);
  element=$j(parent_element_selector + " " + parent_element_selector).show();
  capture_history_level(element);
}

function show_element(css_selector){
  element=$j(css_selector).show();
  capture_history_level(element);
}

function calculate_calories(){
    console.log("calculate_calories() called");
    quantity=$F("portion_quantity");
    unit=$F("portion_unit_id");
    calories_per_unit=unit_calories[unit];
    console.log("calculate_calores()- calories_per_unit=" + calories_per_unit)
    // how to get calories?
    calories=quantity * calories_per_unit;
    $j("#portion_calc").html(calories.toFixed(2) + " calories");
}

function update_weekly_calories(day_id, weekly_calories, calorie_metrics){
  $j(".week_calories", $j(day_id).parents(".week")).text(weekly_calories);
  $j(".week_calories + .summary_metrics", $j(day_id).parents(".week")).html(calorie_metrics);  
}

function toggle_toolbars(){
  console.log("toggle-toolbars called");
  $j("#pane_controller").toggle();
  $j("#commitment").toggle();
  // $j("#top_nav").toggle();
}

function jquery_set_calorie_handler(){
    console.log("jquery_set_calorie_handler() called");
    console.log("set_hander...unit_calories length=" + unit_calories.length);

    jQuery("#portion_quantity").keyup( function(){
        calculate_calories();
        });

    jQuery("#portion_unit_id").change( function(){
        calculate_calories();
        });

}

function jquery_set_handlers(){
    console.log("jquery_set_handlers() called");

    //jquery_set_calorie_handler();

    $j('.inp').keydown(function(event){
      switch (event.keyCode) {
        // ...
        // different keys do different things
        // Different browsers provide different codes
        // see here for details: http://unixpapa.com/js/key.html
        // ...
      }
    });
}

function add_units_table_row(){
    console.log("add_units_table_row called")
    
    //$j('#units_edittable tr:last').after('<tr><td></td><td></td></tr>');
    //$j('#units_edittable tr:last').after('<tr><td></td><td></td></tr>');
    //$j('#units_edittable tbody>tr:last').clone(true).insertAfter('#units_edittable tbody>tr:last');    
    rows=$j('#units_edittable tbody tr').length
    console.log("add_units_table_row() rows=" + rows )
    $j("#units_edittable > tbody").append('\
      <tr>\
          <td><input id="item_units_attributes_' + rows + '_name" type="text" value="" size="20" name="item[units_attributes]['+ rows +'][name]"/></td>\
          <td><input id="item_units_attributes_'+ rows +'_calories" type="text" size="8" name="item[units_attributes]['+ rows +'][calories]"/></td>\
          <td><input id="item_units_attributes_'+ rows +'_notes" type="text" size="30" name="item[units_attributes]['+ rows +'][notes]"/></td>\
          <td><a href="#" onclick="return delete_units_table_row(this)">Delete</a></td>\
      </tr>');
}

// remove a row added via js
function delete_units_table_row(cell){
  row=cell.parentNode.parentNode; // a td tr
  var row_index=row.rowIndex; 
  console.log("delete_units_table_row called for " + row_index);
  // $j("#units_edittable").deleteRow(row_index);
  document.getElementById('units_edittable').deleteRow(row_index);
  return false;
}

function remove_row_by_id(row_css_id){
  jrow_css_id = '#' + row_css_id;
  row=$j(jrow_css_id)[0];
  console.log("row=" + row );
  var row_index=row.rowIndex;
  console.log("remove_row_by_id called for: " + jrow_css_id + " row_index=" + row_index)
  document.getElementById('units_edittable').deleteRow(row_index);
}

function set_info_pane_background(){
    jQuery("#info_pane").css("background-color","");
}

function jquery_highlight(element_id){
  jQuery(element_id).effect("highlight", {}, 1000);
}

function clear_tracker_input_fields(){
  $j(".track_column input").val("");
  $j(".datalist").val(null)
}

function reset_search(){
  //alert("heya");
  //clear_tracker_input_fields();
  $j(".track_column input").val("");
  $j("#typelist").val("all");
  handle_type_change("all");
  $j("#typelist").val("all");
  //$j("#item_name").val(null);
  //$j("#food_name").val(null);
  //$j("#type_name").val(null);
}