// This is a single javascript method for handling all the actions in our app
// Put here for ease of handling
// This uses methods for prototype, control, windowHandler, extended_request
actionHandler = {
  effectDuration: .5,
  forward: {},      // Hash that is referenced by the day
  id: Math.random(),
  setForward: function(day,on) {
    this.forward[day] = on
  },
  
  // Narrow the type choices for the given day for bm
  narrowChoices: function(day) {
    $('j-firstsel-' + day).selected = true;
    Effect.SlideUp('j-ncLink-' + day, {duration: this.effectDuration});
    Effect.SlideDown('j-ncSelector-' + day, {duration: this.effectDuration});
  },
  
  // Narrow choices for given day for plan
  planNarrowChoices: function(day) {
    Element.hide('j_ingredientsSearch');
    $('j-firstsel-' + day).selected = true;
    Effect.SlideUp('j-ncLink-' + day, {duration: this.effectDuration});
    Effect.SlideDown('j-ncSelector-' + day, {duration: this.effectDuration});
  },
  
  getTypeSelectorValue: function(day) {
    var sel = $('j-ncs-' + day);
    return sel.options[sel.selectedIndex].value;    
  },
  
  getScopeSelectorValue: function() {
    var sel = $('j_scope_sel');
    return sel.options[sel.selectedIndex].value;        
  },
  
  newSelection: function(day) {
    var v = this.getTypeSelectorValue(day)
    if (v == "All") { 
      this.all(day);
      return true;
    } 
    $('j-sa-' + day).value = "Next " + v;
    $('j-firstsel-' + day).value = "All";
    $('j-firstsel-' + day).innerHTML = "All";
    this.suggest(day, true)
  },
  
  planNewSelection: function(day) {
    var v = this.getTypeSelectorValue(day)
    if (v == "all") { 
      this.resetPlanSelector(day);
      // return true;
    } else {
      $('j-firstsel-' + day).innerHTML = "All";
    }
    this.planGetRecipeForNewSelection(day);
  },
  
  resetPlanSelector: function(day,duration) {
    duration = duration || this.effectDuration;
    if (document.getElementById('j-firstsel-' + day)){
      $('j-firstsel-' + day).innerHTML = "Pick one";
      Effect.SlideUp('j-ncSelector-' + day, {duration: duration});
      $('j-ncs-'+day).value = "all"
      Effect.SlideDown('j-ncLink-' + day, {duration: duration});
    }
  },
  
  planGetRecipeForNewSelection: function(day){
    var type = this.getTypeSelectorValue(day)
    var scope = this.getScopeSelectorValue(day)
    new Ajax.Request ( '/planning/changed_type',
    {
      parameters: { type: type, scope: scope },
      method: 'get',
      evalScripts: true
    });
    return false;
  },
  
  planShowSearch: function() {
    this.resetPlanSelector(0,0.01);
    $('j_scope_sel').value = 'not_disliked'
    Element.hide('j_scope_sel')
    Element.show('j_ingredientsSearch');
    $('entry').focus(); 
    new Ajax.Request ( '/planning/show_search',
    {
      method: 'get',
      evalScripts: true
    });
    return false;
  },
  
  planCancelSearch: function() {
    new Effect.Fade('j_ingredientsSearch', {duration: 0.2}); 
    new Ajax.Request ( '/planning/cancel_search',
    {
      method: 'get',
      evalScripts: true
    });
    return(false);
  },

  planResetActionList: function() {
	  Element.hide('j_scope')
  },
  
  all: function(day) {
    $('j-firstsel-' + day).value = "Pick one";
    $('j-firstsel-' + day).innerHTML = "Pick one";
    Effect.SlideDown('j-ncLink-' + day, {duration: this.effectDuration});
    Effect.SlideUp('j-ncSelector-' + day, {duration: this.effectDuration});
    $('j-sa-' + day).value = "Suggest Another";
  },
  
  recipeById: function(day){
    var rid = $('j_direct_rid_' + day).value
    new Ajax.Request ( '/bm/recipe_by_id',
    {
      parameters: { day: day, direct_rid: rid },
      method: 'get',
      evalScripts: true
    });
  }, 
  
  suggest: function(day, changed_type){
    var v = this.getTypeSelectorValue(day)
    var type;
    if ( v == "Pick one" || v == "" ) {
      type = "All"
    } else {
      type = v
    }
    this.get_next_menu (day, type, changed_type);
    return false;
  },
  
  get_next_menu: function (day, type, changed_type) {
    var action;
    if (this.forward[day] && !changed_type) {
      action = "next"
    } else {
      action = "suggest"      
    }
    new Ajax.Request ( '/bm/' + action,
    {
      parameters: { day: day, type: type, changed_type: changed_type },
      method: 'get',
      evalScripts: true
    });
  },
  
  prev: function (day) {
    new Ajax.Request ( '/bm/prev?day=' + day,
    {
      method: 'get',
      evalScripts: true
    });
  },

  pick_from_list: function (day) {
    new Effect.Fade('j_prev_' + day, {duration: .5})
    new ExtendedRequest('/bm/show_yum_list?day='+day+'&pickable=true', { overlay:true } ) ;
  },
  
  planPickFromList: function (day) {
    overlayHandler.displayUrl('/bm/show_yum_list?day='+day+'&pickable=for_planning' ) ;
  },

  my_own: function (day) {
    new ExtendedRequest('/bm/my_own?day='+day, { overlay:true } ) ;
  },
  
  showYumList: function (){
    overlayHandler.displayUrl('/bm/show_yum_list' ) ;
  },
  
  remove_from_yum: function (recipe_id) {
    new Effect.Fade("j_rline_" + recipe_id) ;
    new Ajax.Request ( '/bm/remove_from_yum?r=' + recipe_id,
    {
      method: 'get'
    });
  },
  
  planCount: function() {
    var ch_boxes = $('j_recipe_summary').getElementsByClassName('j_try_it')
    var count = 0
    for (i=0; i<ch_boxes.length; i++){
      if (ch_boxes[i].checked) {
        count++;
      }
    }
    return count;
  },
  
  showPlanRecipesOnly: function(set) {
    var recipes = $('j_recipe_summary').getElementsByClassName('recipe_line')
    for ( i = 0 ; i < recipes.length ; i++ ) {
      if ( set ) {
        if ( recipes[i].getElementsByClassName('j_try_it')[0].checked ) 
          Element.show(recipes[i])
        else
          Element.hide(recipes[i])        
      } else {
        Element.show(recipes[i])
      }
    }
  },
  
  pick_from_yum: function (recipe_id, day){
    overlayHandler.closeOverlay();
    new Ajax.Request ( '/bm/choose/?rid=' + recipe_id + '&day=' + day ,
    {
      method: 'get'
    });
  },
  
  chooseRecipe: function (recipe_id){
    overlayHandler.closeOverlay();
    new Ajax.Request ( '/planning/choose/' + recipe_id,
    {
      method: 'get'
    });
  },

  lastEvent: null,
  
  // Present the recipe rating menu at the location indicated
  rate_recipe: function(recipe_id,event) {
    var point = windowHandler.clickPoint(event);
    new Ajax.Request('/rating/actual/'+recipe_id,
    { method: 'get',
      evalScripts: true,
      onSuccess: function(transport) { 
        $('overlayMenu').innerHTML = transport.responseText;
        windowHandler.positionRelativeToPoint('overlayMenu',point,{removeOnClick: true, placement: {xpos: 'center', ypos: 'top'}, offset: {xpos: 0, ypos: -10}});
       }.bind(this)
     }
    )
  },
   
  rated: function(recipe_id,rating) {
    new Ajax.Request('/rating/actual/'+recipe_id,
    { method: 'post',
      parameters: { rating: rating},
      evalScripts: true,
      onSuccess: function(transport) { 
        // $('j_rpr'+recipe_id).innerHTML = transport.responseText;
       }.bind(this)
     }
    )
  },
  
  note: function(recipe_id,event) {
    var point = windowHandler.clickPoint(event);
    new Ajax.Request('/rating/note/'+recipe_id,
    { method: 'get',
      evalScripts: true,
      onSuccess: function(transport) { 
        $('overlayMenu').innerHTML = transport.responseText;
        windowHandler.positionRelativeToPoint('overlayMenu',point,{removeOnClick: false, placement: {xpos: 'center', ypos: 'top'}, offset: {xpos: 0, ypos: -10}});
       }.bind(this)
     }
    );
  },
  
  // Currently unused - using rjs instead
  noted: function(recipe_id,note) {
    new Ajax.Request('/rating/note/'+recipe_id,
    { method: 'post',
      parameters: { note: note},
      evalScripts: true,
      onSuccess: function(transport) { 
        $('j_rpn'+recipe_id).innerHTML = transport.responseText;
       }.bind(this)
    }
    );
    Element.hide('overlayMenu');
  },
  
  comment: function(recipe_id,event) {
    var point = windowHandler.clickPoint(event);
    new Ajax.Request('/recipe/comment/'+recipe_id,
    { method: 'get',
      evalScripts: true,
      onSuccess: function(transport) { 
        $('overlayMenu').innerHTML = transport.responseText;
        windowHandler.positionRelativeToPoint('overlayMenu',point,{removeOnClick: false, placement: {xpos: 'center', ypos: 'top'}, offset: {xpos: 0, ypos: -10}});
       }.bind(this)
     }
    );
  },
  
  refreshShortList: function() {
    new Ajax.Request ( '/planning/refresh_short_list/',
    {
      method: 'post'
    });    
  },
  
  removeVegeSide: function(recipe_id) {
    new Ajax.Request ( '/planning/remove_vege_side/' + recipe_id,
    {
      method: 'post'
    });    
  },
  
  removeStarchSide: function(recipe_id) {
    new Ajax.Request ( '/planning/remove_starch_side/' + recipe_id,
    {
      method: 'post'
    });  
  },
  
  addSide: function(main_recipe_id, side_recipe_id) {
    overlayHandler.closeOverlay();
    new Ajax.Request ( '/planning/add_side/?main_recipe_id=' + main_recipe_id + '&side_recipe_id=' + side_recipe_id,
    {
      method: 'post'
    });    
  },
  
  
  stickToDiet: function(checked, context){
    new Ajax.Request('/planning/personalize?set=' + checked, {asynchronous: false});
    overlayHandler.repaintWithUrl('/planning/show_last_search_as_list?context=' + context);
    new Ajax.Updater($('j_stick_to_diet'), '/planning/stick_to_diet')
  },
    
  removeFromShortList: function(recipe_id) {
    new Effect.Fade("j_rline_" + recipe_id) ;
    new Ajax.Request ( '/planning/remove/' + recipe_id,
    {
      method: 'post'
    });    
  },
  
  call:function(url) {
    new Ajax.Request (url,
    {
      method: 'post',
      evalScripts: true
    });        
  },
  
  erase_and_call:function(recipe_id,url) {
    new Effect.Fade("j_rline_" + recipe_id) ;
    new Ajax.Request (url,
    {
      method: 'post'
    });        
  },
  
  didnt_cook:function(uniq_id) {
    new Effect.Fade("j_rh_line_" + uniq_id) ;
    new Ajax.Request ( '/user/didnt_cook/' + uniq_id,
    {
      method: 'post'
    });    
  },
  
  fullSearch: function(value) {
    new Ajax.Request('/planning/full_search',
    {
      evalScripts: true, method:'get', 
      parameters: {'search[ingredients]': value }, 
      onComplete: function(transport) { overlayHandler.fillAndShowOverlay(transport.responseText)} 
    })
  },
  
  // Toggle the status of an edible for the shopping list
  toggleEdible: function(edible_id) {
    new Ajax.Request('/sl/toggle_has_edible/'+edible_id,
    {
      method: 'get',
      evalScripts: true,
      onSuccess: function(transport) {
        if ( transport.responseText == 'off' ) {
          $('j_edn_'+edible_id).addClassName('off')
          $('j_eda_'+edible_id).innerHTML = "I don't have it"
        } else {
          $('j_edn_'+edible_id).removeClassName('off')
          $('j_eda_'+edible_id).innerHTML = 'I have it'
        }
      }
    }
    )
  },
  
  slToggleEdible: function(edible_id, checked) {
    new Ajax.Request('/sl/toggle_has_edible/'+ edible_id + '?have_it=' + checked,
    {
      method: 'get',
      evalScripts: true,
      onSuccess: function(transport) {
        if ( transport.responseText == 'off' ) {
          $('j_sl_edible_'+edible_id).addClassName('off')
        } else {
          $('j_sl_edible_'+edible_id).removeClassName('off')
        }
      }
    }
    )
  },
  
  // Add the staple represented by the ingredients array back into the shopping list
  outOfStaple: function(edible_id) {
    new Ajax.Request('/sl/out_of_staple/'+edible_id,
    {
      method: 'post',
      evalScripts: true
      // parameters: {'ing[]': ingredients_array}
    }
    )
  },
  
  removeStaple: function(edible_id) {
    new Ajax.Request('/sl/remove_staple/'+edible_id,
    {
      method: 'post',
      evalScripts: true
    }
    )    
  },
  
  // Add the edible as a staple
  addStaple: function(edible_id) {
    new Ajax.Request('/sl/add_staple/'+edible_id,
    {
      method: 'post',
      evalScripts: true
    }
    )    
  },
  
  num_days: function() {
    n = ($('j_num_days').selectedIndex + 1) + ''
    window.location = '/bm/index?n=' + n
  },
  
  rjsRequest: function (URL) {
    new Ajax.Request ( URL,
    {
      method: 'get',
      evalScripts: true
    });
  }  
}