
// Cubic easing for use with jQuery's fx functions
jQuery.extend(jQuery.easing, {
    quadInOut: function(p, n, firstNum, diff) {
        p *= 2;
        if (p < 1) return diff * 0.5 * p * p + firstNum;
        p -= 1;
        return -diff * 0.5 * (p * (p - 2) - 1) + firstNum;
    },
    cubicOut: function(p, n, firstNum, diff) {
        p -= 1;
        return diff * (p * p * p + 1) + firstNum;
    },
    cubicInOut: function(p, n, firstNum, diff) {
        p *= 2;
        if (p < 1) return diff * 0.5 * p * p * p + firstNum;
        p -= 2;
        return diff * 0.5 * (p * p * p + 2) + firstNum;
    }
});

jQuery.fn.heroChooser = function() {
    return this.each(function() {
        var el = $(this);
        var nextBtn = el.find('.next-btn');
        var prevBtn = el.find('.prev-btn');
        var pages = el.find('.page');
        var thumbs = el.find('.page a');
        var pageContainer = el.find('.page-container');
        var numPages = pages.length;
        var marker = $('#hero-selected');
        var index = 0;
        
        var selected = [0,0];
        
        if (numPages < 2) {
            nextBtn.addClass('next-btn-disabled');
        }
        
        function gotoPage(n) {
            index = n;
            
            if (n == 0) {
                prevBtn.addClass('prev-btn-disabled');
            } else {
                prevBtn.removeClass('prev-btn-disabled');
            }
            
            if (n == numPages - 1) {
                nextBtn.addClass('next-btn-disabled');
            } else {
                nextBtn.removeClass('next-btn-disabled');
            }
            
            if (selected[0] == index) {
                marker.stop(true).animate({opacity:1}, 200);
            } else {
                marker.stop(true).animate({opacity:0}, 200);
            }
            
            var targetLeft = 0 - pages.eq(n).position().left;
            pageContainer.stop(true);
            pageContainer.animate({'left': targetLeft}, 700, 'cubicInOut');
        }
        
        thumbs.each(function(i) {
            var thumb = $(this);
            thumb.click(function(e) {
                e.preventDefault();
                
                if (i == selected[1]) return;
                
                var oldPage = selected[0];
                selected = [index, i];
                
                if (oldPage != index) {
                    marker.stop(true);
                    marker.css({'left': thumb.position().left + 84 + 86});
                    marker.animate({'opacity': 1}, 200, 'cubicInOut');
                } else {
                    marker.stop(true).animate({
                        'left': thumb.position().left + 84 + 86,
                        'opacity': 1
                    }, 500, 'cubicInOut');
                }
                
                el.trigger('heroSelected', [selected[1]]);
            })
        })
        
        nextBtn.click(function(e) {
            e.preventDefault();
            
            if (index + 1 < numPages) {
                gotoPage(index + 1);
            }
        });
        
        prevBtn.click(function(e) {
            e.preventDefault();
            
            if (index - 1 >= 0) {
                gotoPage(index - 1);
            }
        });
        
        
    });
}

// similar to jQuery.fn.load but let's you abort request and only allows one request per dom element
jQuery.fn.ajaxLoad = function(url, params, callback) {
    
    if ($.isFunction(params)) {
        callback = params;
        params = null;
    }
    
    return this.each(function() {
        var el = $(this);
        
        if (el.data('request')) el.data('request').abort();
        
        el.data('request', $.get(url, params, function(data, status) {
            el.html(data);
            el.each(callback, [data, status]);
            el.removeData('request');
        }, 'html'));
    })
}

jQuery.fn.stopAjax = function() {
    return this.each(function() {
        var el = $(this);
        if (el.data('request')) {
            el.data('request').abort();
            el.removeData('request');
        } 
    });
}

jQuery.fn.zoomwin = function(options) {
    var wrapper = $('.popwindow-wrapper');
    var frame = $('.popwindow');
    var container = frame.find('.center');
    return this.each(function() {
        var el = $(this);
        el.click(function(e) {
            e.preventDefault();
            e.stopPropagation();
            var loc = el.offset();
            var size = {
                'width': el.outerWidth(),
                'height': el.outerHeight()
            }
            
            var loader = $('<div class="loader-white"></div>');
            container.empty().append(loader);
            var win = $(window);
            
            el.bind('close', function() {
                el.trigger('willClose');
                frame.unbind('click');
                frame.stop(true).animate({'opacity':0}, 200).queue(function() {
                    wrapper.css('display', 'none');
                    el.trigger('didClose');
                    $(this).dequeue();
                });
            });
            
            wrapper.css('height', Math.max($('body').outerHeight(), win.height()));
            wrapper.click(function(e) {
                // keep things in background from being clicked on
                el.trigger('close');
            });
            frame.click(function(e) {
                e.stopPropagation();
            })
            wrapper.css({'display': 'block'});
            frame.css({'opacity': 1});
            
            if (options.start && $.isFunction(options.start)) {
                options.start.apply(el.get(0));
            } else {
                frame.css({
                    'left': loc.left - Math.floor(($('body').outerWidth() - 940) * 0.5) - 20,
                    'top': loc.top - 10,
                    'width': size.width + 40,
                    'height': size.height + 40
                });
            }
            if ($.browser.msie && $.browser.version < 7) {
                loader.css({
                    width: options.width - 40,
                    height: options.height - 40
                });
                
                frame.css({
                    'width': options.width,
                    'height': options.height,
                    'left': Math.max(Math.round((940 - options.width) * 0.5), 0),
                    'top': Math.max(Math.round((win.height() - options.height) * 0.25), 0) + win.scrollTop()
                });
                
                container.ajaxLoad(el.attr('href'), function() {
                    el.trigger('loaded');
                });
            } else {
                frame.animate({
                    'width': options.width,
                    'height': options.height,
                    'left': Math.max(Math.round((940 - options.width) * 0.5), 0),
                    'top': Math.max(Math.round((win.height() - options.height) * 0.25), 0) + win.scrollTop()
                }, options.speed || 400, 'cubicOut').queue(function() {
                    // ajax load content
                    container.ajaxLoad(el.attr('href'), function() {
                        el.trigger('loaded');
                    });
                    $(this).dequeue();
                });
            }
            el.trigger('open');
        });
    });
}

jQuery.fn.pictureviewer = function() {
    var win = $('.popwindow');
    var container = win.find('.center');
    
    return this.zoomwin({'width':640, 'height':565}).each(function() {
        var el = $(this);
        
        el.bind('open', function(e) {
            var closeBtn = $('<a href="#" class="close-btn png">Close</a>');
            win.append(closeBtn);
            
            closeBtn.click(function(e) {
                e.preventDefault();
                closeBtn.remove();
                container.stopAjax().find('*:first').stop(true);
                el.trigger('close');
            });
        });
        
        el.bind('willClose', function() {
            win.find('.close-btn').remove();
            container.stopAjax().find('*:first').stop(true);
            container.find('.img img').stop(true).unbind('load');
        });
        
        el.bind('loaded', function(e) {
            container.find('.image-viewer').css({'opacity': 0}).animate({'opacity': 1}, 200);
            var imgContainer = container.find('.img');
            var navLinks = container.find('.nav a');
            var images = $([]);
            var currentImage;

            navLinks.each(function(i) {
                var img;
                if ($(this).hasClass('selected')) {
                    img = imgContainer.find('img').data('loaded', true);
                    currentImage = img;
                } else {
                    img = $('<img/>').css('visibility', 'hidden');
                    imgContainer.append(img);
                }
                $(this).data('index', i);
                images = images.add(img);
            });

            function showImage(img) {
                images.stop(true).css({
                    'opacity': 1,
                    'z-index': ''
                });
                images.not(currentImage).css({'visibility':'hidden'});
                currentImage = img;
                img.css({
                    'z-index':1,
                    'visibility':'visible',
                    'opacity':0
                }).animate({'opacity': 1}, 300);
            }

            navLinks.click(function(e) {
                e.preventDefault();
                var link = $(this);
                var currentLink = navLinks.filter('.selected');
                if (currentLink.get(0) == link.get(0)) return;

                currentLink.removeClass('selected');
                link.addClass('selected');

                var img = images.eq(link.data('index'));

                if (!currentImage.data('loaded')) {
                    currentImage.unbind('load');
                    currentImage.attr('src', '');
                    loader.remove();
                }

                if (img.data('loaded')) {
                    showImage(img);
                } else {

                    loader = $('<div class="loader-white"></div>');
                    imgContainer.append(loader);
                    loader.css({
                        'position':'absolute',
                        'left':0,
                        'top':0,
                        'opacity':0,
                        'z-index': 2
                    }).animate({'opacity':0.5}, 200);

                    img.one('load', function(e) {
                        loader.remove();
                        $(this).data('loaded', true);
                        showImage($(this));
                    }).attr('src', link.attr('href'));
                }
            });
        });
    });
}

jQuery.fn.stepper = function() {
    return this.each(function() {
        var container = $(this);
        var inputEl = container.find('input');
        var upBtn = container.find('.step-up');
        var downBtn = container.find('.step-down');
        
        inputEl.keyup(function(e) {
            var val = inputEl.val();
            if (val == '') return;
            val = parseInt(val, 10);
            val = isNaN(val) ? 0 : val;
            inputEl.val(Math.min(Math.max(0, val), 99));
        });
        
        inputEl.change(function(e) {
            var val = inputEl.val();
            val = parseInt(val, 10);
            val = isNaN(val) ? 0 : val;
            inputEl.val(Math.min(Math.max(0, val), 99));
        })
        
        upBtn.click(function(e) {
            e.preventDefault();
            var val = inputEl.val();
            val = parseInt(val, 10);
            val = isNaN(val) ? 0 : val;
            inputEl.val(Math.min(Math.max(0, val + 1), 99));
            inputEl.trigger('change');
        })
        
        downBtn.click(function(e) {
            e.preventDefault();
            var val = inputEl.val();
            val = parseInt(val, 10);
            val = isNaN(val) ? 0 : val;
            inputEl.val(Math.min(Math.max(0, val - 1), 99));
            inputEl.trigger('change');
        })
    })
}

$(function() {
    
    //
    // global.js
    //
    
    // change text only addresses to real email addresses
    $(".canned-meat").each(function() {
        var address = $(this).text().replace("-at-", "@").replace("-dot-", ".");
        $(this).attr("href", "mailto:" + address).text(address);
    })
    
    //
    // home.js
    //
    
    var VideoPlayerArea = function() {
        $(".video-frame .vid").css("display", "none");
        var vidFrames = $(".video-frame .vid");
        var currentButton;
        var currentFrame;
        var videoPlayer;
        var useFlash = false;
        var onVideo = false;
        
        if (swfobject.hasFlashPlayerVersion("9.0.115")) {
            $("<div id='flashVideoPlayer'></div>").appendTo(".video-frame");
            window.onPlayerReady = function() {
                useFlash = true;
                $(videoPlayer).css({"left":"-1000px"});
            }
            videoPlayer = swfobject.createSWF({data:"/_swf/player.swf", width:"480", height:"270"}, {allowScriptAccess:"sameDomain"}, "flashVideoPlayer");
            $(videoPlayer).css({
                "position":"absolute",
                "left":"-1000px",
                "top":"0px"
            })
        }
        

        function playFlashVideo(url) {
            try {
                videoPlayer.loadVideo(url);
                onVideo = true;
            } catch(e) {
                window.location.href = url;
            }
            
            $(videoPlayer).css({"left":"0px"});
        }

        function showVideoFrame(n) {
            if (useFlash) {
                if (onVideo) {
                    try {
                        videoPlayer.unloadVideo();
                        onVideo = false;
                    } catch (e) {}
                }
                
                $(videoPlayer).css({"left":"-1000px"});
            }
            if (currentFrame) {
                currentFrame.css("display", "none");
            }
            currentFrame = $(vidFrames[n]).css("display", "block");
        }

        $(".video-menu a").each(function (i) {
            $(this).click(function(e) {
                showVideoFrame(i);
                if (currentButton) {
                    currentButton.removeClass("selected");
                }
                currentButton = $(this).addClass("selected");
                e.preventDefault();
            })
        })

        vidFrames.each(function(i) {
            $(this).click(function(e) {
                if (useFlash) {
                    playFlashVideo($(this).attr("href"));
                    e.preventDefault();
                }
            })
        })

        $(".video-menu a").filter(":first").click();
    }
    
    VideoPlayerArea();
    
    var HeroStage = function() {
        
        var container = $('#hero-container');
        var heroes = container.find('.hero');
        var selectedHero = heroes.eq(0);
        var lastHero;
        
        $('#hero-chooser').heroChooser().bind('heroSelected', function(e, n) {
            
            if (selectedHero.get(0) == heroes.eq(n).get(0)) return;
            heroes.not(selectedHero).css('display', 'none');
            selectedHero.stop(true).css({
                'z-index': '',
                'opacity': 1,
                'display': 'block'
            });
            selectedHero = heroes.eq(n);
            selectedHero.css({
                'z-index': 1, 
                'display': 'block',
                'opacity': 0
            }).animate({'opacity': 1}, 600, 'quadInOut');
            
        })
    }
    
    HeroStage();
    
    $('.ibend-thumb').pictureviewer().bind('open', function() {
        $('.video-menu a.selected').click();
    });
    
    
    //
    // store.js
    //
    
    $('.item-preview a').pictureviewer();
    $('.item-quantity').stepper();
    $('#promo-code-btn').click(function(e) {
        e.preventDefault();
        $('#order_form').submit();
    })
    
    // shipping address show and hide
    function showShipping() {
        if ($.browser.msie && $.browser.version <= 7) {
            $('#shipping_form').css('display', 'block');
            $('body').css('display', 'none');
            $('body').css('display', 'block');
        } else {
            $('#shipping_form').slideDown("normal");
        }
        
    }
    
    function hideShipping() {
        if ($.browser.msie && $.browser.version <= 7) {
            $('#shipping_form').css('display', 'none');
            $('body').css('display', 'none');
            $('body').css('display', 'block');
        } else {
            $('#shipping_form').slideUp("normal");
        }
    }
    
    function showHideShipping(e) {
        if ($('.shipping-address-btn-group input').attr('checked')) {
            showShipping();
        } else {
            hideShipping();
        }
        
        PriceCalculator.calculateTotal();
    }
    
    $('.shipping-address-btn-group input').click(showHideShipping);
    if($('.shipping-address-btn-group input:checked').length > 0) {
        $('#shipping_form').css('display', 'block');
    }
    
    // calculates the price based on quantity tax and shipping
    var PriceCalculator = {
        init: function() {
            
            var req = PriceCalculator.calculateTotal;
            
            $('.item-quantity input').change(req).keyup(req);
            $('#shipping_state_field').change(req);
            $('#billing_state_field').change(req);
            $('#shipping_country_field').change(req);
            $('#billing_country_field').change(req);
            
            this.calculateTotal();
            
        },
        calculateTotal: function() {
            PriceCalculator.getStateAndCountry();
            PriceCalculator.setValues();
        },
        setValues: function() {
            
            var totalQuantity = 0;
            var subtotal = 0;
            var cookie = [];
            
            $('.store-item').each(function() {
                var item = $(this);
                var itemPriceEl = item.find('.item-price');
                var itemTotalEl = item.find('.item-total');
                
                var itemPrice = parseFloat(itemPriceEl.text().slice(1));
                itemPrice = isNaN(itemPrice) ? 0 : itemPrice;
                itemPrice = Math.round(itemPrice * 100) * 0.01;
                
                var quantityField = item.find('.item-quantity input');
                
                var q = parseInt(quantityField.val(), 10);
                q = isNaN(q) ? 0 : q;
                
                // update cookie for prepopulating later
                if (q > 0) {
                    cookie.push({
                        'name': quantityField.attr('name'),
                        'value': q
                    });
                }
                
                subtotal += q * itemPrice;
                totalQuantity += q;
                
                itemTotalEl.text(PriceCalculator.toPrice(q * itemPrice));
            });
            
            // create cookie
            document.cookie = 'cart=' + encodeURIComponent($.param(cookie)) + ';path=/';
            
            if (totalQuantity > 0) {
                
                $(".subtotal-value").text(this.toPrice(subtotal)).removeClass("empty");
                
                var shipping = this.getShipping(totalQuantity);
                $(".shipping-value").text(this.toPrice(shipping)).removeClass("empty");
                
                var tax = this.getTax() * subtotal;
                var total = subtotal + tax + shipping;
                
                if (tax > 0) {
                    $(".tax-value").text(this.toPrice(tax)).removeClass("empty");
                } else {
                    $(".tax-value").html("&mdash;").addClass("empty");
                }
                
                $(".total-value").text(this.toPrice(total)).removeClass("empty");
                
            } else {
                $(".tax-value").html("&mdash;").addClass("empty");
                $(".shipping-value").html("&mdash;").addClass("empty");
                $(".subtotal-value").html("&mdash;").addClass("empty");
                $(".total-value").html("&mdash;").addClass("empty");
            }
        },
        getTax: function() {
            if (this.state.toLowerCase() == "ca" && this.country.toLowerCase() == "us") {
                return 0.095;
            } else {
                return 0;
            }
        },
        getShipping: function(q) {
            
            var countryField = $("#shipping_address_specified").attr("checked") ? $("#shipping_country_field").val() : $("#billing_country_field").val();
            
            if (countryField != "US" && countryField != "PR" && countryField != "GU") {
                if (q < 4) {
                    return 2.5;
                } else {
                    return 5;
                }
            } else {
                if (q < 4) {
                    return 1;
                } else if (q < 10) {
                    return 2;
                } else {
                    return 0;
                }
            }
        },
        getStateAndCountry: function() {
            var countryField = $("#shipping_address_specified").attr("checked") ? $("#shipping_country_field") : $("#billing_country_field");
            var stateField = $("#shipping_address_specified").attr("checked") ? $("#shipping_state_field") : $("#billing_state_field");
            PriceCalculator.state = stateField.val() || "";
            PriceCalculator.country = countryField.val() || "";

            $(".subtotal-value").html("&mdash;").addClass("empty");
            $(".tax-value").html("&mdash;").addClass("empty");
            $(".shipping-value").html("&mdash;").addClass("empty");
            $(".total-value").html("&mdash;").addClass("empty");
        },
        toPrice: function(n) {
            var dollars = Math.floor(n);
            var cents = Math.round((n - dollars) * 100);
            if (cents == 100) {
                dollars++;
                cents = 0;
            }
            
            cents = cents.toString();
            
            var dollars = dollars.toString();
            var dollarsWithCommas = '';
            var i = dollars.length;
            while (i) {
                if (i - 3 > 0) {
                    dollarsWithCommas = "," + dollars.slice(i - 3, i) + dollarsWithCommas;
                    i -= 3;
                } else {
                    dollarsWithCommas = dollars.slice(0, i) + dollarsWithCommas;
                    i = 0;
                }
            }
            
            cents = cents.length < 2 ? "0" + cents : cents;

            return "$" + dollarsWithCommas + "." + cents;
        }
    }
    
    if ($('#order_form').length > 0) PriceCalculator.init();
    
})