function rand(m,M){return M?m+rand(M-m):Math.random()*++m<<.5}
function preloadImage(img){ pic = new Image(100,100); pic.src=img; }
$(document).ready(function() {

    var scrollElem = scrollableElement('html', 'body');

    $('#accordion dt h2').click(function(e){
        e.preventDefault();
        var $h2 = $(this);
        if( $h2.parent().next().is(':hidden') ) {
            $('#accordion dd').slideUp();
            $('#accordion dt h2').removeClass("active");
            $h2.addClass("active").parent().next().slideDown(600,function(){
                $(scrollElem).animate({scrollTop: $h2.offset().top}, 300);
            }).removeClass("hidden");
            return false;
        }
    });
    $("#fcart .open-cart").click(function(e){ e.preventDefault(); $("#fcart").toggleClass("open"); });

    $("#recommend .slider").jCarouselLite({
        btnNext: "#recommendNext", btnPrev: "#recommendPrev",
        visible: 4, auto:4000, speed:1500, scroll:1, start: rand(0,$("#recommend .slider li").length)
    });
    $("#recommend .slider li").hover( function(){ stopAutoScroll = true; }, function(){ stopAutoScroll = false; } );

    /* == POPUP == */
    var closeBtn = $("#item-popup-close");
    var nextBtn = $("#item-popup-next");
    var prevBtn = $("#item-popup-prev");

    nextBtn.click(function(){
        el = $(".item-popup:visible");
        if(el){ $('#item-popup-shadow').unbind('click'); el.hide().next(".item-popup").togglePopup(); }
    });
    prevBtn.click(function(){
        el = $(".item-popup:visible");
        if(el){ $('#item-popup-shadow').unbind('click'); el.hide().prev(".item-popup").togglePopup(); }
    });

    $("#items .item, .slider li").each(function(e){
        el = $(this);
        var popup = $("#"+el.attr("popup"));
        $(".show-popup",el).click(function(e){ e.preventDefault(); popup.togglePopup(); });
        $(".item-popup-close",popup).click(function(e){ e.preventDefault(); popup.togglePopup(); });

        $(".thumbs a",popup).click(function(e){
            e.preventDefault(); $(".large",popup).css("backgroundImage","url("+$(this).attr("href")+")")
        });
    });

    // link in cart
    $(".popup_link").each(function(e){
        el = $(this);
        //alert(el.attr("popup"));
        var popup = $("#"+el.attr("popup"));
        el.click(function(e){ e.preventDefault(); popup.togglePopup(); });
        $(".item-popup-close",popup).click(function(e){ e.preventDefault(); popup.togglePopup(); });
         $(".thumbs a",popup).click(function(e){
            e.preventDefault(); $(".large",popup).css("backgroundImage","url("+$(this).attr("href")+")")
        });
    });


    $.fn.togglePopup = function(){
        var popup = $(this);
        //detect whether popup is visible or not
        if(!popup.is(':visible')) { //hidden - then display
            $('#item-popup-shadow').height($(document).height()).show().click(function(){popup.togglePopup();});

            var ml = -popup.width()/2;
            var mt = -popup.height()/2;
            popup.css({'margin-left': ml + 'px', 'margin-top': mt + 'px'}).show();

            closeBtn.css({'margin-top': (mt-15) + 'px'}).show().unbind('click').click(function(){popup.togglePopup();});
            if(popup.next(".item-popup").length > 0){ nextBtn.show(); } else { nextBtn.hide(); }
            if(popup.prev(".item-popup").length > 0){ prevBtn.show(); } else { prevBtn.hide(); }

            $(".img img",popup).each(function(e,i){
                $(this).css("backgroundImage","url("+$(this).attr("image")+")");
            })
            $(".thumbs a",popup).each(function(e,i){ preloadImage($(this).attr("href")); })
        } else { //visible - then hide
            $('#item-popup-shadow').hide().removeAttr('style').unbind('click');
            popup.hide();
            closeBtn.unbind('click').hide();
            nextBtn.hide();
            prevBtn.hide();
        }
    };


    // use the first element that is "scrollable"
    function scrollableElement(els) {
        for (var i = 0, argLength = arguments.length; i <argLength; i++) {
          var el = arguments[i],
              $scrollElement = $(el);
          if ($scrollElement.scrollTop()> 0) {
            return el;
          } else {
            $scrollElement.scrollTop(1);
            var isScrollable = $scrollElement.scrollTop()> 0;
            $scrollElement.scrollTop(0);
            if (isScrollable) {
              return el;
            }
          }
        }
        return [];
    }
});

