// XXX These functions should all be properly named-spaced and named better.
function addItemToCart(form) {
    $('#cart-total-container')
        .load('/commerce/choose_format_api.html',
            $(form).serializeArray(),
            function() {
                disablePopup();
                $('#cart-total').addClass("cart-box");
                window.setTimeout(function () {$('#cart-total').removeClass("cart-box"); }, 2000);
            }
        );
}

function PopupBox() {
    this.productInfo = {};
}

PopupBox.prototype.addProductInfo = function (obj) {
    $.extend(this.productInfo, obj);
}

PopupBox.prototype.bindDialogBox = function (selector, dialogBox) {
    var popupThis = this;
    $(selector).unbind('click');
    $(selector).bind('click', function() {
            var classes = $(this)[0].className.split(/ /);
            var product_no = '';

            $.each(classes, function(i, item) {
               if (item.substring(0, 10) == 'addToCart-') {
                   product_no = item.substring(10);
               }
            });
            dialogBox.html(popupThis.productInfo[product_no]);
            if (!dialogBox.html()) {
                dialogBox.html('<p>No product information is available.</p>');
            }

            $("#popupBoxClose, #backgroundPopup, .secondary-btn").click(disablePopup);

            $("#popup-buttons .button").click(function(){
                dialogBox.find("#popup-buttons")
                    .hide()
                    .end()
                    .find("#popup-waiting")
                    .show();
            });

            centerPopup();
            loadPopup();
            return false;
    });

    //Press Escape event!
    $(document).keypress(function(e){
        if(e.keyCode==27 && popupStatus==1){
            disablePopup();
        }
    });
}

var popup = new PopupBox();

var popupStatus = 0;

function loadPopup(){
    //loads popup only if it is disabled
    if(popupStatus==0){
        $("#backgroundPopup").css("opacity","0.7");
        $("#backgroundPopup").css("filter","alpha(opacity=70)");
        $("#backgroundPopup").fadeIn("slow");
        $("#popupBox").fadeIn("slow");
        popupStatus = 1;
    }
}
function disablePopup(){
    //disables popup only if it is enabled
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $("#popupBox").fadeOut("slow");
        popupStatus = 0;
    }
}
function centerPopup(){
    //request data for centering
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $("#popupBox").height();
    var popupWidth = $("#popupBox").width();

    //centering
    $("#popupBox").css({
        "position": "fixed",
        "top": windowHeight/2-popupHeight/2,
        "left": windowWidth/2-popupWidth/2
    })
    //only need force for IE6
    $("#backgroundPopup").css({
        "height": windowHeight
    });
}
