

function applyRules(context){

  var last = null;
  var ff = function(){
    if(last) last.removeClass("focus");
    last = $(this).parents('li');
    last.addClass("focus");
  }

  $('.form li .text',context).focus(ff);
  $('.form li textarea',context).focus(ff);


}

$(document).ready(function(){
    applyRules(document.body);

    
    $('form').submit(function(){
        $(this).addClass('submitting-form');
        $('.button', this).val('Submitting...');
    });

    
});


$.fn.show_in_lightbox = function(sel){
  $(document.body).scrollTop(0);
  var light = $(".lightbox");
  if(light.length==0){
    $(document.body).append('<div class="lightbox-under"></div><div class="lightbox"></div>');  
    light = $(".lightbox");
    $(".lightbox-under").height($(document).height()).mousedown(function(){
      $(this).close_lightbox();
    });

  }
  $(".lightbox-under").show();
//  document.body.style.overflow='hidden';
  light.hide();
  var c = $(sel).html();
  light.html(c);
  light.show('slow');
  applyRules(light);
  light.data('state','on');
  return light;
}

$.fn.close_lightbox = function(){

  
  var light = $(".lightbox");
  if(light.length>=0){
    if(light.data('state')=='on'){
      if(!confirm('Are you sure you want to close this form? Doing so will lose all changes you made!')) return;
//      document.body.style.overflow='';

      $(".lightbox-under").hide();
      light.hide();
      light.data('state','off');
    }
  }

}

$.fn.add_row = function (start,pre){
  var rownr = this.data('rownr');
  if(start>=rownr || typeof rownr =="undefined") rownr=start;

  var kv = this.parents('.keyvalues');
  var ne = kv.find('.new-entry');
  ne.before('<div><input name="'+pre+'_key['+rownr+']" value="" class="text" /><input name="'+pre+'_val['+rownr+']" value="" class="text" /></div>');
  var f = ne.parents("form")[0];
  f.elements[pre+'_key['+rownr+']'].value  = f.elements[pre+'_key[]'].value;
  f.elements[pre+'_val['+rownr+']'].value  = f.elements[pre+'_val[]'].value;
  f.elements[pre+'_key[]'].value  = '';
  f.elements[pre+'_val[]'].value  = '';



  rownr++;
  this.data('rownr',rownr);
}

