var popupActive = false;
var numberOfProductsUrl = "";

function addProductCheckNorm(id, medium, dateRetraction, warning1, warning2, warning3) {

    //Steps:
    //1. Get list of replaced by's (contains html links)
    //2. Check if the norm is retracted. If not, return
    //3. Initialize modal dialog
    //4. Set the warning text incl. urls
    //5. Replace the functionality of the default close button by its own
    //6.  Show the modal dialog
    //warning 1 - Let op! Deze norm is ingetrokken op <datum>
    //warning 2 - Deze norm is vervangen door: <link naar norm>
    //warning 3 - Klik op de vervangende norm of bevestig om de huidige norm te bestellen

    //Step 1 - Get list of replaced by's (contains html links)
    replacedby = $("em#replacedByList").html();

    //Step 2 - Check if the norm is retracted. If not, return
    if ((dateRetraction == null) || (dateRetraction == "")) {
        addProduct(id, medium);
        return;
    }

    //Step 3 - Initialize modal dialog
    $(".carousel").css('z-index', '0');
    $("div#tb_placeholder").html($("#normwarningdialog").html());
    popupActive = true;

    //Step 4 - Set the warning text incl. urls
    if (replacedby != null) {
        $("div#tb_placeholder>div#warning").html(warning1 + " " + dateRetraction + ".<BR/><BR/>" + warning2 + " " + replacedby + ".<BR/><BR/>" + warning3)
    } else {
        $("div#tb_placeholder>div#warning").html(warning1 + " " + dateRetraction + ".<BR/><BR/>");
    }

    //Step 5 - Replace the functionality of the default close button by its own
    $("div#tb_placeholder a.button").unbind();
    $("div#tb_placeholder a.button").click(function() {
        //$("div#TB_ajaxContent").html('');
        addProduct(id, medium);
    });

    //Step 6 - Show the modal dialog
    tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);
    SimplyButtons.init();

}

function addProduct(id, medium, confirm, isCampaignPackage) {

    var data = "productId=" + id + "&numberOfProducts=1&medium=" + medium;
    if (confirm != null) {
        data += "&confirm=" + confirm;
    }
    if (isCampaignPackage != null) {
        data += "&campaignpackage=" + isCampaignPackage;
    }
    $.ajax({
        type: 'POST',
        url: "/web/wcbservlet/nl.vlc.nen.servlets.shoppingcartservlet.add",
        data: data,
        dataType: 'json',
        success: function(data, status) {
            var jsonString = $.toJSON(data);
            var status = $.evalJSON(jsonString).status;

            switch (status) {
            case '10':
                //                        if(popupActive) {
                //                            $("div#TB_ajaxContent").html($("#productaddeddialog").html());
                //                        } else {
                //                            $(".carousel").css('z-index', '0');
                //
                //                            $("div#tb_placeholder").html($("#productaddeddialog").html());
                //                            tb_show("","#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true",null);
                //
                //                            SimplyButtons.init();
                //                        }
                $("a.cart-box").css("font-weight", "bold");
                goToShoppingCart(shoppingCartPageURL);
                break;
            case '11':
                //alert("confirmation needed");
                var products = $.evalJSON(jsonString).products;
                var mandatoryProducts = new Array();
                var nonMandatoryProducts = new Array();

                //clear previous
                $('div#checkListMandatory').html("");
                $('div#checkListNonMandatory').html("");

                jQuery.each(products,
                function(i, p) {
                    if (p.mandatory == 'true') {
                        var checkbox = "<input type=\"checkbox\" name=\"confirm\" id=\"confirm" + p.id + "\" value=\"" + p.id + "\" checked=\"checked\" DISABLED/><label for=\"confirm" + p.id + "\" title=\"" + p.documentnumber + "\">" + p.documentnumber + " (&euro; " + p.line_price.replace('.', ',') + ")</label><br/>"
                        $('div#checkListMandatory').append(checkbox);

                    } else {
                        var checkbox = "<input type=\"checkbox\" name=\"confirm\" id=\"confirm" + p.id + "\" value=\"" + p.id + "\"/><label for=\"confirm" + p.id + "\" title=\"" + p.documentnumber + "\">" + p.documentnumber + " (&euro; " + p.line_price.replace('.', ',') + ")</label><br/>"
                        $('div#checkListNonMandatory').append(checkbox);

                    }
                });

                var optionalProductsEmpty = $('div#checkListNonMandatory').html() == "";
                var mandatoryProductsEmpty = $('div#checkListMandatory').html() == "";
                if (optionalProductsEmpty) $('span#confirmdialog_optional').hide();
                //2010-04-19 RH: Added to hide optional header when no optional products are available
                if (mandatoryProductsEmpty) $('span#confirmdialog_mandatory').hide();
                //2010-04-19 RH: Added to show optional header when no optional products are available
                $(".carousel").css('z-index', '0');

                $("div#tb_placeholder").html($("#confirmdialog").html());

                $("div#tb_placeholder a.button").unbind();
                $("div#tb_placeholder a.button").click(function() {
                    confirmProduct(id, medium);
                    $("div#TB_ajaxContent").html('');
                    closeConfirmDialog();
                    return false;
                });

                popupActive = true;
                tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                SimplyButtons.init();
                break;
            case '12':
                $("div.popupheadline").html('<h2>Error</h2>');
                $("div#errorSection").html('<b>not all mandatory products are accepted</b>');

                $("div#tb_placeholder").html($("#errorDialog").html());

                $("div#tb_placeholder a.button").unbind();
                $("div#tb_placeholder a.button").click(function() {
                    $("div#TB_ajaxContent").html('');
                    closeConfirmDialog();
                    return false;
                });

                popupActive = true;
                tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                SimplyButtons.init();

                //popupActive = true;
                //alert("not all mandatory products are accepted");
                break;
            case '20':
                $("div.popupheadline").html('<h2>Error</h2>');
                $("div#errorSection").html('<b>error parsing parameters</b>');

                $("div#tb_placeholder").html($("#errorDialog").html());

                $("div#tb_placeholder a.button").unbind();
                $("div#tb_placeholder a.button").click(function() {
                    $("div#TB_ajaxContent").html('');
                    closeConfirmDialog();
                    return false;
                });

                tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                SimplyButtons.init();

                popupActive = true;
                //alert("error parsing parameters");
                break;
            case '21':
                $("div.popupheadline").html('<h2>Error</h2>');
                $("div#errorSection").html('<b>error parsing confirmation</b>');

                $("div#tb_placeholder").html($("#errorDialog").html());

                $("div#tb_placeholder a.button").unbind();
                $("div#tb_placeholder a.button").click(function() {
                    $("div#TB_ajaxContent").html('');
                    closeConfirmDialog();
                    return false;
                });

                tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                SimplyButtons.init();

                popupActive = true;
                //alert("error parsing confirmation");
                break;
            case '23':
                $("div.popupheadline").html('<h2>Error</h2>');
                $("div#errorSection").html('<b>product not available in selected medium</b>');

                $("div#tb_placeholder").html($("#errorDialog").html());

                $("div#tb_placeholder a.button").unbind();
                $("div#tb_placeholder a.button").click(function() {
                    $("div#TB_ajaxContent").html('');
                    closeConfirmDialog();
                    return false;
                });

                tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                SimplyButtons.init();

                popupActive = true;
                //alert("product not available in selected medium");
                break;
            case '24':
                if (popupActive) {
                    $("div#TB_ajaxContent").html($("#notforsaledialog").html());
                } else {
                    $(".carousel").css('z-index', '0');

                    $("div#tb_placeholder").html($("#notforsaledialog").html());
                    tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

                    SimplyButtons.init();
                }
                break;
            }

            if (numberOfProductsUrl != "") {
                $('#numberOfProducts').load(numberOfProductsUrl);
            }
        }
    });

}

function goToCourseReservation(url, courseId) {
    var courseId = $('#currentCourseId').val();
    location.href = url + "?courseid=" + courseId;
    closeConfirmDialog();
}

function goToShoppingCart(url) {
    location.href = url;
    closeConfirmDialog();
}

function closeConfirmDialog() {
    tb_remove();
    $(".carousel").css('z-index', '600');

    popupActive = false;
}

function confirmProduct(id, medium) {
    var confirm = "";

    $("div#checkListMandatory input:checkbox").each(function() {
        if (this.checked == true) {
            if (confirm != "") {
                confirm += ",";
            }
            confirm += $(this).val();
        }
    });
    $("div#checkListNonMandatory input:checkbox").each(function() {
        if (this.checked == true) {
            if (confirm != "") {
                confirm += ",";
            }
            confirm += $(this).val();
        }
    });

    if (confirm == "") {
        confirm = -1;
    }

    addProduct(id, medium, confirm);
}

function deleteProduct(id, container, url) {
    $.ajax({
        type: "POST",
        url: "/web/wcbservlet/nl.vlc.nen.servlets.shoppingcartservlet.delete",
        data: "productId=" + id,
        success: function(msg) {
            if (container && url) {
                $('div#' + container).load(url);
            }

            if (numberOfProductsUrl != "") {
                $('#numberOfProducts').load(numberOfProductsUrl,
                function() {
                    if ($('#numberOfProducts').html().trim() != '') {
                        $('a.cart-box').css('font-weight', 'bold');
                    } else {
                        $('a.cart-box').css('font-weight', 'normal');
                    }
                });
            }
        }
    });
}

function updateProduct(id, number, container, url) {
    $.ajax({
        type: "POST",
        url: "/web/wcbservlet/nl.vlc.nen.servlets.shoppingcartservlet.update",
        data: "productId=" + id + "&numberOfProducts=" + number,
        success: function(msg) {
            if (container && url) {
                $('div#' + container).load(url);
            }

            if (numberOfProductsUrl != "") {
                $('#numberOfProducts').load(numberOfProductsUrl,
                function() {
                    if ($('#numberOfProducts').html().trim() != '') {
                        $('a.cart-box').css('font-weight', 'bold');
                    } else {
                        $('a.cart-box').css('font-weight', 'normal');
                    }
                });
            }
        }
    });
}

function validateCampaignCode(campaignCode, container, url) {
    $.ajax({
        type: "POST",
        url: "/web/wcbservlet/nl.vlc.nen.servlets.shoppingcartservlet.validatecampaigncode",
        data: "campaigncode=" + campaignCode,
        dataType: 'json',
        success: function(data, status, message) {
            var jsonString = $.toJSON(data);
            var status = $.evalJSON(jsonString).status;
            var message = $.evalJSON(jsonString).message;
            var statusNumber = parseInt(status);
            if (!isNaN(statusNumber) && statusNumber >= 10) {
                $('.campaigncode_warning').removeClass('campaigncode_warning_invisible');
                $('.campaigncode_warning strong').html(message);
            } else {
                $('.campaigncode_warning').addClass('campaigncode_warning_invisible');
                $('.campaigncode_warning strong').html('');
            }
            if (container && url) {
                $('div#' + container).load(url);
            }

            if (numberOfProductsUrl != "") {
                $('#numberOfProducts').load(numberOfProductsUrl,
                function() {
                    if ($('#numberOfProducts').html().trim() != '') {
                        $('a.cart-box').css('font-weight', 'bold');
                    } else {
                        $('a.cart-box').css('font-weight', 'normal');
                    }
                });
            }
        }
    });
}

function checkNumberOfArticles(submitURL, message) {
    //2010-04-13 RH: Als items verwijderd zijn uit de shopping cart en het aantal is weer gelijk aan 0, knoppen verbergen
    var totalArticlesCount = $("strong#totalArticlesCount").html();

    if (totalArticlesCount > 0) {
        location.href = submitURL;
    } else {
        //alert("U heeft geen artikelen meer in uw winkelmandje.")
        alert(message);
    }
}

function showCourseDelay(courseId) {
    if (popupActive) {
        $("div#TB_ajaxContent").html($("#courseDelayDialog").html());
    } else {
        $(".carousel").css('z-index', '0');

        $("div#tb_placeholder").html($("#courseDelayDialog").html());
        tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

        SimplyButtons.init();
    }
}

function showIE6Message() {
    if (popupActive) {
        $("div#TB_ajaxContent").html($("#IE6Message").html());
    } else {
        $(".carousel").css('z-index', '0');

        $("div#tb_placeholder").html($("#IE6Message").html());
        tb_show("", "#TB_inline?height=&width=400&inlineId=tb_placeholder&modal=true", null);

        SimplyButtons.init();
    }
}

//$(document).ready(function() {
//    if(typeof(String.prototype.trim) === "undefined")
//    {
//        String.prototype.trim = function()
//        {
//            return String(this).replace(/^\s+|\s+$/g, '');
//        };
//    }
//    if ($("#numberOfProducts").html().trim() != "") {
//        $("a.cart-box").css("font-weight", "bold");
//    } else {
//        $('a.cart-box').css('font-weight', 'normal');
//    }
//});

