$(index_init);
var ingrednum;
var curcat = 0;
var currec;

function index_init() {
  init_navigation();
  init_dragdrop();
  
  $.ajaxSetup({
    success: function(){$("#ajaxload").hide();},
    complete: function(){$("#ajaxload").hide();},
    beforeSend: function(){$("#ajaxload").show();}        
  });
  
  $(".tabs").corner("top").click(e_tab_select);
  $("#but_register").click(function(){
  	if ($("#reg_mail").val() == '') {
  		$("#info").html('<center>Complete all neccessary fields</center>').slideDown("slow",close_ajax_reply);
			return;
  	}
    $("#ajaxload").show();
    var data = {};
    $("#register_dialog :input").each(function(){
      data[$(this).attr('name')]=$(this).val();
    });
    $.post('index.php?do=register',data,function(reply){
      $("#register_dialog").slideUp('slow');
      $("#ajaxload").hide();
      $("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
    })
  });
  
  $("#but_login").click(function(){
    $("#ajaxload").show();
    var data = {};
    $("#login_dialog :input").each(function(){
      data[$(this).attr('name')]=$(this).val();
    });
    $.post('index.php?do=login',data,function(reply){
      $("#login_dialog").slideUp('slow');
      $("#ajaxload").hide();
      $("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
      setTimeout('location.reload();',2000);  
    })
  });
  
  $("#but_reset").click(function(){
  	var mail = $("#reset_mail").val();
		$.post('php/login.php?do=remember',{mail:mail},function(reply){
			$("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
		});
  });
  
  $("#but_addcat").click(function(){
    var data = {};
    data['id'] = curcat;
    data['name'] = $("#addcat_dialog input").val();
    $.post('index.php?do=addcat',data,function(reply) {
      $("#addcat_dialog").hide();
      $("#navigation #"+curcat).next("div").prepend(reply).
        children(":first").contextMenu({menu: 'folder_menu'}, menu_folders).
        children(".plus").click(e_expand_cat);
        init_dragdrop();
    });
  });
  
  $("#but_rencat").click(function(){
    var data = {};
    data['id'] = curcat;
    data['name'] = $("#dlg_rencat input").val();
    $.post('index.php?do=rencat',data,function(reply) {
      $("#dlg_rencat").fadeOut("slow");
      $("#navigation #"+curcat).html('<div class="plus">&nbsp;</div>'+data['name']).
      children(".plus").click(e_expand_cat);
    });
  });
   
  $("#but_sendmail").click(function(){
  	var mailaddr = $("#dlg_sendmail input").val();
		$.post('index.php?do=sendmail',{mail: mailaddr, rec: currec}, function(reply){
			alert(reply);
			$("#dlg_sendmail").fadeOut("slow");
		})
  });
  
  $(".rem_tab").click(e_remtab);
	$("#feedback_caption").click(function(){
		if ($("#dlg_feedback").css('left') == "0px")
			$("#dlg_feedback").animate({left: "-203px"},"slow");
		else
			$("#dlg_feedback").animate({left: "0px"},"slow");
	});
	
	$("#search_caption").click(function(){
		if ($("#dlg_search").css('left') == "0px")
			$("#dlg_search").animate({left: "-203px"},"slow");
		else
			$("#dlg_search").animate({left: "0px"},"slow");
	});
		
	
	
	$("#but_feedback").click(function(){
  	if ($("#dlg_feedback textarea").val() == '') {
  		$("#info").html('<center>Complete all neccessary fields</center>').slideDown("slow",close_ajax_reply);
			return;
  	}
		var data = {};
    data['mail'] = $("#feedback_form input").val();
    data['msg'] = $("#feedback_form textarea").val();
    $.post('index.php?do=feedback',data,function(reply) {
			$("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
    });
	});
	
	$("#but_search").click(function() {
		var term = $("#dlg_search input").val();
		$("#search_results").load('index.php?do=search_recipe',{term: term});
	});
}

function init_dragdrop() {
  $(".drag").draggable({
    helper: 'clone',
    opacity: 0.35
  });
  $(".drop").droppable({
    accept: '.drag',
    greedy: true,
    tolerance: 'intersect',
    over: function(event, ui) {
      $(this).addClass('drop_over');
    },
    drop: function(event, ui) {
      $(this).removeClass('drop_over');
      var dropid = ui.draggable.attr("id");
      ui.draggable.appendTo($(this)).css('position');
      var recid = ui.draggable.attr('id');
      var catid = $(this).attr('cat');
      $.post('index.php?do=change_cat',{recid: recid, catid: catid});
    },
    out: function(event, ui) {
      $(this).removeClass('drop_over');
    }
  });  
}

function init_addrecipe() {
  init_addfields();
 
  $("#but_addingr").click(function(){
    $("#ingred_table").append('<tr>\
              <td><input type="text" name="item'+ingrednum+'" class="inpdata" style="width:145px;"></td>\
              <td><input type="text" name="unit'+ingrednum+'" class="inpdata" style="width:30px;"></td>\
              <td><input type="text" name="amount'+ingrednum+'" class="inpdata" style="width:40px;"></td>\
              <td><input type="text" name="notes'+ingrednum+'" class="inpdata" style="width:245px;"></td>\
              </tr>');
    ingrednum++;
    init_addfields();
  });
  
  $("#but_addrecipe").click(function(){
    var data = {};
    $("#main :input").each(function(){
      data[$(this).attr('name')]=$(this).val();
    });
    $.post('index.php?do=add_recipe',data,function(reply){
      $(".cat #"+curcat).next("div").prepend(reply).children(":first").click(e_show_recipe).contextMenu({menu: 'recipe_menu'}, menu_recipes).click();
      init_dragdrop();
    });
  });
}

function init_editrecipe() {
	$("#but_editrecipe").click(function() {
		var data = {};
    $("#main :input").each(function(){
      data[$(this).attr('name')]=$(this).val();
    });
    var id = data['id'];
    $.post('index.php?do=edit_recipe',data,function(reply){
			$(".cat #"+id).click();
		}); 	
	});
}

function init_addfields() {
  $(".inpdata").focus(function(){
    $(this).addClass('inpactive');
  });
  $(".inpdata").blur(function(){
    $(this).removeClass('inpactive');
  });  
}

function init_navigation() {
  $(".cat h2").contextMenu({menu: 'cat_menu'}, menu_folders);
  $(".cat h3, h4").contextMenu({menu: 'folder_menu'}, menu_folders);
  $(".cat h5").contextMenu({menu: 'recipe_menu'}, menu_recipes);
  $("#navigation #0").contextMenu({menu: 'root_menu'}, menu_root);
  $(".cat .plus").click(e_expand_cat);
  $(".cat h5").click(e_show_recipe);
}

function menu_root(action, el, pos) {
    curcat = 0;
    if (action == 'addfolder') {
      var w = ($(window).width()*0.5)-100;
      var h = ($(window).height()*0.5)-50;
      $("#addcat_dialog").css('top',h+'px').css('left',w+'px').fadeIn("slow");
    }
}

function menu_folders(action, el, pos) {
  var id = $(el).attr('id');
  curcat = id;
  if (action == 'delete') {
    if (confirm("Do you want to delete this folder?"))
    $.post('index.php?do=del_cat',{id:id}, function(reply){
      $("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
      $("#"+id).next().remove();
      $("#"+id).remove();
    });
  }
  if (action == 'addfolder') {
    var w = ($(window).width()*0.5)-100;
    var h = ($(window).height()*0.5)-50;
    $("#addcat_dialog").css('top',h+'px').css('left',w+'px').fadeIn("slow");
  }
  if (action == 'addrecipe') {
    if ($(el).parent().hasClass('cat')) {
      alert('Create sub directory for recipes');
      return;
    } 
    $("#main").load('index.php?do=show_addrecipe&cat='+curcat,function(){
      init_addrecipe();
      ingrednum = 3;
    });
  }
  if (action == 'rename') {
    var w = ($(window).width()*0.5)-100;
    var h = ($(window).height()*0.5)-50;
    $("#dlg_rencat").css('top',h+'px').css('left',w+'px').fadeIn("slow");
  }
}

function menu_recipes(action ,el, pos) {
  var id = $(el).attr('id');
  if (action == 'delete') {
    if (confirm("Do you want to delete this recipe?"))
    $.post('index.php?do=del_rec',{id:id},function(reply){
      $("#info").html('<center>'+reply+'</center>').slideDown("slow",close_ajax_reply);
      $("#"+id).remove();
      $(".tab_panel div[recp="+id+"]").fadeOut("slow",function(){
        $(".tab_panel div[recp="+id+"]").remove();
      });
    });
  }
  if (action == 'edit') {
		$("#main").load('index.php?do=show_edit_recipe&id='+id,function(){
			init_editrecipe();
		});
  }
  if (action == 'export') {
    location.href="export.php?id="+id;
  }
}

function login() {
  $("#login_dialog").corner("bottom").slideDown("slow");
}
function register() {
  $("#register_dialog").corner("bottom").slideDown("slow");
}
function logout() {
  $.get('index.php?do=logout',function(){
    location.reload();
  });  
}
function close_ajax_reply() {
  setTimeout('$("#info").slideUp("slow");',2500);
}

function show_sendmail() {
  var w = ($(window).width()*0.5)-100;
  var h = ($(window).height()*0.5)-50;
  $("#dlg_sendmail").css('top',h+'px').css('left',w+'px').fadeIn("slow");
}

function open_recipe(id) {
	$(".cat #"+id).click();
}

function print_rec(id) {
	var href = "index.php?do=print&recipe="+id;
	window.open(href,'print','status=0,toolbar=0,menubar=0,location=0,scrollbar=0,width=300,height=200');
}

function e_show_recipe() {
   var name = $(this).text();
    var id = $(this).attr("id");
    currec = id;
    $("#main").load('index.php?do=show_recipe&id='+id,function(){
      $("#ajaxload").hide();
      if ($(".tab_panel div[recp="+id+"]").size()) {
        $(".tab_panel div").removeClass("tab_active");
        $(".tab_panel div[recp="+id+"]").addClass("tab_active");
      } else {
        $(".tab_panel div").removeClass("tab_active");
        $(".tab_panel").prepend('<div recp="'+id+'" class="tabs tab_active">'+name+'&nbsp;<img src="img/delsmall.png" class="rem_tab"></div>').children(":first").corner("top").click(e_tab_select);
        $(".tab_panel div[recp="+id+"] .rem_tab").click(e_remtab);  
      }
    });
}

function e_tab_select() {
  var id = $(this).attr("recp");
  currec = id;
  $("#main").load('index.php?do=show_recipe&id='+id,function(){
    $(".tab_panel div").removeClass("tab_active");
    $(".tab_panel div[recp="+id+"]").addClass("tab_active");  
  });
}

function e_expand_cat(e) {
  $(this).parent().next("div").toggle();
  $(this).toggleClass("minus");
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();

}

function e_remtab(e) {
  if (!e) var e = window.event;
  e.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
  var tab = $(this).parent();
  var id = tab.attr("recp");
  $.post('index.php?do=rem_tab',{id:id});
  tab.fadeOut("slow",function(){
    tab.remove();
  });
}