// /root/js/ajax_search.js
// Last Updated : 17 January 2007

// Initializes the AJAX engine and contains the entry functions

// Get the ajaxEngine Objext
var ajaxEngine = new Ace.Engine();

// For the search text
var textSearch = " ";

// For breadcrumbs
var arrBCText = new Array();
var arrBCID = new Array();
var ptrA = 0;

var section = "";
var sectionID = 0;
var currentdiaryobject=new Object;
var currentobj;
var currentpid;
var currentwiz;

// For a Text Search
function SearchText(f) {
	
	// Reset breadcrumbs
	bc_reset();
	
	if(section=='recipe')
	{
		if(sectionID==0)
		{
			alert("Please make sure you have selected a recipe first.");
			return false;
		}
	}
	// Validation
	if (f.txt_productsearch.value.length < 3)
	{
		alert("Please enter 3 or more characters to perform a search");
	} 
	else { // If validation passes
	textSearch = "Text Search > " + f.txt_productsearch.value;
		Search("/DataAction?section=search&action=text&text=" + escape(f.txt_productsearch.value)+ (section=='compare'?"&fs=1":""), productList);
	}
	
	return false;
}

// For a Barcode Search
function SearchBarcode(f) {
	
	// Reset breadcrumbs
	bc_reset();
	
	if(section=='recipe')
	{
		if(sectionID==0)
		{
			alert("Please make sure you have selected a recipe first.");
			return false;
		}
	}
	
	
	// Validation
	if (f.txt_barcodesearch.value.length != 4) 
	{
		alert("Please enter 4 digits");
	} 
	else { // If validation passes
		textSearch = "Barcode Search > " + f.txt_barcodesearch.value;
		Search("/DataAction?section=search&action=barcode&barcode=" + f.txt_barcodesearch.value + (section=='compare'?"&fs=1":""), productList);
	}
	
	return false;
}

// For Exercise Search
function SearchExercise(parentid, bc) {
	
	// Reset breadcrumbs
	bc_reset();
	
	bc_push(parentid, bc);
	
	textSearch = "";
	ajax_request("/DataAction?section=exercise&action=children&parentid=" + parentid, ExerciseCallBack, {list: exerciseList} );
}

// For a Servings Search
function SearchServings(productid,wizardid) {


    if(wizardid==undefined) wizardid=0;
    
    currentpid = productid;
    currentwiz = wizardid;
    url = "/DataAction?section=search&action=product&productid=" + productid;
    if(wizardid>0)
    {
        //new Ajax.Request(url,
        //        {
        //    method:'get',
        //    onSuccess: wizedit    
        //        });    
        
        new Ajax.Request("/DataAction?section=wizard&action=get&wid="+ wizardid+"&id=" + productid,
  	{
    method:'get',
    onSuccess: wizinit    
	});
         
        
	
    }
    else
    {

	ajax_request(url, ServingsCallBack, {list: servingList} );
    }
}
function pageinit(url,sclass)
{
	var searchbox = getSearchBox();

	$("pane_search_extend").addClassName(sclass);
	callUpdaterURL2(url,searchbox.id,displaySearch);

	return false; 

}
function wizedit(transport)
{
    jsonObj =  transport.responseText.evalJSON();
}
function wizinit(transport)
{
    jsonObj1 = transport.responseText.evalJSON();
        //this is to fake the edit data
    $("pane_search_extend").addClassName("extendFullWiz");		
    $("pane_search_extend").innerHTML=jsonObj1.html;
    eval(jsonObj1.js);
    
}
// For Bottom Level Exercise Search
function SearchExerciseBL(parentid, bc) {
	
	bc_push(parentid, bc);
	
	textSearch = "";
	ajax_request("/DataAction?section=exercise&action=childlist&parentid=" + parentid, ExerciseCallBack, {list: exerciseList} );
}

// Entry function for a main category
function SearchCategoryMain(parentid, bc) {
	// Reset breadcrumbs
	bc_reset();
	
	textSearch = " ";
	
	if(section=='recipe')
	{
		if(sectionID==0)
		{
			alert("Please make sure you have selected a recipe first.");
			return;
		}
	}
	// Perform Search
	SearchCategory(parentid, bc);
}

function SearchRecipeMain() {
	// Reset breadcrumbs
	bc_reset();
	
	textSearch = " ";
	// Perform Search
	RecipeCategories();	
}

function RecipeCategories(){

	url = "/DataAction?section=search&action=recipe";
	ajax_request(url, RecipeCategoriesCallBack, '' );

}


function SearchFavouritesMain() {
	// Reset breadcrumbs
	bc_reset();
	
	textSearch = " ";
	// Perform Search
	SearchFavourites();
}


function SearchManAddMain() {
	// Reset breadcrumbs
	bc_reset();
	
	textSearch = " ";
	// Perform Search
	//SearchManAdd(parentid, bc);
	 SearchManAdd();
}

function SearchFavourites(parentid, bc){	
	
	url = "/DataAction?section=search&action=favourites";
	ajax_request(url, SearchFavouritesCallBack,'' );
}

function SearchManAdd(){	
	
	url = "/DataAction?section=search&action=manualadd";
	ajax_request(url, SearchManAddCallBack,'' );
}

function SearchRecipeCategories(rcat){	
	
	url = "/DataAction?section=search&action=recipe&occ=" + rcat;
	ajax_request(url, SearchRecipeCategoryCallBack,'' );
}

function SearchRecipeServings(recipeid){
	url = "/DataAction?section=search&action=recipe&id=" + recipeid;
	currentpid=0;
	ajax_request(url, ServingsCallBack, {list: servingList} );
}

function SearchFavouritesServings(favsid){
	url = "/DataAction?section=search&action=favourites&id=" + favsid;
	currentpid=0;
	ajax_request(url, ServingsCallBack, {list: servingList} );
}

function SearchManAddServings(MAid){
	url = "/DataAction?section=search&action=manualadd&id=" + MAid;
	currentpid=0;
	ajax_request(url, ServingsCallBack, {list: servingList} );
}

// For a category Search
function SearchCategory(parentid, bc) {
	// Load the breadcrumb into the arrays
	bc_push(parentid, bc);
	
	textSearch = " ";
	
	// We need to do two AJAX requests for this one.
	url = "/DataAction?section=category&action=children&parentid=" + parentid;
	ajax_request(url, CategoryCallBack, {parentid: parentid} );
}

// For a bottom level category search
function SearchCategoryBl(parentid, bc) {
	// Load the breadcrumb into the arrays
	bc_push(parentid, bc);
	
	textSearch = " ";
	
	Search("/DataAction?section=category&action=products&parentid=" + parentid, productList);
}


// For a Text Search on Food Swap
function SearchTextFS(f) {
	
	// Validation
	if (f.txt_productsearch.value.length < 3)
	{
		alert("Please enter 3 or more characters to perform a search");
	} 
	else { // If validation passes
		ajax_request("/DataAction?section=search&action=text&text=" + f.txt_productsearch.value, fsSearchCallBack, {list: fsProductList} );
	}
	
	return false;
}

// For a Barcode Search on Food Swap
function SearchBarcodeFS(f) {
	
	// Validation
	if (f.txt_barcodesearch.value.length != 4) 
	{
		alert("Please enter 4 digits");
	} 
	else { // If validation passes		
		ajax_request("/DataAction?section=search&action=barcode&barcode=" + f.txt_barcodesearch.value, fsSearchCallBack, {list: fsProductList} );
	}
	
	return false;
}

// Food Swap search for flavour
function FSGetCombos(productid) {
	// Do Flavour Search first
	ajax_request("/DataAction?section=foodswap&action=flavour&productid=" + productid, fsComboCallBack, {list: fsFlavourList, productid: productid} );
}

// Food Swap search for flavour
//function FSSearchServing(productid) {
//	ajax_request("/DataAction?section=foodswap&action=serving&productid=" + productid, fsComboCallBack, {list: fsServingList} );
//}

// Food Swap search for flavour
//function FSSearchBrand(productid) {
//	ajax_request("/DataAction?section=foodswap&action=brand&productid=" + productid, fsComboCallBack, {list: fsBrandList} );
//}

// Food Swap Entry Function
//function FSGetCombos(productid) {
//	FSSearchFlavour(productid);
//}


// For a servings search
//function SearchServings() {
	//Search("/DataAction?section=search&action=servings&value="
//	Search("servings.json",servingList);
//}

// This starts the ajax request
function ajax_request(url, callback, args) {
        var request;
	var callbackArgs = args;

	request = new Ace.Request(Ace.Method.Get, url, null, null, callback, callbackArgs, Ace.CallbackOption.ReadyStateComplete);
	ajaxEngine.invoke(request);
}

// Generic Function to initiate the AJAX request using the correct content
function Search(url, contentFunc) {
	ajax_request(url, SearchCallBack, {list: contentFunc} );
}

// The callback function for search
function SearchCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	drawSearchBox(args.list);
}

// The callback function for servings
function ServingsCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	drawSearchServingsBox(args.list);
}

// The callback function for exercise
function ExerciseCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	drawExerciseBox(args.list);
}

// The callback function for foodswap combo boxes
function fsComboCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	fsComboBox(args.list);
	
	ajax_request("/DataAction?section=foodswap&action=brand&productid=" + args.productid, fsComboCallBackBrand, {list: fsBrandList} );
	// Do Servings Next
	//ajax_request("/DataAction?section=foodswap&action=serving&productid=" + args.productid, fsComboCallBackServing, {list: fsServingList, productid: args.productid} );
}
// The callback function for foodswap combo boxes
function fsComboCallBackServing(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	fsComboBox(args.list);
	
	// Do Brand Next
	ajax_request("/DataAction?section=foodswap&action=brand&productid=" + args.productid, fsComboCallBackBrand, {list: fsBrandList} );
}

// The callback function for foodswap combo boxes
function fsComboCallBackBrand(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	fsComboBox(args.list);
}

// The callback function for main categories
function CategoryCallBack(response, args) {
	checkLogin(response);
	// Get first response, then perform second request.
	jsonChildren = response.text.parseJSON();
	url = "/DataAction?section=category&action=popular&parentid=" + args.parentid;
	ajax_request(url, CategoryCallBackFinal, {parentid: args.parentid, children: jsonChildren} );
}

// The callback function for categories
function CategoryCallBackFinal(response, args) {
	checkLogin(response);
	jsonPopular = response.text.parseJSON();
	drawSearchBoxCategory(categoryMore, productList, args.children, jsonPopular);
}

// The callback function for a food swap search
function fsSearchCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	content = document.getElementById("scrollResults");
	content.innerHTML = '';
	args.list(content,jsonObj.ajaxJSON);
}

// Redirect if the user isn't logged in
function checkLogin(response) {
	if (response.text.indexOf("err:Unauthorised") != -1)
	{
		window.location.href = "http://" + document.domain + "/?errorMsg=Please log in first";
	}
}
// For a Servings Search  
function SearchDiaryServings(obj,diaryid,serving,productid,quantity,kcal,fatg) { 
	url = "/DataAction?section=search&action=product&productid=" + productid;
	
	currentobj = obj;
	currentdiaryobject.diaryid=diaryid;	
	currentdiaryobject.quantity = quantity;
	currentdiaryobject.serving = serving;
	currentdiaryobject.kcal = kcal;
	currentdiaryobject.fatg = fatg;
	currentdiaryobject.productid = productid
	
	//if(productid==-1)
	//	drawDiaryServingsBox(diaryservingList,currentobj,currentdiaryobject);
	//else
		ajax_request(url, DiaryServingsCallBack, {list: diaryservingList});
	return false;
}

// The callback function for servings
function DiaryServingsCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	drawDiaryServingsBox(args.list,currentobj,currentdiaryobject);
}
function SearchRecipeServingsList(obj,ingredientid,serving,productid,quantity,kcal,fatg) { 

	url = "/DataAction?section=search&action=product&productid=" + productid;

	currentobj = obj;
	currentdiaryobject.diaryid=ingredientid;
	currentdiaryobject.ingredientid=ingredientid;	
	currentdiaryobject.quantity = quantity;
	currentdiaryobject.serving = serving;
	currentdiaryobject.kcal = kcal;
	currentdiaryobject.fatg = fatg;
	currentdiaryobject.productid = productid

	ajax_request(url, DiaryServingsCallBack, {list: diaryservingList});
}

// For a Servings Search
function SearchEd(productid) {
	url = "/DataAction?section=search&action=product&productid=" + productid;
	currentpid = productid;
	ajax_request(url, EdCallBack, {list: productid} );
}
// The callback function for servings
function EdCallBack(response, args) {
	checkLogin(response);
	jsonObj = response.text.parseJSON();
	ED_create('diary',currentpid);
}
