﻿$(document).ready(function() {
    $("img.fading").hover(
      function() {
        $(this).stop().animate({ "opacity": "0" }, "fast");
      },
      function() {
        $(this).stop().animate({ "opacity": "1" }, "fast");
      }
    );

    $(".mainMenuItem").hover(
      function() { $('img', this).replaceOnAttribute("src", "Off", "On") },
      function() { $('img', this).replaceOnAttribute("src", "On", "Off") }
    );

    $("#search-query").focus(
      function() { $("#storeSearchBubble").replaceOnAttribute("src", "Default", "Secondary") }
    );

    $("#search-query").blur(
      function() { $("#storeSearchBubble").replaceOnAttribute("src", "Secondary", "Default") }
    );
    
});

jQuery.fn.replaceOnAttribute = function(name, str, replacement) {
    this.each(function() {
        $(this).attr(name, $(this).attr(name).replace(str, replacement))
    });
}

function htmlEscape(value) {
    if (value == null) return "";
    return $("<div />").text(value).html();
}

function setCookie(name, value) {
    if (value != null) {
        var date = new Date();
        date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
        document.cookie = name + "=" + encodeURIComponent(value) + "; path=/ ; expires=" + date.toUTCString();
    } else {
        document.cookie = name + '=; path=/ ; expires=Thu, 01-Jan-70 00:00:01 GMT;';
    }
}

$.fn.carousel = function() {
    return this.each(function() {
        var $wrapper = $('> .wrapper', this).css('overflow', 'hidden');
        var $items = $wrapper.find('> ul > li');
        var $single = $items.filter(':first');
        
        var singleWidth = $single.outerWidth();
        var visible = Math.ceil($wrapper.innerWidth() / singleWidth);
        var currentIndex = 0;
        var lastValidIndex = $items.length - visible;
        var scrolling = false;

        $(this).attr('data-item-count', $items.length);

        $wrapper.scrollLeft(0);

        function move(dx) {
            var newIndex = Math.max(0, Math.min(lastValidIndex, currentIndex + dx));
            if (!scrolling && newIndex != currentIndex) {
                scrolling = true;

                dx = newIndex - currentIndex;
                var scrollAmount = dx * singleWidth;

                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft: '+=' + scrollAmount
                }, 300, 'swing', function() {
                    currentIndex = newIndex;

                    var canMoveBack = newIndex > 0;
                    var canMoveForward = newIndex < lastValidIndex;

                    scrolling = false;

                    $(this).trigger('scrollEnded', [newIndex, canMoveBack, canMoveForward]);
                });
            }
        };

        $(this).bind('move', function(event, count) {
            move(count);
        });
    });
};

