$(document).ready(function() {
	//hide the form and the tree view
	$('#treeview').hide();
	

	// hide the search form if we're already editing a product. active-product is added to the body with php if that's the case.
	$('.active-product #add-product-find').hide();
	


	// set up the tree
/*
	if($('#categories-tree').length){
		$('#categories-tree').each(function(){
			buildTree($(this));
		});
	}*/

	
	//let's show the taxonmy tree
	$('.browse-taxonomy').bind("click", function(e){ 
		showTree(e); 
		return false; 
		}
	);

	$('#add-product-find').bind("submit", addProductFind);
	
	//$('#add-product-cancel').bind("click", addProductCancel)
	


	
}); //ready



function showTree(event, header){
	
	if($('#treeview').is(':visible')){
		return true;
	}
	
	//url changes depending on buy/sell.
	var theUrl = $('.browse-taxonomy').attr("href");
	
	$('#treeview').show();
	
	$("#categories-tree").html(FH.loader);

	jQuery("#categories-tree").load(theUrl, function()
		{
			if(!header){	
				$(this).prepend('<h2>Browse For Products</h2>');
			} else{
				$(this).prepend('<h2>'+header+'</h2>');
			}
			buildTree($(this));
		}
	);
	return false;
}
function buildTree(el) {
	var $el = $(el);
	
	$el.treeview({
		collapsed: true,
		animated: "fast",
		control:"#sidetreecontrol",
		persist: "location",
		unique: true
	});
}



function addProductFind () {
	var $product = $('input#product-name').val();
	var $productInput = $('input#product-name');
	var $hidden = $('#product-id-searched');
	
	// if they've entered in something that's not in the list, let's show thme the tree, shall we? 
	// treated differently then a blank or default input. (below)
	if ($hidden.val() == "" && $product != "" && $product != "enter a product name") {
		var title = "We couldn't find that product. <br /> Browse our taxonomy to find the product you'd like to add.";
		showTree( null, title);
		return false;
	}
	
	
	//if the submit button is clicked and there are no products, show the browse tree
	else if ($product == "" || $product == "enter a product name" || $hidden.val() == ""){
		showTree();
		return false;
	}
	else{
		return true;
	}
}

