/// <reference path="jquery-1.3.2-vsdoc.js" />

$(document).ready(function() {

    Cufon.set('fontFamily', 'Archer Bold').replace('.archerbold');
    Cufon.set('fontFamily', 'Archer Medium').replace('.archermedium');
    Cufon.set('fontFamily', 'Archer Semibold').replace('.archersemibolditalic');
    Cufon.set('fontFamily', 'Archer Bold').replace('.archermedium strong');
    Cufon.set('fontFamily', 'Archer Bold').replace('.searchResults #tabs li a');
    Cufon.now();



    $('.aboutFaqContent a.answer').bind('click', function(e) {
        if ($(this).text().indexOf('Ver') > -1) {
            $(this).html('&gt;&gt; Ocultar respuesta');
        }

        else {
            $(this).html('&gt;&gt; Ver respuesta');

        }
        $(this).next().slideToggle();


        $(this).next()
        // return false;
        e.preventDefault();

    });

    // add space above the first footnote listed within the recipe detail directions ordered-list.
    $('ol.directions li.heading:first').css("margin-top", "1.0em");


    // hover effect for search results
    if ($("#my-recipes.search-results").length) {
        $("#my-recipes.search-results div.recipe").hover(function() {
            $(this).addClass("hover");
        }, function() {
            $(this).removeClass("hover");
        });
    }




    // if the slideshow exists run the code
    // needs to be gone through for optimizations
    if ($("#slideshow").length) {

        var Slideshow = function() {
            var defaultTab = "cookbook";
            var currentTab = defaultTab;
            var slideShow = $("#slideshow");
            var tabs = slideShow.find("ul.tabs");
            var tabView = slideShow.find("div.tab-view");
            var overlay = tabView.find("div.overlay");
            var currentSlide = undefined;
            var slideQueue = undefined;
            // var tabsBuilt = false;
            var timer = undefined;
            var tabTimer = undefined;
            var tabNames = ["cookbook", "choosy", "new"];
            var tabName = defaultTab;


            // overide the default value set in the markup
            var setDefault = function(def) {
                updateTabs(def);
            };

            // update the tabs look
            var updateTabs = function(tab) {
                if (!slideShow.hasClass(tab)) {
                    slideShow.removeClass();
                    slideShow.addClass(tab)
                    // if( !tabsBuilt ) {
                    updateTabView(tab);
                    // tabsBuilt = true;
                    // } else {
                    // tabsBuilt = false;
                    // }
                }
            };

            // build out the dots depending on how many slides there are
            var buildDots = function() {
                // faster but can't bind functions
                /*
                var tempDots = "<li class='left'></li>";
                $( "<li class='left'></li>" ).appendTo( dotParent );
                for( var i = 0; i < dotList.length ; i++ ) {
                //tempDots += "<li class='dot dot" + i + "'></li>";
                }
                tempDots += "<li class='right'></li>";
                dotParent.html( tempDots );
                */
                // console.log( currentTab );
                var dots = currentTab.find("div.dots ul");
                if (!dots.find("li").length) {
                    // console.log( "buildDots" );
                    dots.parent().css("display", "block");
                    // delete any old dot nav from old tab views
                    destroyDots(dots.find("ul"));
                    // create the left dot
                    // $( "<li class='left'></li>" ).appendTo( dots );				
                    // create all the slides dots
                    for (var i = 0; i < slideQueue.length; i++) {
                        var dot = $("<li class='dot-" + i + "'></li>");
                        setDotEvents(dot);
                        dot.appendTo(dots);
                    }
                    dots.find("li[ class*='dot' ]").first().addClass("light");
                    // create the right dot
                    // $( "<li class='right'></li>" ).appendTo( dots );
                }
            };

            // destroy any old dot navigation in this slide
            var destroyDots = function(dots) {
                dots.html("");
            };



            // bind a click event to all the paging dots
            var setDotEvents = function(dot) {
                dot.bind("click", function(e) {
                    // console.log( $( this ).attr( "class" ).replace( "dot-" , "" ) );
                    window.clearInterval(timer);
                    window.clearInterval(tabTimer);

                    if (currentSlide != parseInt($(this).attr("class").replace("dot-", ""))) {
                        dot.parent().children().removeClass("light");
                        dot.addClass("light");
                        currentSlide = parseInt($(this).attr("class").replace("dot-", ""));
                        updateListView();
                    }
                });
            };

            // bind a click event to all tabs			
            var setTabEvents = function(tabs) {
                // bind events to the tabs
                tabs.find("li").bind("mouseup", function(e) {
                    // make a switch statement and throw an error
                    window.clearInterval(tabTimer);
                    if ($(this).hasClass("cookbook")) {
                        updateTabs("cookbook");
                    } else if ($(this).hasClass("choosy")) {
                        updateTabs("choosy");
                    } else if ($(this).hasClass("new")) {
                        updateTabs("new");
                    } else {
//                        console.log("the tab doesn't exist");
                    }
                });
            };


            var resetDots = function() {
                var tempSlide = $(slideQueue[currentSlide]);
                var tempDots = tempSlide.parent().parent().find("div.dots ul");
                // console.log( tempDots );			        
                tempDots.find("li").removeClass("light");
                tempDots.find("li:eq(" + currentSlide + ")").addClass("light");
            };


            // make the slides update once a tab is clicked
            var updateTabView = function(slide) {
                // console.log( "updateTabView" );
                currentTab = tabView.find("div." + slide);
                var listView = currentTab.find("ul.list-view");
                window.clearInterval(timer);

                // tabView.find( "div.slide" ).css( "display", "none" );
                if (listView.length) {
                    slideQueue = listView.find("li");
                    buildDots(slide);
                    currentSlide = 0;
                    timer = window.setInterval(timerUpdate, 7000);

                    resetDots();
                }
                // console.log( currentSlide );
                // currentTab.css( "display" , "block" );
            };


            var updateListView = function() {
                overlay.fadeIn(500, function(e) {
                    resetDots();
                    slideQueue.css("display", "none");
                    slideQueue[currentSlide].style.display = "block";
                    overlay.fadeOut(500);
                })
                // slideQueue.css( "display" , "none" );
                // console.log( slideQueue );
                // console.log( currentSlide );
                // slideQueue[ currentSlide ].style.display = "block";			
            };


            var timerUpdate = function() {
                // console.log( "timerUpdate" );
                // console.log( currentSlide );
                // console.log( slideQueue.length );
                if (currentSlide < slideQueue.length - 1) {
                    currentSlide++;
                    updateListView();
                } else {
                    currentSlide = 0;
                    updateListView();
                }
            };


            var tabTimer = function() {
                // console.log( "tabTimer" );
                if (tabName == "cookbook") {
                    tabName = "choosy";
                    updateTabs(tabName);
                } else if (tabName == "choosy") {
                    tabName = "new";
                    updateTabs("new");
                } else if (tabName == "new") {
                    tabName = "cookbook";
                    updateTabs(tabName);
                }
            };


            // public functions
            // return {}


            // initalize the slideshow
            var init = function() {
                setDefault(defaultTab);
                setTabEvents(tabs);
                tabTimer = window.setInterval(tabTimer, 7000);
            } ();
        } ();

    }






    // if the scroller exists run the code
    if ($("#scroller").length) {

        var Scroller = function() {
            var scroll = $("#scroller");
            var prvBtn = scroll.find("img.prv-scroll");
            var nxtBtn = scroll.find("img.nxt-scroll");
            var scrollView = scroll.find("div.scroller-view");
            var pGroup = scrollView.find("div.parent-group");
            var groups = pGroup.find("div.content-group");
            var animating = false;
            var scrollWidth = scrollView.width();
            var pGroupWidth = undefined;
            var groupsLen = groups.length;
            var groupWidth = groups.first().outerWidth(true);


            var moveLeft = function() {
                // console.log( pGroup.width() - 885 );
                // console.log( parseInt( pGroup.css( "left" ) ) );
                // console.log( scrollWidth );
                // console.log( pGroupWidth );
                // console.log( groupWidth );
                if (parseInt(pGroup.css("left")) <= ((pGroupWidth - scrollWidth) * -1)) {
                    // foo					
                } else {
                    pGroup.animate({ "left": "-=" + groupWidth + "px" }, "slow", function() { /*console.log( parseInt( pGroup.css( "left" ) ) );*/animating = false; });
                    animating = true;
                }
            };

            var moveRight = function() {
                // console.log( "right" );
                if (parseInt(pGroup.css("left")) >= 0) {
                    // foo
                } else {
                    pGroup.animate({ "left": "+=" + groupWidth + "px" }, "slow", function() { animating = false; });
                    animating = true;
                }
            };

            var setBtnEvents = function() {
                // console.log( groups.length );
                if (groups.length > 3) {
                    prvBtn.bind("click", function(e) {
                        if (!animating) {
                            moveRight();
                        }
                    });

                    nxtBtn.bind("click", function(e) {
                        if (!animating) {
                            moveLeft();
                        }
                    });
                } else {
                    prvBtn.css("display", "none");
                    nxtBtn.css("display", "none");
                }
            };

            var setParentWidth = function() {
                // make width more dynamic ** done **
                // this is all needed for stupid IE caue i can't use right
                // console.log( groups.first().outerWidth( true ) );
                pWidth = groups.first().outerWidth(true) * groups.length;
                // var pWidth = 295 * groups.length;
                // pGroup.css( "width" , pWidth + "px" );
                pGroup.width(pWidth);
                pGroupWidth = pWidth;
            }

            // public functions
            // return {}

            var init = function() {
                setBtnEvents();
                setParentWidth();
            } ();
        } ();

    }

    $('.jifCarousel .leftArrow').bind('mousedown', function(e) {
        if ($(this).hasClass('active')) {
            continueAnimationLeft($(this), '+=27');
        }
    });

    $('.jifCarousel .rightArrow').bind('mousedown', function(e) {
        if ($(this).hasClass('active')) {
            continueAnimationRight($(this), '-=27');
        }
    });


    $('.jifCarousel .rightArrow, .jifCarousel .leftArrow').bind('mouseup mouseleave', function() {


        $('.carouselContent').stop(true);
    });



    $('.poll').submit(function(event) {
        var form = $(this);
        $.post('/polls/vote', form.serialize(), function(data) {
            var results = form.siblings('ul.poll-results');
            results.empty();
            var answers = data.Answers;
            for (var i = 0; i < answers.length; i++) {
                var answer = answers[i];
                results.append('<li>' + answer.AnswerText + ' - ' + answer.VoteCount + '</li>');
            }
        });
        return false;
    });

    $('#pack-it-tips li:even').addClass('gray');
    $('#pack-it-tips li:odd').addClass('white');
    $('#dip-it-tips li:even').addClass('gray');
    $('#dip-it-tips li:odd').addClass('white');
    $('#go-tips li:even').addClass('gray');
    $('#go-tips li:odd').addClass('white');

    //For the Prodcuts Jif To Go Page// 

    $("#jiftogoTabs ul.tabs li").click(function() {
        $('div.slide').css('display', 'none');
        var tabid = $(this).attr('id');
        $('#jiftogoTabs').attr('class', tabid);
        $('div.' + tabid).css('display', 'block');

    });

    $(".results_btn_pack, .vote_btn_pack").click(function() {
        $("div#pack_poll").css("display", "none");

    });
    $(".results_btn_dip, .vote_btn_dip").click(function() {
        $("div#dip_poll").css("display", "none");

    });
    $(".results_btn_go, .vote_btn_go").click(function() {
        $("div#go_poll").css("display", "none");

    });


    // end Jif To Go tabs //

});


var width = 953;
function continueAnimationLeft(obj, amount) {
    $('.carouselContent').animate({ left: amount }, 200, 'linear', function() {
        obj.siblings().addClass('active');
        var elemPos = parseInt($(this).css('left').replace('px', ''));
        if ((elemPos + width) >  width) {
            obj.removeClass('active');
            $('.carouselContent').stop(true);
            return;
        }
        continueAnimationLeft(obj, amount)
    });
}

function continueAnimationRight(obj, amount) {
    $('.carouselContent').animate({ left: amount }, 200, 'linear', function() {
        obj.siblings().addClass('active');
        var elemPos = parseInt($(this).css('left').replace('px', ''));
        
        if ((elemPos + width) < 0) {
            obj.removeClass('active');
            $('.carouselContent').stop(true);
            return;
        }
        continueAnimationRight(obj, amount)
    });
}

function openRecipe(recipeName) {
    recipePopup = window.open('/recipePopups/' + recipeName + '.html', 'recipePopup', 'width=573,height=679,scrollbars=no,resizable=yes,toolbar=no,directories=no,location=no,menubar=no,status=no,left=200,top=200');
    if (window.focus) { recipePopup.focus() }
}

MyCookbook = {}

MyCookbook.Main = function(config) {
    this.config = config
    this.init()
}

MyCookbook.Main.prototype = {
    init: function() {
        this.page = this.config.page != null ? this.config.page : ""
        if (this.page != "") {
            switch (this.page) {
                case "create":
                    new MyCookbook.Create({})
                    break;
                case "share":
                    new MyCookbook.Share({})
                    break;
                default:
                    //code to be executed if n is different from case 1 and 2
            }
        }
    }
}

MyCookbook.Create = function(config) {
    this.config = config
    this.init()
}

MyCookbook.Create.prototype = {
    init: function() {
        this.form = $('#createCookbookForm')
        this.fieldsets = $('fieldset', $('#createCookbookForm'))
        this.designUl = $('ul', $('#designs'))
        this.designs = $('img', $('li#designs'))
        this.designRadios = $('input', $('li#designs'))
        this.filter = $('#addRecipeFilter')
        this.mjRecipes = $('li.mj', $('#selectRecipe'))
        this.scRecipes = $('li.sc', $('#selectRecipe'))
        this.step2Controls = $('a', $('#step2Controls'))
        this.previewPop = $('#preview-popup')
        this.controls = '<div class="moveRecipe">' +
                        '<a class="up" href="">^</a>' +
                        '<span></span>' +
                        '<a class="down" href="">v</a>' +
                        '</div>'


        this.bMoveRecipe = $.proxy(this.moveRecipe, this);
        this.bRecipeAdded = $.proxy(this.recipeAdded, this);
        this.bRecipeRemoved = $.proxy(this.recipeRemoved, this);
        this.bAddRecipe = $.proxy(this.addRecipe, this);
        this.bRemoveRecipe = $.proxy(this.removeRecipe, this);
        this.bSelectDesign = $.proxy(this.selectDesign, this);
        this.bShowDesignPreview = $.proxy(this.showDesignPreview, this);

        this.v = $("#createCookbookForm").validate({
            errorClass: "input-validation-error",
            errorElement: "div",
            errorPlacement: function(error, element) {
                if (element.attr('id') == "Radio1") {
                    element.parent("li").parent("ul").parent("li").children('p').after(error);
                } else {
                    error.appendTo(element.next())
                }
            },
            onkeyup: false,
            onblur: false
        });

        this.attachEvents()
    },

    attachEvents: function() {
        $(document).bind('moverecipe:event', this.bMoveRecipe);
        $(document).bind('recipeadded:event', this.bRecipeAdded);
        $(document).bind('reciperemoved:event', this.bRecipeRemoved);

        $('a', $('.moveRecipe')).live('click', $.proxy(function(el) {
            $(document).trigger({ type: 'moverecipe:event', element: $(el.currentTarget) })
            return false
        }, this))

        $('span.blue', $('#toRecipes')).bind('click', $.proxy(function() {
            if (this.v.form()) {
                $(this.fieldsets[0]).hide()
                $(this.fieldsets[1]).show()
            } else {
                $('html, body').animate({ scrollTop: $("#step1").offset().top }, 1000);
            }

        }, this))

        $('li.recipe', $('#recipeSelection')).live('click', $.proxy(function(e) {

            parentId = $(e.currentTarget).parent('ul').attr('id')

            selectLength = $('li.selected', $('#selectRecipe')).length
            selectedLength = $('li', $('#selectedRecipes')).length

            if (parentId == 'selectRecipe') {
                if ((selectLength + selectedLength) < 15) {
                    $(e.currentTarget).toggleClass('selected')
                } else {
                    if ($(e.currentTarget).hasClass('selected')) {
                        $(e.currentTarget).removeClass('selected')
                    } else {
                        alert("Ya has elegido 15 recetas. Desmarca o quita alguna")
                    }
                }
            } else {
                $(e.currentTarget).toggleClass('selected')
            }
        }, this))

        $('a', $('#recipeSelectControls')).each($.proxy(function(c, el) {
            $(el).bind('click', $.proxy(function() {
                if ($(el).attr('id') == 'add') {
                    this.bAddRecipe()
                } else {
                    this.bRemoveRecipe()
                }
                return false
            }, this))
        }, this))

        $(this.designs).each($.proxy(function(c, el) {
            $(el).bind('click', $.proxy(function() {
                this.bSelectDesign(el)
            }, this))
        }, this))
        $(this.filter).bind('change', $.proxy(function() {
            if ($(this.filter).val() == 'all') {
                $('li', $('#selectRecipe')).addClass('show')
            } else {
                $('li', $('#selectRecipe')).removeClass('show')
                $('li.' + $(this.filter).val(), $('#selectRecipe')).addClass('show')
            }
        }, this))

        $('#createCookbookForm').bind('submit', $.proxy(function() {
            $('input[name="CookbookRecipes"]', $('#recipeSelection')).val('')
            stringRecipes = ''

            arrayLI = $('li', $('#selectedRecipes'))

            $(arrayLI).each($.proxy(function(c, el) {
                stringRecipes += $(el).attr('ref')
                if (arrayLI.length != (c + 1)) {
                    stringRecipes += ','
                }
            }, this))


            $('input[name="CookbookRecipes"]', $('#recipeSelection')).val(stringRecipes)

            if (arrayLI.length < 5) {
                alert('Selecciona entre 5 y 15 recetas.')
                return false
            }

        }, this))

        $(this.step2Controls[0]).bind('click', $.proxy(function() {
            $(this.fieldsets[1]).hide()
            $(this.fieldsets[0]).show()
            return false
        }, this))

        $('#generateCB').bind('click', $.proxy(function() {

            $('input[name="CookbookRecipes"]', $('#recipeSelection')).val('')

            stringRecipes = ''

            arrayLI = $('li', $('#selectedRecipes'))

            $(arrayLI).each($.proxy(function(c, el) {
                stringRecipes += $(el).attr('ref')
                if (arrayLI.length != (c + 1)) {
                    stringRecipes += ','
                }
            }, this))


            $('input[name="CookbookRecipes"]', $('#recipeSelection')).val(stringRecipes)

            return false
        }, this))

        $('#previewCookbook').bind('click', $.proxy(function() {
            stringRecipes = ''

            arrayLI = $('li', $('#selectedRecipes'))

            $(arrayLI).each($.proxy(function(c, el) {
                stringRecipes += $(el).attr('ref')
                if (arrayLI.length != (c + 1)) {
                    stringRecipes += ','
                }
            }, this))


            $('input[name="CookbookRecipes"]', $('#recipeSelection')).val(stringRecipes)

            $.ajax({
                url: "/MyJif/PreviewCookbook",
                data: decodeURIComponent($("#createCookbookForm").serialize()),
                type: "POST",
                success: function(data) {
                    if (data != '') {
                        window.open(data)
                    }
                },
                fail: function() {
                    //fail message
                }

            })
            return false
        }, this))

        $('a', $(this.designUl)).bind('click', $.proxy(function(event) {
            this.bShowDesignPreview(event.currentTarget)
            return false
        }, this))

        $('a.close', this.previewPop).bind('click', $.proxy(function() {
            $(this.previewPop).hide()
            return false
        }, this))

    },
    addRecipe: function() {
        liArray = $('li.selected', $('#selectRecipe'))
        $(liArray).each($.proxy(function(c, el) {
            $(el).addClass('chosen').removeClass('selected').clone().append(this.controls).appendTo('#selectedRecipes')
        }, this))
        if (liArray.length > 0) {
            $(document).trigger({ type: 'recipeadded:event' })
        }
    },
    removeRecipe: function() {
        liArray = $('li.selected', $('#selectedRecipes'))
        $(liArray).each($.proxy(function(c, el) {
            $('li[ref="' + $(el).attr('ref') + '"]', $('#selectRecipe')).removeClass('chosen')
            $(el).remove()
        }, this))
        if (liArray.length > 0) {
            $(document).trigger({ type: 'reciperemoved:event' })
        }
    },
    moveRecipe: function(event) {
        action = $(event.element).hasClass('up') ? 'up' : 'down'
        element = $(event.element).parent('div').parent('li')

        if (!($(element).hasClass('last') && $(element).hasClass('first'))) {
            if (action == 'up') {

                if ($(element).prev().hasClass('first')) {

                    if ($(element).hasClass('last')) {

                        $(element).removeClass('last').prev().addClass('last')
                        $(element).addClass('first').prev().removeClass('first')
                    }
                    $(element).addClass('first').prev().removeClass('first')

                    $(element).insertBefore($(element).prev())
                } else if ($(element).hasClass('last')) {
                    $(element).removeClass('last').prev().addClass('last')
                    $(element).insertBefore($(element).prev())
                } else if ($(element).prev().length != 0) {
                    $(element).insertBefore($(element).prev())
                }

            } else {

                if ($(element).next().hasClass('last')) {
                    if ($(element).hasClass('first')) {
                        $(element).removeClass('first').next().addClass('first')
                    }
                    $(element).addClass('last').next().removeClass('last')
                    $(element).insertAfter($(element).next())
                } else if ($(element).hasClass('first')) {
                    $(element).removeClass('first').next().addClass('first')
                    $(element).insertAfter($(element).next())
                } else if ($(element).next().length != 0) {

                    $(element).insertAfter($(element).next())
                }

            }
        }

    },
    recipeAdded: function() {

        liArray = $('li', $('#selectedRecipes'))

        $(liArray).each(function() {
            $(this).removeClass('first')
            $(this).removeClass('last')
        })
        if (!$(liArray[0]).hasClass('first')) {
            $(liArray[0]).addClass('first')
        }

        if (!$(liArray[liArray.length - 1]).hasClass('last')) {
            $(liArray[liArray.length - 1]).addClass('last')
        }

    },
    recipeRemoved: function() {
        liArray = $('li', $('#selectedRecipes'))
        if (!$(liArray[0]).hasClass('first')) {
            $(liArray[0]).addClass('first')
        }
        $(liArray).each(function() {
            $(this).removeClass('last')
        })
        if (!$(liArray[liArray.length - 1]).hasClass('last')) {
            $(liArray[liArray.length - 1]).addClass('last')
        }
    },
    selectDesign: function(element) {
        $(this.designs).each(function(el) {
            $(this).removeClass('selected')
        })

        $(this.designRadios).each(function() {
            $(this).attr("checked", false);
        })
        $(element).addClass('selected')
        $(element).prev().attr("checked", true);
    },
    showDesignPreview: function(element) {
        preview = {}

        preview.title = $(element).parent().siblings('p').html()
        preview.cover = $(element).parent().siblings('img').attr('src').replace('Sm', 'Lg')
        preview.recipe = preview.cover.substr(0, preview.cover.indexOf(".jpg")) + "Recipe" + preview.cover.substr(preview.cover.indexOf(".jpg"))

        previewHtml = '<li><img src="' + preview.cover + '"/></li>' +
        '<li><img src="' + preview.recipe + '"/></li>'

        $('h4', this.previewPop).html(preview.title)
        $('ul', this.previewPop).html(previewHtml)
        this.runImgTest()

    },
    runImgTest: function() {

        testImageSourceId = 0;
        testImageSourceId = setInterval($.proxy(this.testImageSource, this), 500);

    },
    testImageSource: function() {
        if ($('li', this.previewPop).children('img').attr('src') != null) {
            clearInterval(testImageSourceId);
            this.previewPop.center()
            this.previewPop.show()
        }
    }
}

MyCookbook.Share = function(config) {
    this.config = config
    this.init()
}

MyCookbook.Share.prototype = {
    init: function() {
        this.attachEvents()
    },

    attachEvents: function() {
        $('#shareYourCookbookForm').validate({
            errorClass: "input-validation-error",
            errorElement: "div"
        })
    }

}




jQuery.fn.center = function() {
    this.css("position", "absolute");
    this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
    this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
    return this;
}
