jQuery(function($) {
  
  $.fn.sortableTable = function(opts) {
    opts = $.extend({}, {
      handle: null,
      reorder: function(table) { },
      rowsToMove: function(grabbedTR) { return $(grabbedTR); },
      canInsertAfter: function(tr, table) { return true; },
      canInsertBefore: function(tr, table) { return true; }
    }, opts);
    
    return this.each(function() {
      var table = $(this);
      $("tbody tr", table).each(function() {
        var selectedTR = $(this);
        var rowsToMove = opts['rowsToMove'](selectedTR);
        (opts['handle'] == null ? selectedTR : $(opts['handle'], selectedTR)).mousedown(function() {
          var selectedIndex = $("tbody tr", table).index(selectedTR);

          $("tbody tr", table).not(rowsToMove).fadeTo("fast", 0.5);
          $("tbody tr", table).not(rowsToMove).mouseenter(function() {
            var enteredTR = $(this);
            var enteredIndex = $("tbody tr", table).index(enteredTR);
            
            if (selectedIndex < enteredIndex && opts['canInsertAfter'](enteredTR, table)) {
              enteredTR.after(rowsToMove);
              opts['reorder'](table);
            } else if (selectedIndex > enteredIndex && opts['canInsertBefore'](enteredTR, table)) {
              enteredTR.before(rowsToMove);
              opts['reorder'](table);
            }
            selectedIndex = enteredIndex;
          });
          $("body").mouseup(function() { 
            $("tbody tr", table).not(selectedTR).fadeTo("fast", 1);
            $("tbody tr", table).unbind("mouseenter");
            $(this).unbind("mouseup");
          });
          return false;
        });
      });
    });
  }
  
  var superSetRows = function(tr, table) {
    var selectors = "." + $.each(tr.attr("class").split(/\s+/), function(className) { return className }).join(".");
    return $(selectors, table)
  }
  
  $(".workout_result table").sortableTable({
    handle: ".grippy",
    reorder: function(table) {
      var count = 0;
      $("tbody tr input.position", table).each(function() {
        $(this).attr("value", count); // this requires only 1 position input per row (and 1 per superset)
        count++;
      });
    },
    canInsertAfter: function(tr, table) {
      if(tr.hasClass("superset")) {
        var matchingRows = superSetRows(tr, table);
        return (matchingRows.length-1) == matchingRows.index(tr);
      }
      return true;
    },
    canInsertBefore: function(tr, table) {
      if(tr.hasClass("superset")) {
        return superSetRows(tr, table).index(tr) == 0;
      }
      return true;
    },
    rowsToMove: function(grabbedTR, table) {
      if($(grabbedTR).hasClass("superset")) {
        return superSetRows(grabbedTR, table);
      }
      return $(grabbedTR)
    },
  });
  
  $.fn.forwardFill = function() {
    var selector = this.selector;
    return this.each(function() {
      var input = $(this);
      var row = $(this).parent().parent();
      input.change(function() {
        var index = $(selector, row).index(input);
        $(selector + ":gt("+index+")", row).val(input.val())
      });      
    })
  };
  $("input.weight").forwardFill();
  $("input.quantity").forwardFill();
  
  $.fn.placeholder = function() {
    return this.each(function() {
      var self = $(this);
      var placeHolderText = self.val();
      self.focus(function() {
        self.removeClass('placeholder');
        if(self.val() == placeHolderText) {
          self.val("");
        }
      }); 
      self.blur(function() {
        if(self.val() == "") {
          self.val(placeHolderText);
        }
        if(self.val() == placeHolderText) {
          self.addClass('placeholder');
        }        
      });
    });
  }
  $('.placeholder').placeholder();
  
  $.fn.deleteRow = function() {
    return this.each(function() {
      var link = $(this);
      link.click(function(el) { link.parent().parent().remove() });
      
    });
  };
  
  $.fn.activityBuilder = function() {
    return this.each(function() {
      var table = $(this);
      var exerciseList = $("tr.exercise_builder", table).clone();
      $("td.sets", exerciseList).text("alternating with sets of");
      $('.add_superset', table).click(function() {
        var superSetRow = exerciseList.clone().insertBefore($(this).parent().parent());
        $(".delete", superSetRow).deleteRow()
      })
    });
  };
  $('.activity_builder').activityBuilder();
  
  $.fn.clickEdit = function() {
    return this.each(function() {
      var formElement = $(this);
      formElement.addClass("click-editable");
      var wrapper = $(document.createElement("span")).addClass("click-edit");
      formElement.wrap(wrapper);
      formElement.hide();
      
      var valueWrapper = $(document.createElement("a")).addClass("click-edit-value").text(formElement.attr("value"));
      valueWrapper.insertAfter(formElement);
      valueWrapper.click(function() {
        valueWrapper.hide();
        formElement.show();
      })
      formElement.blur(function() {
        valueWrapper.text(formElement.attr("value"));
        formElement.hide();
        valueWrapper.show();
      });
    })
  };
});