﻿/// <reference path="jquery-1.4.1-vsdoc.js"/>
//Tips Landing Page
//Enable tab switching and set the lifestyle as the default tab with CSS active class
function changeTabsLandingPage() {

    $('li.tip-overview-tab#fitness-tab').addClass('active');
    $('div.tip-description#fitness-tips').addClass('active');
    $('div.tips-images#fitness-images').addClass('active');

    $('li.tip-overview-tab').click(function() {
        if (!$(this).is('.active')) {

            var new_active = $(this).attr('id').substring(0, $(this).attr('id').indexOf('-'));

            $('li.tip-overview-tab.active').removeClass('active');
            $('div.tip-description.active').removeClass('active');
            $('div.tips-images.active').removeClass('active');

            $('li.tip-overview-tab#' + new_active + '-tab').addClass('active');
            $('div.tip-description#' + new_active + '-tips').addClass('active');
            $('div.tips-images#' + new_active + '-images').addClass('active');

        }

    });

}

//This should cycle the content of the current active tip tab
function cycleTipsLandingPage() {
    $('.tip-description').cycle({
        fx: 'fade',
        slideExpr: 'div.rotating-tip',
        cleartypeNoBg: true,
        timeout: 12000
    });
    $('div.tips-images').cycle({
        fx: 'fade',
        slideExpr: 'img.tip-top-image',
        timeout: 12000
    });
}

function cycleImageTips() {
    $('#tip-left-col').cycle({
        fx: 'fade',
        pager: '#left-rotating-image-nav',
        pagerAnchorBuilder: function(idx, slide) {
            return '<li><a href="#">' + idx + '</a></li>';
        },
        slideExpr: 'div.rotate-container',
        timeout: 8000
    });
}

function cycleImageIdeas() {
    $('#rotating-food-image-ideas').cycle({
        fx: 'fade',
        pager: '#rotating-food-nav-ideas',
        pagerAnchorBuilder: function(idx, slide) {
            return '<li><a href="#">' + idx + '</a></li>';
        },
        slideExpr: 'div.rotating-image',
        timeout: 8000
    });
}

function cycleImageRecipes() {
    $('#rotating-food-image').cycle({
        fx: 'fade',
        pager: '#rotating-food-nav',
        pagerAnchorBuilder: function(idx, slide) {
            return '<li><a href="#">' + idx + '</a></li>';
        },
        slideExpr: 'div.rotating-image'
    });
}


//Recipes overview page, show all/vegetarian options
/*function toggleVegetarian() {

    $('a#sort-vegetarian-meals').click(function() {

        if ($(this).attr('class').search('current') == -1) {

            $(this).addClass('current');
            $('a#sort-all-meals').removeClass('current');

            //first remove all the items that are not vegetarian
            $('li.recipes-list-recipe:not(.vegetarian)').slideUp('slow');

            //next, redo the alt striping to take into account the new list position
            $('li.recipes-list-recipe.alt').removeClass('alt');
            $('li.recipes-list-recipe:even').addClass('alt');

        }

    });

    $('a#sort-all-meals').click(function() {

        if ($(this).attr('class').search('current') == -1) {

            $(this).addClass('current');
            $('a#sort-vegetarian-meals').removeClass('current');

            //first show all the items that are not vegetarian
            $('li.recipes-list-recipe:not(.vegetarian)').slideDown('slow');

            //next, redo the alt striping to take into account the new list position
            $('li.recipes-list-recipe.alt').removeClass('alt');
            $('li.recipes-list-recipe:even').addClass('alt');

        }

    });

    //we're also going to inject the vegetarian icon into those recipes here
    $('li.recipes-list-recipe.vegetarian div.recipe-text p.recipe-name').append('<span class="vegetarian"></span>');

}*/
var resultsPerPage = 10;
var currentSelector;
var currentSelectedType;
var currentPath;
var currentLocation;
if ($.sammy != undefined) {
    ; (function($) {
        var app = $.sammy(function() {
            this.get('#/dinner/:num', function() {
                reorderList('Dinner', Number(this.params['num']));
            });
            this.get('#/lunch/:num', function() {
                reorderList('Lunch', Number(this.params['num']));
            });
            this.get('#/breakfast/:num', function() {
                reorderList('Breakfast', Number(this.params['num']));
            });
            this.get('#/vegetarian/:num', function() {
                reorderList('Vegetarian', Number(this.params['num']));
            });
            this.get('#/:num', function() {
                reorderList('All', Number(this.params['num']));
            });
            currentLocation = this.getLocation();


        });

        $(function() {
            app.run('#/1');

        });
    })(jQuery);
}


function reorderList(type, num) {
    $('li.recipes-list-recipe').remove();
    currentSelectedType = type;
    countChild = 0;
    $("#recipes-list-header a[href='#/" + type + "']").addClass('current');

    var url = "/tips-and-tools/paged-recipes/" + type + "/" + (num - 1);


    $("#recipes-list").before('<img id="challenge-loader" class="loader" src="/_res/i/site/ajax-loader.gif" alt="">');
    
    $.ajax({
        url: url,
        dataType: 'json',
        success: onRecipesLoaded
    });

    if (type == "All") {
        currentPath = "#/" + num;
    } else {
        currentPath = "#/" + currentSelectedType.toLowerCase() + "/" + num;
    }
    
/*
    reorderListPage(num);
    setCurrentPage(num);
    setCurrentPagePagination(num - 1, false)*/


}

function onRecipesLoaded(data) {

    $("#challenge-loader").remove();
    var recipes_str = "";
    for(var d = 0 ; d < data.Recipes.length; d++){
        recipes_str += recipeTpl(data.Recipes[d]);
    }
    $("#recipes-list").append(recipes_str);

    $('li.recipes-list-recipe').each(function(index) {
        if (index % 2 != 0) {
            $(this).addClass('alt');
        } else {
            $(this).removeClass('alt');
        }
        $(this).hide().delay(120 * index).slideDown(100);
    });

    reorderListPage(data.CurrentPage, resultsPerPage * data.TotalPages);



    serViewAll_href();   

}


function recipeTpl(recipeData){
    var tpl = '<li class="recipes-list-recipe">';
    tpl += '    <a href="' + recipeData.RouteName + '"  class="google-track" rev="1317-' + recipeData.KicId + '"><img width="140" src="/_res/i/recipes/thmbs/' + recipeData.ThumbnailImage + '" alt="' + recipeData.ImageAltTag + '" class="recipe-thmb" /></a>'
    tpl += '    <div class="recipe-text">' ;
    tpl += '        <p class="recipe-name"> ';
    tpl += '            <a href="' + recipeData.RouteName + '" class="google-track" rev="1317-' + recipeData.KicId + '"><span class="name">' + recipeData.Name + '</span></a>';
    tpl +=              (recipeData.VegetarianFlag == 'Yes' ? '<span class="vegetarian"></span>' : '') +'</p>';
    tpl += '        <p class="recipe-description">' + recipeData.Description + '</p>';
    tpl += '    </div>';
    tpl += '    <p class="view-recipe"><a href="' + recipeData.RouteName + '" class="google-track" rev="1317-' + recipeData.KicId + '">View Recipe</a></p>';
    tpl += '</li>';
    return tpl;
}
function reorderListPage(num, count) {
    if ($('#pagination').length > 0) {
        if (count <= resultsPerPage) {
            $("#pagination").html('');
            return;
        }
        var opt = {
            callback: setCurrentPagePagination,
            items_per_page: resultsPerPage,
            current_page: num,
            prev_text: "Prev",
            next_text: "Next"
        };
        $("#pagination").pagination(count, opt); 
    }             
}
function setCurrentPagePagination(n , setLocation) {

    var num = n + 1;
    if (currentSelectedType == "All") {
        currentPath = "#/" + num ;
    } else {
        currentPath = "#/" + currentSelectedType.toLowerCase() + "/" + num;
    }
    if (setLocation == true || setLocation) {
        window.location = currentPath;
    }
    
    serViewAll_href();
}
function serViewAll_href() {
    $(".recipes-list-recipe a").each(function(index) {
        var view_href = $(this).attr("href");
        view_href = view_href.split("#")[0];
        if (currentPath != undefined) {
            $(this).attr("href", view_href + currentPath);
        }
    });
}
function setCurrentPage(n)
{
    var num = n ;
    var min = (num - 1) * resultsPerPage;
    var max = (num * resultsPerPage);
    $(currentSelector).each(function(index) {
        var _index = index;
        if (_index >= min && _index < max) {
            $(this).slideDown('slow');
            if (_index % 2 != 0) {
                $(this).addClass('alt');
            } else {
                $(this).removeClass('alt');
            }
        } else {
            $(this).slideUp('slow');
        }
    });
}


function setRecipeLocations() {
    $("#recipe-back-link").attr('href', $("#recipe-back-link").attr('href') + currentLocation);
    $(".rating-link a").attr('href', currentLocation);
    $("#email-recipe").attr('href', currentLocation);
}

/* SK BOOK functions */

var currentBookPage;
var totalBookPage = 7;

function loadBookPage(n) {
    if (currentBookPage == 1) $("#book-modal-back").hide();
    else $("#book-modal-back").show();
    if (currentBookPage == totalBookPage) $("#book-modal-next").hide();
    else $("#book-modal-next").show();
    var img_html = "<img src='/_res/i/tips-and-tools/book/book-page-0" + n + ".png' />";
    $("#book-modal-dynamic-content").hide();
    $("#book-modal-dynamic-content").html(img_html).ready(
        function() { $("#book-modal-dynamic-content").fadeIn(); }
    );
}

function initBookModal() {
    // variables
    // Fires where to buy Modal
    $('#learn-more-modal').dialog({ autoOpen: false, modal: true, dialogClass: 'modal-popup-auto-height png-fix',
        open: function(event, ui) {
            $(".ui-dialog-titlebar-close").show();
        } 
    })
    $('#where-buy-btn').click(function() {
        $('#learn-more-modal').dialog('open');
    });


    var $bookModal = $('#book-modal');

        // initialize modal plugin
    $bookModal.dialog({
        autoOpen: false,
        height: 577,
        width: 930,
        open: function(event, ui) {
            currentBookPage = 1;
            loadBookPage(currentBookPage);
            $(".ui-widget-overlay").css("background-color", "#000000")
            $(".ui-widget-overlay").css("opacity", ".60");
            $(".ui-dialog").addClass("large-shadow-box");
            $(".ui-dialog-titlebar-close").hide();
            $(document).bind('keydown', function(e) {
                if (e.keyCode == 37) {
                    // back
                    if (currentBookPage > 1) {
                        currentBookPage--;
                        loadBookPage(currentBookPage);
                    }
                    return false;
                }
                if (e.keyCode == 39) {
                    // next
                    if (currentBookPage < totalBookPage) {
                        currentBookPage++;
                        loadBookPage(currentBookPage);
                    }
                    return false;
                }
            });
        },
        close: function(event, ui) {
            $(document).unbind();
        },
        modal: true
    });
    $("#book-look-inside").click(function(e) {
        e.preventDefault();
        $bookModal.dialog('open');
    });

    $("#book-modal-back").click(
        function() {
            currentBookPage--;
            loadBookPage(currentBookPage);
        }
    )
    $("#book-modal-next").click(
        function() {
            currentBookPage++;
            loadBookPage(currentBookPage);
        }
    )
    $("#book-modal-close").click(
        function() {
            $bookModal.dialog('close');
        }
    )

}



$(document).ready(function() {
    initBookModal();
    changeTabsLandingPage();
    cycleTipsLandingPage();
    cycleImageTips();
    cycleImageIdeas();
    cycleImageRecipes();
    setRecipeLocations();
    // initListItems()
});
