var popupStatus = 0;

function loadPopup() {
    if(popupStatus==0) {
        $("#popupbg").css("opacity","0.0");
        $("#popupbg").fadeIn("fast");
        $("#popup").fadeIn('fast');
        popupStatus = 1;
    }
}

function disablePopup() {
    if(popupStatus==1) {
        $("#popupbg").fadeOut('fast');
        $("#popup").fadeOut('fast');
        popupStatus = 0;  
    }
}

function centerPopup() {
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popup").height();
    var popupWidth = $("#popup").width();

    $("#popup").css({
        "position": "absolute",
        "top": windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2  
    });

    $("#popupbg").css("height",windowHeight);
    $("#popupbg").css("width",windowWidth);
}

function putContent(e) {
    $('#popup').css('width',390);
    $('#popup').css('height',530);
    $("#popup-content .image-list").html($(e.currentTarget).parent().parent().siblings('div.item-popup-content').html());
    // add this line
    $(".b-popup-body .b-popup-picture").attr('src',$("#popup-content ul.b-popup-thumbs li.current img.big").attr('src'));
    $("#popup-content ul.b-popup-thumbs li.pict").click(function(){
        $(this).siblings(".current").removeClass('current');
        $(this).addClass('current');
        var new_src = $(this).children("img.big").attr('src')
        $(".b-popup-body .b-popup-picture").attr('src',new_src);
    });
}

function putCartContent(e) {
    $('#popup').css('width',600);
    $('#popup').css('height',520);
    $("#popup #popup-content").html($('#cart-content').html())
}

$(document).ready(function() {
    $("div.cart-actions p.zoom a, div.cart-item a.zoom, div.cart-item h2 a.zoom").bind("click", function(event) {
        loadPopup();
        putContent(event);
        centerPopup();
    });
    
    $("div.cart-actions p.tocart a").bind("click", function(event) {
        loadPopup();
        putCartContent(event);
        centerPopup();
    });

    $("#popupbg, .b-popup-content #close, .b-popup-content #continue").bind('click', function() { disablePopup(); });

    $(document).bind("keypress", function(e) {
        if (e.keyCode==27 && popupStatus==1) {
            disablePopup();
        }
    });
});