/*
 * author : michael bosworth 2006
 *
 *
 * note : this class is dependant on : /web/common/js/lib/prototype/prototype.lite.js
 *                                     /web/common/js/lib/moofx/moo.fx.js
 *                                     /web/common/js/lib/moofx/moo.fx.utils.js
 *                                     /web/common/js/ui/carousel/carousel.js
 *                                     /web/common/js/ui/tooltip/tooltip.js
 * these files must be included with this script to function.
*/

$(document).ready( function(){
	mealIdeasInit();
});	

/* Checks for page specific elements and runs appropriate initialization function */
function mealIdeasInit(){
    /* If view page  */
    if($("#detail").length > 0){
        viewInit();
    }
    /* If explorer page  */
    else if($("#efeatured").length > 0){
        explorerInit();
    }
    /* If create page  */
    else if($("#sidedish2").length > 0){
		sideDishInterfaceInit();
        sideDishSelectorInit();
		initToggle(100);
    }
    /* If results page  */
    else if($("#results").length > 0){
        resultsInit();
    }
}

var myTarget;
var directionslink;
var dirHeight;
function initToggle(offset){
	directionslink = $("#directionslink");
	if(offset == null){
        offset = 0;
    }
	dirHeight = myTarget.height() + offset;
	myTarget.css({position:'relative', visibility:'visible', height:'0px'});
	$("#directionslink").click(function(){ toggleHeight(); directionslink.html((directionslink.html() == 'View recipe details') ? "Hide recipe details" : "View recipe details"); });
}

function toggleHeight(){
	if(myTarget.height() == dirHeight){
		myTarget.animate({height:0},500);
	}
	else{
		myTarget.animate({height:dirHeight},500);
	}
}

/* ------------------------------------Meal Ideas View Page Javascript----------------------------------------- */

    function viewInit()
    {
		initToggle();
		var customize = $("#customize");
		customize.mouseover(function(){ toggleDisplay(); });
		customize.mouseout(function(){ toggleDisplay(); });
    }

    var rollover;
    function toggleDisplay(){
        if(rollover == null){
            rollover = $("#mirollover");
            rollover.css('visibility',"hidden");
        }
        if(rollover != null){
            if(rollover.css('visibility') == "hidden"){
              rollover.css('visibility',"visible");
            }
            else{
              rollover.css('visibility',"hidden");
            }
        }
    }

/* End of Meal Ideas View Page Javascript*/


/* ------------------------------------Meal Ideas Explorer Page Javascript---------------------------------- */
    var Ecarousel = new Carousel();
    var Scarousel = new Carousel();
    var etooltip = new ToolTip();
    var isIE;
    var checkSponsors = false;

    function explorerInit(){
        /* Check for IE */
        isIE = $.browser.msie;

        /* Initialize tooltip */
        etooltip.init(300,0,true);

        /* Initialize carousel */
        carouselInit();
    }

    /* Renders the tooltip */
    etooltip.render = function(){
        this.tooltip = document.createElement("div");
        this.tooltip.id = "etooltipWrap";

        var content = document.createElement("div");
        content.id = "tooltip";
        content.className = "brandcol5";
        var tip_img = document.createElement("div");
        if(isIE){
            tip_img.className = "tipIE";
        }
        else{
            tip_img.className ="tip";
        }
        content.appendChild(tip_img);

        tip_img.style.top = "-40px";
        this.tooltip.style.top = this.findPosY(this.relativeEl)  + "px";
        this.tooltip.style.left = this.findPosX(this.relativeEl) + 112 + "px";

        var item = itemLookup(this.relativeEl.src);
        if(item != null){
            var mTitle = document.createElement("h2");
            mTitle.innerHTML = item[0];
            var rTitle = document.createElement("strong");
            rTitle.innerHTML = item[5];
            rTitle.className = "txtcol2";
            var text = document.createElement("span");
            var sideDishes = document.createElement("strong");
            if(item[6] != ""){
                text.innerHTML = "with";
                sideDishes.innerHTML = item[6];
            }
        }

        content.appendChild(mTitle);
        content.appendChild(rTitle);
        content.appendChild(document.createElement("br"));
        content.appendChild(text);
        content.appendChild(document.createElement("br"));
        content.appendChild(sideDishes);

        this.tooltip.appendChild(content);
        document.body.appendChild(this.tooltip);
    };

    /* Finds meal idea information by matching the image path on the page to the image path in either
       the Eargs or Sargs array */
    function itemLookup(imgPath){
        for(var i=0; i<Eargs.length; i++ ){
            if(Eargs[i][1] == imgPath){
                return Eargs[i];
            }
        }
        if(Sargs.length > 0){
            for(var i=0; i<Sargs.length; i++ ){
                if(Sargs[i][1] == imgPath){
                    return Sargs[i];
                }
            }
        }
        return null;
    }

    /* Initializes either one or two carousels based on the existance of div element 'monitor2'
       which is present only when the the information for two carousels is available */
    function carouselInit(){
        Ecarousel.imageIndex = Scarousel.imageIndex = 1;
        if($("#monitor2") != null){
            checkSponsors = true;
            Ecarousel.init(Eargs, 125,375,170,3,"slideshow1","active1","monitor1",700);
            Scarousel.init(Sargs, 125,375,170,3,"slideshow2","active2","monitor2",700);            
        }
        else{
            var ary = new Array();
            ary = ary.concat(Eargs,Sargs);
            Ecarousel.init(ary, 125,375,360,6,"slideshow1","active1","monitor1",700);
        }
        if(Ecarousel.scrollLock){
            $("#ebtnleft").css('visibility','hidden');
            $("#ebtnright").css('visibility','hidden');
        }
        if(Scarousel.scrollLock){
            $("#sbtnleft").css('visibility','hidden');
            $("#sbtnright").css('visibility','hidden');
        }
    }

    /* Renders a single 'item' in a carousel */
    Ecarousel.render = Scarousel.render = function(index,hide){
        var ss_item = document.createElement("div");
        ss_item.style.cssFloat = this.direction;
        ss_item.className = "citem";
        ss_item.cssFloat = this.direction;
        ss_item.id = this.args[index][4];
        if(hide){ ss_item.style.width = "0px"; }
        /* create image tag */
        var ss_imgLink = document.createElement("a");
        var milink;
        var isSponsored = false;
        if(checkSponsors){
            if(Sargs[index] != null){
                if(this.args[index][4] == Sargs[index][4]){
                    milink = "/recipes/mealideas/searchResults.jsp?searchType=sponsor&searchTerm=" + this.args[index][4];
                    isSponsored = true;
                }
                else{
                    milink = "/recipes/mealideas/view.jsp?id=" + this.args[index][4];    
                }
            }
            else{
                milink = "/recipes/mealideas/view.jsp?id=" + this.args[index][4];
            }
        }
        else{
            milink = "/recipes/mealideas/view.jsp?id=" + this.args[index][4];
        }     
        ss_imgLink.href = milink;
        var ss_imgWrap = document.createElement("div");
        ss_imgWrap.style.height = "83px";
        ss_imgWrap.style.overflow = "hidden";
        var ss_img = document.createElement("img");
        ss_img.src = this.loadedImages[index].src;
        ss_img.onmouseover = function() {
            etooltip.create(this);
        };
        ss_img.onmouseout = function() {
            etooltip.remove();
        };
        ss_img.onclick = function() {
            window.location = milink;
        };
        ss_imgWrap.appendChild(ss_img);
        ss_imgLink.appendChild(ss_imgWrap);
        /* create anchor tag */
        var ss_link = document.createElement("a");
        ss_link.href = milink;
        if(isSponsored){
            ss_link.innerHTML = this.args[index][this.args[index].length - 1];
        }
        else{
            ss_link.innerHTML = this.args[index][0];
        }
        ss_link.className = "itemlink";
        var ss_ratingWrap = document.createElement("div");
        /* create image tag */
        var ss_img2 = document.createElement("img");
        ss_img2.src = "http://images.meredith.com/bhg/images/tmp/mi/" + this.args[index][2] + "star.gif";
        /* create span tag */
        var ss_span = document.createElement("span");
        ss_span.innerHTML = "&nbsp;(<strong class='txtcol1'>" + this.args[index][3] + "</strong>)";
        ss_ratingWrap.appendChild(ss_img2);
        ss_ratingWrap.appendChild(ss_span);

        ss_item.appendChild(ss_imgLink);
        ss_item.appendChild(ss_link);
        ss_item.appendChild(ss_ratingWrap);
        return ss_item;
    };
/* End of Meal Ideas Explorer Page Javascript */


/* ----------------------------------Meal Ideas Create Page Javascript----------------------------------- */
/* initialize variables */
var effect_ary = new Array(4);
var size;

/* initialize effects */
function sideDishInterfaceInit(){
    myEffect = $("#vdirections");
    effect_ary[0] = $("#sidedish2");
    effect_ary[1] = $("#sidedish3");
    effect_ary[2] = $("#sidedish4");
    effect_ary[3] = $("#sidedish5");
    
	var sidedish2 = $("#sidedish2");
	sidedish2.css('height',"auto");
	size = sidedish2.height();
	
	var sides = $('#csidedish').find('div[id^=sidedish]');
	for(var i=2; i<sides.length; i++){
		sides[i].className = "closed";
	}
}

/* shows first hidden sidedish */
function addSidedish(){
	var firstClosed = $('div.closed:first','csidedish');
    if(firstClosed != null){
		var index = parseInt(firstClosed.id.substr(firstClosed.id.length-1))-2;
        effect_ary[index].animate({height:size},500);
        firstClosed[0].className = "";
    }
    else{
        alert("Meal ideas can have a maximum of 5 side dishes!");
    }
}

/* hides selected side dish */
function removeSidedish(index){
    var div = $("#sidedish" + index);
    lastRemoved = index;
	effect_ary[index-2].animate({height:0},500);
	div.className = "closed";
	clearFields(index);
}

/* clears the fields of the removed side dish */
function clearFields(index){
    $('input:first','sidedish'+index)[0].value = "";
    $('textarea:first','sidedish'+index)[0].value = "";
}

/* Side Dish Selector Javascript */

var sideDishCarousel = new Carousel();
var opEffect;
var selector;
var titleElement;
var descElement;

/* Initializes main variables */
function sideDishSelectorInit(){
    sideDishCarousel.init(null,220,220,null,1,"pDiv","active","monitor",null);
    MealIdeaService.getSideDishesByType("Rice",returnResult);
    selector = $('#scontainer');
	opEffect = $('#scontainer');
    opEffect.hide();
}

/* Adjusts side dish selector dropshadow */
function adjustDropShadow(){
    var height = parseFloat($("#swrap").height());
    selector.css('height',height + 5 + "px");
}

/* Populates the side dish selector carousel with an array contained in 'obj' */
function returnResult(obj){
    sideDishCarousel.populate(obj.result);
}

/* Fills out a side dish form with info selected in the side dish selector */
function pasteInfoTo(){
    titleElement.value = sideDishCarousel.args[sideDishCarousel.index-1].title;
    descElement.value = sideDishCarousel.args[sideDishCarousel.index-1].description;
    hideSideDishSelector();
}

/* Finds the y coordinate of HTML element 'obj' on the page */
function findPosY(obj){
    var curtop = 0;
    if(obj.offsetParent)
        {
            while (1)
            {
                curtop += obj.offsetTop;
                if (!obj.offsetParent)
                {
                    break;
                }
                obj = obj.offsetParent;
            }
        }
    else {
        if (obj.y)
        {
            curtop += obj.y;
        }
    }
    return curtop;
}


/* Shows the side dish selector window  */
function showSideDishSelector(element1,element2,element3){
    selector.hide();
    selector.animate({'opacity':1},300);
    selector.css('display',"block");
    selector.css('top',(findPosY(element1) + -180) + "px");
    selector.css('left',"138px");
    titleElement = $(element2);
    descElement = $(element3);
}

/* Hides the side dish selector HTML elements */
function hideSideDishSelector(){
    selector.css('display',"none");
    selector.hide();
}
 
/* Renders a single item within carousel */
sideDishCarousel.render = function(index,hide){
    var c_item = document.createElement("div");
    c_item.id = "sideDish_" + index;
    c_item.textAlign = "center";
    c_item.overflow = "hidden";
    if(hide){ c_item.style.width = "0px"; }
    var c_title = document.createElement("div");
    c_title.innerHTML = this.args[index].title;
    c_title.className = "txtcol5";
    c_title.fontWeight = "bold";
    c_title.style.width = this.iwidth + "px";
    var c_desc = document.createElement("div");
    c_desc.style.width = this.iwidth + "px";
    c_desc.innerHTML = this.args[index].description;
    /* add tags to active div */
    c_item.appendChild(c_title);
    c_item.appendChild(c_desc);
    return c_item;
};
/* End of Meal Ideas Create Page Javascript */



/* ----------------------------------Meal Ideas Results Page Javascript-------------------------------------------- */
var tooltip = new ToolTip();
var select1;
var select2;
var mitid = null;
var overTooltip = false;
var resultsLoaded = false;
/* tooltip elements */
var tooltipwrap, content, tip_img, img, type, subContain, mTitle, rTitle, text, sideDishes;

function resultsInit(){
    /* Initialize tooltip */
    tooltip.init(100,0,false);

    /* Check for IE */
    isIE = $.browser.msie;

    /* Fix png rendering if needed */
    fixPNG();

    /* DOM lookups */
    select1 = $("#select1")[0];
    select2 = $("#select2")[0];
    tooltipwrap = $("#tooltipWrap")[0];
    content = $("#tooltip")[0];
    tip_img =  $("#tip")[0];
    img = $("#timg")[0];
    type = $("#tcat")[0];
    mTitle = $("#tooltiptitle")[0];
    rTitle = tooltipwrap.find("a")[0];
    text = tooltipwrap.find("span")[0];
    sideDishes = tooltipwrap.find("strong")[0];
    tooltip.tooltip = tooltipwrap;
    resultsLoaded = true;
}

/* Fixes PNG images for display in versions of IE */
function fixPNG(){
    if(isIE){
        var ary = $("#results").find("img");
        for(var i=0; i<ary.length; i++){
            if(ary[i].src.substring(ary[i].src.length-3).match("png")){
                var newTag = "<span style=\"display:inline-block; height:11px; width:65px; vertical-align:middle; overflow:hidden; filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ary[i].src+"',sizingMethod='scale');\"></span>";
                ary[i].outerHTML = newTag;
            }
        }
    }
}

/* Renders tooltip and appends it to the page */
function show(element){        
    if(resultsLoaded){
        if(mitid != null)
            {
                clearTimeout(mitid);
            }
        if(isIE){
            select1.style.visibility = "hidden";
            select2.style.visibility = "hidden";
        }
        /* Switch tip img classes based on browser */
        if(isIE){
            tip_img.className = "tipIE";
            select1.style.visibility = "hidden";
            select2.style.visibility = "hidden";
        }
        else{
            tip_img.className = "tip";
        }
        /* Position tooltip */
        if(tooltip.findPosY(element) == null || tooltip.findPosX(element) == null){
            return;
        }
        else{
            if(isIE){
                tooltipwrap.style.top = (tooltip.findPosY(element) -308) + "px";
            }
            else{
                tooltipwrap.style.top = (tooltip.findPosY(element) -305) + "px";
            }
            tooltipwrap.style.left = (tooltip.findMousePosX() + 130)  + "px";

            var ary = element.parentNode.parentNode.parentNode.getElementsByTagName("input");

            if(ary.length == 4){
                if(ary[0] != null){img.src = ary[0].value; img.alt = ""; }
                type.innerHTML = element.parentNode.parentNode.parentNode.getElementsByTagName("td")[1].innerHTML;
                mTitle.innerHTML = element.innerHTML;
                if(ary[2] != null){rTitle.innerHTML = ary[2].value;}
                if(ary[3] != null){rTitle.href = ary[3].value;}
                if(ary[1].value != ""){
                    text.innerHTML = "with";
                    sideDishes.innerHTML = ary[1].value;
                }
            }
            else if(ary.length == 3){
                img.src = ""; img.alt = "No image available."; 
                type.innerHTML = element.parentNode.parentNode.parentNode.getElementsByTagName("td")[1].innerHTML;
                mTitle.innerHTML = element.innerHTML;
                if(ary[1] != null){rTitle.innerHTML = ary[1].value;}
                if(ary[2] != null){rTitle.href = ary[2].value;}
                if(ary[0].value != ""){
                    text.innerHTML = "with";
                    sideDishes.innerHTML = ary[0].value;
                }
            }
            tooltipwrap.style.display = "block";
        }
        mitid = setTimeout("hide()",2000);
    }
}

/* Removes and releases the tooltip from the page */
function hide(){
    tooltipwrap.style.display = "none";
    if(isIE){
        select1.style.visibility = "visible";
        select2.style.visibility = "visible";
    }
}

/* Handles changes to HTML select boxes */
function onChange() {
    var currentSortBy = document.searchForm.sortBy.selectedIndex;
    var currentFilter = document.searchForm.filter.selectedIndex;
    var destUrl = "/recipes/mealideas/searchResults.jsp?sortBy=" + document.searchForm.sortBy.options[currentSortBy].value + "&filter="+document.searchForm.filter.options[currentFilter].value;
    document.location.href= destUrl;
}
/* End of Meal Ideas Results Page Javascript */
