var Foodberry = new Object();

window.onload = init; // call initialize function on window load
 
// *****************************************
// Initialization
// *****************************************

function init() {

    // Preload Images    
    pic1 = new Image(88, 39);
    pic2 = new Image(88, 39);
    pic1.src = "/images/btn_topNav_brightYellow.gif";
    pic2.src = "/images/btn_topNav_brightGreen.gif";


    // Event handlers
    document.getElementById("topNav1").onmouseover = mouseOverEffect;
    document.getElementById("topNav2").onmouseover = mouseOverEffect;
    document.getElementById("topNav3").onmouseover = mouseOverEffect;
    document.getElementById("topNav4").onmouseover = mouseOverEffect;
    document.getElementById("topNav5").onmouseover = mouseOverEffect;
    document.getElementById("topNav6").onmouseover = mouseOverEffect;
    document.getElementById("topNav7").onmouseover = mouseOverEffect;

    document.getElementById("topNav1").onmouseout = mouseOverEffect;
    document.getElementById("topNav2").onmouseout = mouseOverEffect;
    document.getElementById("topNav3").onmouseout = mouseOverEffect;
    document.getElementById("topNav4").onmouseout = mouseOverEffect;
    document.getElementById("topNav5").onmouseout = mouseOverEffect;
    document.getElementById("topNav6").onmouseout = mouseOverEffect;
    document.getElementById("topNav7").onmouseout = mouseOverEffect;

}      


// *****************************************
// Supporting Functions
// *****************************************

// Sets active section in top navigation menu
function setTopMenu(selected) {		
    document.getElementById("topNav"+selected).className = "selected";	 // change style of currently selected menu item
}


// On mouseOver, change element class (highlight top menu items on mouseover)
function mouseOverEffect() {
        if (this.className == "yellow") {
            this.className = "brightYellow";
        }
        else if (this.className == "brightYellow") {
            this.className = "yellow";
        }
        
        if (this.className == "green") {
            this.className = "brightGreen";
        }
        else if (this.className == "brightGreen") {
            this.className = "green";
        }
}


// Expand/Collapse Rows (Used for side navigation menu)
function toggle(id) {
    $(document.getElementById(id)).slideToggle();
}



// Show Div
function showDiv(id) {
    document.getElementById(id).style.display = "block";
}

// Hide Div
function hideDiv(id) {    
    document.getElementById(id).style.display = "none";
}


// Expand Current Side Menu
function expandSelectedSideMenu(category) {
    if (category != null && category != "") {
        document.getElementById("submenu_"+category).style.display = "block";
    }
}

// Bold Currently Selected Side Menu Item
function boldSelectedSideMenu(category) {
    if (category != null && category != "" && category > 0) {
        document.getElementById("link_cat"+category).style.fontWeight = "bold";
    }
}

/* ------------------------------------------------------------ */
/* Common AJAX Functions                                        */
/* ------------------------------------------------------------ */

// Creates XML HTTP Object
function GetXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
        // code for all new browsers
        return new XMLHttpRequest();      
    }
    else if (window.ActiveXObject)
    {
        // code for IE5 and IE6
        return new ActiveXObject("Microsoft.XMLHTTP");
    }
    else
    {
        //alert("Your browser does not support XMLHTTP.");
    }
}




/* ------------------------------------------------------------ */
/* Ad Sapce                                                     */
/* ------------------------------------------------------------ */

//  Global vars
var xmlhttpAdSpace;

// Initialize Ad Space (target = element to insert ad, adSize = ad size)
function initAdSpace(target, adSize) {
		xmlhttpAdSpace = GetXmlHttpObject();
		xmlhttpAdSpace.onreadystatechange= function() { writeAdSpace(target); }
		xmlhttpAdSpace.open("GET", "/xml/adspace_"+adSize+".xml",true);	
		xmlhttpAdSpace.send(null);
}


// Retreives banner info from XML and output to screen
function writeAdSpace(target)
{
    if (xmlhttpAdSpace.readyState==4) {   
        // 4 = "loaded"    
        if (xmlhttpAdSpace.status==200) {
            // 200 = OK 
            var xmlDoc2 = xmlhttpAdSpace.responseXML;
            var totalAdsFound = xmlDoc2.getElementsByTagName("item").length; // total ads found
            var randomNum = Math.floor(Math.random()*totalAdsFound);
            document.getElementById(target).innerHTML = xmlDoc2.getElementsByTagName("code")[randomNum].childNodes[0].nodeValue;            
        }
        else {
            //alert("Problem retrieving XML data");
        }
    }
}


/* ------------------------------------------------------------ */
/* Labels                                                       */
/* ------------------------------------------------------------ */

// Difficulty
function getLabelForDifficulty(value) {
    switch (value) {
        case 1:
            return "Simple";
        case 2:
            return "Easy";
        case 3:
            return "Moderate";
        case 4:
            return "Advanced";
        case 5:
            return "Expert";
        default:
            return "All";
    }
}

// Health Conscious
function getLabelForHealth(value) {
    switch (value) {
        case 1:
            return "Indulge";
        case 2:
            return "Splurge";
        case 3:
            return "Balanced";
        case 4:
            return "Healthy";
        case 5:
            return "Very Healthy";
        default:
            return "";
    }
}



// Search Event handlers
$(".search-input").focus(function() { if (this.value == this.title) { this.value = ""; } });
$(".search-input").blur(function() { if (this.value == "") { this.value = this.title; } });


/* -------------------------------------------------------- */
/*  Ajax Functions                                  		*/
/* -------------------------------------------------------- */

// Ajax Request
function ajaxRequest(xml, httpRequest, callback, targetID) {    
    httpRequest.onreadystatechange = function() { ajaxCallback(httpRequest, callback, targetID) };
    httpRequest.open("GET", xml, true);
    httpRequest.send(null);
}

// Ajax Callback function - calls requested function
function ajaxCallback(httpRequest, f, targetID) {
    f(httpRequest,targetID);
}

// Get node value for a given tag name
function getNodeValue(parentNode, instance, tagName) {
    var val = parentNode[instance].getElementsByTagName(tagName);
    try { return val[0].firstChild.nodeValue; }
    catch (ex) { return ""; }
}


/* -------------------------------------------------------- */
/*  Interface (Results Display)								*/
/* -------------------------------------------------------- */

function ajaxResultSet(objName, xml, targetID) {
    this.name = objName;
    this.currentPage = 1;
    this.pageSize = 10;
    this.totalPages = null;
    this.xmlSource = xml;
    this.httpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    this.target = document.getElementById(targetID);
    this.filter = function() {
        if (getFilterValues != "") { $(this.target).html(""); this.currentPage = 1; }
        ajaxRequest(xml + getFilterValues() + "&startIndex=1", this.httpRequest, writeResults, this);
    }
    this.update = function(sIndex) {
        if (sIndex == null) { sIndex = 1; $(this.target).html(""); currentPage = 1; }
        if (sIndex != 1) { this.currentPage++; }        
        ajaxRequest(xml + getFilterValues() + "&startIndex=" + sIndex, this.httpRequest, writeResults, this);
    }    
}

// Parse content from XML and display when loaded
function writeResults(httpRequest, ajaxResultSetObject) {
    // XML Loaded
    if (httpRequest.readyState == 4) {
        // Status 200 (OK)
        if (httpRequest.status == 200) {
            html = "";
            var numResults = httpRequest.responseXML.documentElement.getElementsByTagName("totalResults")
            totalResults = numResults[0].firstChild.nodeValue;
            var item = httpRequest.responseXML.documentElement.getElementsByTagName("item");
            for (i = 0; i < item.length; i++) {
                html += '<li>';
                html += '<span class="top">';
                html += '<ul>';
                html += '   <li><a href="' + getNodeValue(item, i, "link") + '" title="' + getNodeValue(item, i, "title") + '" class="thumbnail"><img src="' + getNodeValue(item, i, "image") + '"  /></a></li>';
                html += '   <li><a href="' + getNodeValue(item, i, "link") + '" title="' + getNodeValue(item, i, "title") + '" class="title">' + getNodeValue(item, i, "title") + '</a></li>';
                html += '   <li>By <a href="' + getNodeValue(item, i, "profile") + '" title="' + getNodeValue(item, i, "author") + '" class="author">' + getNodeValue(item, i, "author") + '</a></li>';
                html += '   <li>' + getStarRatingHTML(getNodeValue(item, i, "rating")) + '</li>';
                html += '   <li><span class="description">' + getNodeValue(item, i, "description") + ' <a href="' + getNodeValue(item, i, "link") + '" class="more">more</a></span></li>';
                html += '   <li name="facepile"></li>';
                html += '</ul>';
                html += '</span>';
                html += '<span class="bottom"></span>';
                html += '</li>';
            }
            if (item.length == 0) {
                html += '<li>Sorry, no search results found.</li>';
            }
            // Show next results link
            if (ajaxResultSetObject.currentPage < Math.ceil(totalResults / ajaxResultSetObject.pageSize)) {
                html += "<a href=\"javascript:" + ajaxResultSetObject.name + ".update(" + (ajaxResultSetObject.pageSize * ajaxResultSetObject.currentPage + 1) + ");\" class=\"view-more\"  id=\"viewMoreLink_" + ajaxResultSetObject.pageSize * ajaxResultSetObject.currentPage + "\">" + (totalResults - (ajaxResultSetObject.pageSize * (ajaxResultSetObject.currentPage - 1) + item.length)) + " results remaining. Click to show more.</a>";
            }
            try {
                $('html,body').delay(1000).animate({ scrollTop: $("#viewMoreLink_" + ajaxResultSetObject.pageSize * (ajaxResultSetObject.currentPage - 1)).offset().top }, 'slow');  // scroll new results to top
            }
            catch (ex) { }
            $(ajaxResultSetObject.target).html($(ajaxResultSetObject.target).html() + html);
            $("#viewMoreLink_" + ajaxResultSetObject.pageSize * (ajaxResultSetObject.currentPage - 1)).fadeOut('slow'); // hide view more results link for previous page
            return;
        }
        else {
            // Error
        }
    }

}


// *****************************************
// Recipe Image Gallery
// *****************************************


// Replaces larger image with thumbnail src
// Also accepts third param to set caption text
function showFullSizeImage(imgObj, targetID, captionID) {

    var targetImg = document.getElementById(targetID);

    

        // Update target image with new src/alt		
        targetImg.src = imgObj.src.replace("&width=45&height=45","");
        targetImg.alt = imgObj.alt;
        targetImg.title = imgObj.title;

        // If captionID provided, update caption div
        if (captionID) {
            var captionDiv = document.getElementById(captionID);
            if (imgObj.title) {
                captionDiv.innerHTML = imgObj.title;
                $(captionDiv).show();
            }
            else {
                captionDiv.innerHTML = "";
                $(captionDiv).hide();
            }
        }


}

// Restore original recipe image to original
function restoreOriginalImage(targetID, captionID) {


        document.getElementById(targetID).src = originalRecipeImage;
        document.getElementById(captionID).innerHTML = originalRecipeCaption;        
        if (originalRecipeCaption != "") {
            $("#"+captionID).show();
        }
        else {
            $("#" + captionID).hide();
        }
        $("#" + targetID).fadeIn('fast');


}





/* ************************************************************ */
/*  Facebook Integration                                        */
/*  Description: Supports integration of Facebook within        */
/*  Foodberry                                                   */
/* ************************************************************ */

Foodberry.Facebook = {

    /* ------------------------------------------------------------ */
    /* Loads Facebook framework, and initializes                    */
    /* ------------------------------------------------------------ */

    Init: function () {

        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/all.js";
            js.onload = function () {
                FB.init({
                    appId: '120518609088',
                    cookie: true,
                    status: true,
                    xfbml: true,
                    oauth: true
                });
            }
            fjs.parentNode.insertBefore(js, fjs);
        } (document, 'script', 'facebook-jssdk'));

    },

    /* ------------------------------------------------------------ */
    /* Facebook Open Graph Actions                                  */
    /* ------------------------------------------------------------ */

    DoAction: function (action, url, callback) {

        var accessToken;

        // Check if user is logged into Facebook
        FB.getLoginStatus(function (response) {
            if (response.authResponse) {
                //console.dir(response);
                accessToken = response.authResponse.accessToken;
            } else {
                //alert('not logged in');
                // Prompt user to log-in to facebook
                FB.login(function (response) {
                    if (response.authResponse) {
                        accessToken = response.authResponse.accessToken;
                    }
                });
            }

            // Now that we have an access token, perform API call
            FB.api('/me/foodberry:' + action + '&recipe=' + url, 'post', function (response) {
                if (!response || response.error) {
                    //alert('Error occured');
                    callback(false);
                } else {
                    //alert('Post was successful! Action ID: ' + response.id);
                    if (typeof callback != undefined) {
                        callback(true);
                    }
                }
            });
        });
    }
}   



/* ************************************************************ */
/*  Foodberry UI                                                */
/*  Description: Foodberry User Interface                       */
/* ************************************************************ */

Foodberry.UI = { 

    // ---------------------------------------- //
    // Create Modal Overlay						//
    // ---------------------------------------- //
    Modal : function(uniqueID, title, html1, html2, callback) {
	
	    // Create Modal Structure
	    var modalDiv = document.createElement("div");
	    modalDiv.id = uniqueID;
	    modalDiv.className = "dialog";
	    var topDiv = document.createElement("div");
	    topDiv.className = "dialog-topCap";
	    var middleDiv = document.createElement("div");
	    middleDiv.className = "dialog-middle";
	    middleDiv.innerHTML = (title) ? "<h1>"+title+"</h1>" : "";
	    middleDiv.innerHTML += (html1) ? html1 : "";
	    middleDiv.innerHTML += (html2) ? html2 : "";
	    var bottomDiv = document.createElement("div");
	    bottomDiv.className = "dialog-bottomCap";			
	    modalDiv.appendChild(topDiv);
	    modalDiv.appendChild(middleDiv);
	    modalDiv.appendChild(bottomDiv);
	
	    // Scroll to top of page
	    $('body').animate({scrollTop:0}, 'slow', function() {
															
		    // Add Modal to below <body> tag
		    var bodyTag = document.getElementsByTagName("body")[0];
		    bodyTag.insertBefore(modalDiv,bodyTag.firstChild);
		
		    // Create Modal Effect
		    $(function() {	
			    $("#"+uniqueID).dialog({
				    close: function(event, ui) { 
					    // When closed, removed from DOM
					    $("#"+uniqueID).dialog("destroy"); 
					    bodyTag.removeChild(document.getElementById(uniqueID))
				    },
				    width: 647,
				    //height: 400,
				    modal: true,
				    autoOpen: true,
				    closeText: 'x'		 	
			    });		
	
		    });	 
			
		    // Initiate callback function
		    if (callback) {
			    callback();	
		    }
														
	    });	
		
    }
    
}





