$(document).ready( function() 
{
  $("form.ajaxUpdate").livequery ( function() 
  {
    var form=$(this)
    $(this).ajaxForm( function(data) 
    {
      $(".status",form).html("").css("opacity",1.0).show();;
      if (data=="OK")
      {        
        $(".status",form).html("העדכון בוצע בהצלחה!").fadeOut(2000,function() {$(this).html("")});
      }
      else
      {
        $(".status",form).html("העדכון נכשל!").fadeOut(2000,function() {$(this).html("")});
      }
    });
  });

  $("form.ajaxAdd").each ( function() 
  {
    var form=$(this);
    $(this).ajaxForm( function(data) 
    {
      $(".status",form).html("").css("opacity",1.0).show();;
      if (data=="OK")
      {
        $(".status",form).html("העדכון בוצע בהצלחה!").fadeOut(2000,function() {$(this).html("")});
	$(".keywordSearch input[type='button']").click();
	form.resetForm();
      }
      else
      {
        $(".status",form).html("העדכון נכשל!").fadeOut(2000,function() {$(this).html("")});
      }
    });
  });


  $(".keywordSearch").each ( function()
  {
    var search=$(this);
    var target=$(this).attr("target");
    var updateTimeout=null;
    var keyword=$("input[type='text']",search)
    var button=$("input[type='button']",search)
    var results=$(".searchResults",search)
    var updateSearchResults = function()
    {
      updateTimeout=null;
      $("*").css("cursor","progress");
      results.load(target,{'keyword' : keyword.val()}, function() { $("*").css("cursor",""); });
    }
    
    keyword.bind("keyup", function(e) {
      if (updateTimeout!=null)
        clearTimeout(updateTimeout);
      updateTimeout=setTimeout(updateSearchResults,300);
    });
    button.bind("click", function() {
      keyword.keyup();
    });
    updateSearchResults();
  });
  
  
  $("input.autocomplete").livequery ( function()
  {
    var val=$(this).val();
    var mustMatch = !$(this).hasClass("freeMatch")
    $(this).attr("title","לחץ כדי לבחור ערך");
    $(this).autocomplete($(this).attr("target"),{ 'minChars' : 0,'mustMatch' : mustMatch });
    $(this).val(val);
  });
  
  $("input.autocomplete_next").livequery ( function()
  {
    var val=$(this).val();
    var target=$(this);
    var mustMatch = !$(this).hasClass("freeMatch")
    var input = $(this).next("input");
    input.autocomplete($(this).attr("target"),
    { 
      'minChars' : 0,
      'mustMatch' : mustMatch,
      formatResult : function(row) {
        return row[0];
      }
    }    
    );
    input.attr("title","לחץ כדי לבחור ערך");
    input.result(function(e,row) {
      target.val(row[1]);
    });
  });
  
  $(".load").livequery ( "click",function()
  {
    var target=$(this).attr("target");
    var href=$(this).attr("href");    
    $(target).load(href);
  });
  
});
