﻿/* ------------------------------------------------------------ */
/* Seach By Ingredient Page Functionality                       */
/* ------------------------------------------------------------ */


var xmlhttp2;
var searchIngredientsArray = new Array();


// Sets event handlers
function initSearchByIngredient() {
    document.getElementById("ingredientSearchPageBox").onfocus = sbi_setActive;
    document.getElementById("ingredientSearchPageBox").onblur = sbi_setInActive;
    document.getElementById("ingredientSearchPageBox").onkeyup = getRecipesFromXML;
}

// Changes css class when focused
function sbi_setActive() {
    this.className = "";
    this.select();
}

// Changes css class when blurred
function sbi_setInActive() {
    if (this.value == "Ingredient 1, Ingredient 2, Ingredient 3...") {
        this.className = "inactive";
        clearResults();
    }
    else if (this.value == "") {
        this.value = "Ingredient 1, Ingredient 2, Ingredient 3...";
        this.className = "inactive";
        clearResults();
    }
}


// Check XML for recipe matches
function getRecipesFromXML() {

    if (this.value != "," && this.value != "") {
        searchIngredientsArray = convertStringToArray(this.value.toLowerCase());
        xmlhttp2 = GetXmlHttpObject();
        xmlhttp2.onreadystatechange=writeRecipesByIngredient;
        xmlhttp2.open("GET","/xml/recipesXML.aspx",true);
        xmlhttp2.send(null);
    }
    else {
        clearResults();
    }
    
}

// Convers a comma seperate string to an array
function convertStringToArray(str) {    
    var strArray = new Array();    
    strArray = str.split(',');
    return strArray;   
}


// Returns whether or not all search terms (in the array) were found in string
function allSearchTermsFound(str) {

    var isMatch = true; 
    str = str.toLowerCase(); // convert to lower case     
    
    for (j=0; j<searchIngredientsArray.length; j++) {
        if (str.indexOf(searchIngredientsArray[j]) == -1) {
            isMatch = false;
        }
    }    
    
    return isMatch;    
}


// Writes results to screen
function writeRecipesByIngredient()
{

    showLoading();
    var recipesFound = 0;
    
    if (xmlhttp2.readyState==4)
    {   
        // 4 = "loaded"
        if (xmlhttp2.status==200)
        {
            // 200 = OK
            // ...our code here...            
            xmlDoc = xmlhttp2.responseXML;             

            var responseText = '<div id="ingredientSearchPageResultsTopCap"><div class="resultTitle"><h1>Here\'s a few suggestions</h1>Based on the ingredients you entered above, here\'s a few recipes you can make.</div></div>';
            responseText += '<div id="ingredientSearchPageResultsMiddle">';
            
            // Loop through each item in xml doc (start at 1 to go to first post)
            for (x=0; x<xmlDoc.getElementsByTagName("recipe").length; x++) {
                                
                var ingredients = xmlDoc.getElementsByTagName("ingredients")[x].childNodes[0].nodeValue;                
                
                // Check all ingredients inputted to see if there's a match (note all search terms entered must match to return a result)
                if (allSearchTermsFound(ingredients)) {
                        responseText += "<div class='resultRowWrapper'>";
                        responseText += "<a href='/recipe.aspx?id=" + xmlDoc.getElementsByTagName("id")[x].childNodes[0].nodeValue + "' class='recipeName floatLeft'>" + xmlDoc.getElementsByTagName("name")[x].childNodes[0].nodeValue + "</a>";
                        responseText += "<a href='/recipe.aspx?id=" + xmlDoc.getElementsByTagName("id")[x].childNodes[0].nodeValue + "' class='viewRecipeButton' title='View Recipe'>View Recipe</a>";
                        responseText += "<div class='clear'></div>";
                        responseText += "</div>";
                        recipesFound++;
                }
                
            }
            
            responseText += '</div>';
            responseText += '<div id="ingredientSearchPageResultsBotomCap"></div>';
            
            if (recipesFound > 0) {
                // Write response to div if recipes found
                document.getElementById("ingredientSearchPageResults").innerHTML = responseText;            
            }
            else {
                // If no recipes found, advise user
                responseText = "<p class='strong'>Sorry, I couldn't find any recipes that match the ingredients you entered.</p>";
                responseText += "<p>Try removing an ingredient, and try your search again. Remember to seperate each ingredient with a comma.</p>";
                document.getElementById("ingredientSearchPageResults").innerHTML = responseText;
            }
            
            
        }
        else
        {
            //alert("Problem retrieving XML data");
        }
    }
}


// Clears results
function clearResults() {
    document.getElementById("ingredientSearchPageResults").innerHTML = "";
}

// Display Loading Status
function showLoading() {

    var results = document.getElementById("ingredientSearchPageResults");
    var output;
    
    output =  "<div class='loadingDiv'>";
    output += "  <p>Looking for recipes, hold on a sec...</p>";
    output += "  <img src='/images/ajax-loader-white.gif' />";
    output += "</div>";
    
    results.innerHTML = output;

}

