var buttonSize = 49;
var stillHide = 1;
var boxWidth = 500;
var boxHeight = 400;
var boxOpen = 0;

function topFollow() {
	var s2 = document.documentElement.scrollTop || window.pageYOffset || 0;
	sTop2 =  s2 > cY2  ? (s2+20) : cY2;

	clearTimeout(stimeOut2);
	stimeOut2 = setTimeout("$('#globalBox1').animate({top:sTop2+'px'},100);",70);

	clearTimeout(stimeOut3);
	stimeOut3 = setTimeout("$('#globalBox2').animate({top:(sTop2+120)+'px'},100);",70);
}

function putAtGoodPlace()
{
	globalWidth = $(document).width();

	$('.leftBox').css('left', (globalWidth-buttonSize));

	if( stillHide == 1 )
	{
		$('.leftBox').fadeIn(500);

		stillHide = 0;
	}
}

function openBox(id)
{
	if( boxOpen == id )
	{
		closeBox(id);
		boxOpen = 0;
		$('#globalBox'+id).css('z-index', 0);
	}
	else
	{
		if( boxOpen != 0 )
		{
			if( boxOpen == 1 )
			{
				closeBox('1');
				$('#globalBox1').css('z-index', 0);
			}
			else
			{
				closeBox('2');
				$('#globalBox2').css('z-index', 0);
			}
		}

		if( id == 1 )
		{
			url = '/public/searchForm.php';
		}
		else
		{
			url = '/public/recettesConsultees.php';
		}

		$.get(url, function(data) {
		  $('#box'+id).html(data);

		  if( id == 1 ) {
			$(".suggest").autoSuggest("/public/searchFromSuggest.php", {minChars: 1, selectedItemProp: "name", searchObjProps: "name", asHtmlID: "suggestquery", startText: "Rechercher...", emptyText: "Pas de correspondance"});
			$(".suggest3").autoSuggest("/public/searchSuggestRecette.php", {formatList: function(data, elem){ var new_elem = elem.html('<img src="'+data.image+'" /> '+data.name); return new_elem; }, selectionAdded: function(elem) { $('#unerecette').submit(); }, minChars: 1, selectedItemProp: "name", searchObjProps: "name", asHtmlID: "suggestquery2", startText: "Rechercher...", emptyText: "Pas de correspondance"});
		  }
		});

		globalWidth = $(document).width();

		$('#globalBox'+id).animate({
		    left: (globalWidth-boxWidth-buttonSize-2)
		  }, 200, function() {
			$('#globalBox'+id).css('z-index', 100);

			$('#box'+id).fadeIn(50);

			$('#box'+id).animate({
			    width: boxWidth,
			    height: boxHeight
			  }, 50);
		});

		boxOpen = id;
	}
}

function closeBox(id)
{
	globalWidth = $(document).width();

	$('#box'+id).html('');

	$('#box'+id).animate({
	    width: 0,
	    height: 0,
	    opacity: '1'
	  }, 500);

	$('#globalBox'+id).animate({
	    left: (globalWidth-buttonSize)
	  }, 965);

	$('#box'+id).fadeOut(500);
}

$(document).ready(function(){ 
	putAtGoodPlace();

	cY2 = $("#menu-categories").offset().top;

	$('#globalBox1').css('top', cY2);
	$('#globalBox2').css('top', cY2+120);

	$('#button1').bind('click', function() {
	  openBox('1');
	});

	$('#button2').bind('click', function() {
	  openBox('2');
	});

	$(window).resize(function(){
		putAtGoodPlace();
	});

	$(window).scroll(function(){
		topFollow();
	});
});

var cY2, stimeOut2, stimeOut3;

