var bobexample = new switchcontent("groupSection", "div")
bobexample.setStatus('<a class="hide" href="javascript:;"></a>', '<a class="open" href="javascript:;"></a>')
bobexample.setPersist(false)
bobexample.collapsePrevious(false)
bobexample.init()

var proPackageContainer;
var basicPackageContainer;
var promoCodeDiscount = 0;
var orderDiscountGl = 0;

$(document).ready(function() {
    basicPackageContainer = $('#basicpackage');
    proPackageContainer = $('#propackage');
    if (promoCodeDiscount.toString() == '0' && document.getElementById('htbPromoPersentage').value != '') {
        promoCodeDiscount = document.getElementById('htbPromoPersentage').value;
    }
    else {
        var t = document.getElementById(document.getElementById('htbPromoName').value);
        if (t.value != ''){
            promoCodeChanged(t.value);
        }
    }
});

function updatePackages() {
    var num = document.getElementById("lblBasicPackage").childNodes[0].checked ? 1 : 2;
    selectPage(num);
    CalcOrderTotalPriceSel();
    //displayOrderDeliveryTime(getPagesCount(), isOrderExpedited());
}

function selectPage(num) {
    document.getElementById("basicpackage").style.display = num == 1 ? "" : "none";
    document.getElementById("propackage").style.display = num == 2 ? "" : "none";
}

function CalcOrderTotalPriceBasic() {
    CalcOrderTotalPrice(basicPackagePrice, basicItemsPrices, basicItemsPricesOrder);
}

function CalcOrderTotalPricePro() {
    CalcOrderTotalPrice(proPackagePrice, proItemsPrices, proItemsPricesOrder);
}

function CalcOrderTotalPriceSel() {
    if (document.getElementById("basicpackage").style.display == "none") {
        CalcOrderTotalPricePro();
    } else {
        CalcOrderTotalPriceBasic();
    }
}

function CalcOrderTotalPrice(packagePrice, itemsPrices, itemsPricesOrder) {
    var optionItemControl = null;
    
    //Get PricePerPage
    var pricePerPage = packagePrice;
    for (key in itemsPrices) {
        optionItemControl = document.getElementById(key);
        if (null != optionItemControl && optionItemControl.checked == true) {
            pricePerPage += itemsPrices[key];
        }
    }

    //Get PricePerOrder
    var pricePerOrder = 0;
    for (key in itemsPricesOrder) {
        optionItemControl = document.getElementById(key);
        if (null != optionItemControl && optionItemControl.checked == true) {
            pricePerOrder += itemsPricesOrder[key];
        }
    }

    //Get pages count
    var pagesCount = getPagesCount();

    //Total price
    var orderTotalPrice = getOrderTotalPrice(pricePerPage, pricePerOrder, pagesCount, globalUserDiscountPercentage);
    
    //Display price
    displayOrderTotalPrice(orderTotalPrice);

    displayOrderDeliveryTime(getPagesCount(), isOrderExpedited());
}

function displayOrderTotalPrice(orderTotalPrice) {
    displayPrice("spnBasicPrice", orderTotalPrice.BasicPrice);
    displayPrice("spnSecondaryPageDiscount", orderTotalPrice.SecondaryPageDiscount);
    displayPrice("spnFivePagesDiscount", orderTotalPrice.FivePageDiscount);
    if (orderTotalPrice.RepeatOrdersDiscount != null)
        displayPrice("spnRepeatOrderDiscount", orderTotalPrice.RepeatOrdersDiscount);

    var totalPrice = orderTotalPrice.getTotalPrice();

    if (isOrderExpedited())
        totalPrice = totalPrice + (totalPrice / 2);
    displayPrice("spnTotal", totalPrice);
}

function displayPrice(spanPriceID, priceValue) {

    var spanPrice = document.getElementById(spanPriceID);
    var totalValue = "$" + Math.round(priceValue * 100) / 100;

    spanPrice.innerHTML = totalValue;
}

function getOrderTotalPrice(pricePerPage, pricePerOrder, pagesCount, userDiscountPercentage) {

    var orderTotalPrice = new OrderTotalPrice();

    if (pagesCount == 0)
        return orderTotalPrice;

    //Secondary page 50% discount
    if (pagesCount > 1)
        orderTotalPrice.SecondaryPageDiscount = 0.5 * (pagesCount - 1) * pricePerPage;

    //5+ volume 3% discount
    if (pagesCount > 5)
        orderTotalPrice.FivePageDiscount = 0.03 * (pagesCount - 5) * pricePerPage;

    //Base price for the all pages
    orderTotalPrice.BasicPrice = pricePerOrder + (pricePerPage * pagesCount);

    //Repeat order nn% discount
    if (userDiscountPercentage != null)
        orderTotalPrice.RepeatOrdersDiscount = orderTotalPrice.BasicPrice * userDiscountPercentage / 100;

    return orderTotalPrice;
}

function OrderTotalPrice() {
    this.BasicPrice = 0;
    this.SecondaryPageDiscount = 0;
    this.FivePageDiscount = 0;
    this.RepeatOrdersDiscount = null;
}

OrderTotalPrice.prototype.getTotalPrice = function() {
    if (this.BasicPrice == 0)
        return 0;

    var repeatOrdersDiscountValue = 0;
    if (this.RepeatOrdersDiscount != null)
        repeatOrdersDiscountValue = this.RepeatOrdersDiscount;

    var orderDiscount = this.SecondaryPageDiscount + this.FivePageDiscount + repeatOrdersDiscountValue;
    orderDiscountGl = orderDiscount;
    return (this.BasicPrice - orderDiscount) * (1 - promoCodeDiscount);
}
// Add date format function
var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);

Date.prototype.format = function(f) {
    if (!this.valueOf())
        return ' ';

    var d = this;

    return f.replace(/(mmmm|dd)/gi,
        function($1) {
            switch ($1.toLowerCase()) {
                case 'mmmm': return gsMonthNames[d.getMonth()];
                case 'dd': return d.getDate();
            }
        }
    );
}

function displayOrderDeliveryTime(pagesCount, isExpedited) {

    var packageOptions = getPackageOptionsIds();
    var spnEstDeliveryCustomValue = $('#spnEstDeliveryCustomValue');
    var spnEstDeliveryCalculatedValue = $('#spnEstDeliveryCalculatedValue');

    $.ajax({
        type: "POST",
        url: "/ajaxhandler.aspx",
        data: {
            "requestType": "orderDeliveryTime",
            "pagesCount": pagesCount,
            "packageOptions": packageOptions,
            "isExpedited": isExpedited
        },
        success: function(data) {
            var orderDeliveryTime = $.parseJSON(data); //convert JSON string into object

            if (orderDeliveryTime.DeliveryHrs == -1) {
                spnEstDeliveryCustomValue.removeClass('hide');
                spnEstDeliveryCalculatedValue.addClass('hide');
            }
            else {
                spnEstDeliveryCustomValue.addClass('hide');
                spnEstDeliveryCalculatedValue.removeClass('hide');
            }
            // set correct date format 
            var myDate = new Date(parseInt(orderDeliveryTime.DeliveryDate.replace("/Date(", "").replace(")/", ""), 10));
            $('#spnDeliveryHrs').attr('innerHTML', orderDeliveryTime.DeliveryHrs);
            $('#spnDeliveryDays').attr('innerHTML', orderDeliveryTime.DeliveryDays);
            $('#spnDeliveryDate').attr('innerHTML', myDate.format('mmmm dd'));
        },
        error: function() {
            spnEstDeliveryCustomValue.removeClass('hide');
            spnEstDeliveryCalculatedValue.addClass('hide');
        }
    });
}

function orderDeliveryInfoChanged() {

    CalcOrderTotalPriceSel();
    //displayOrderDeliveryTime(getPagesCount(), isOrderExpedited());
}

function promoCodeChanged(val) {
    $.ajax({
        type: "POST",
        url: "/ajaxhandler.aspx",
        data: {
            "requestType": "getPromoCode",
            "code": val
        },
        success: function(msg) {
            promoCodeDiscount = parseFloat(msg);
            document.getElementById('htbPromoPersentage').value = promoCodeDiscount;
            CalcOrderTotalPriceSel();
        }
    });
}

function getPagesCount() {
    var pagesValue = document.getElementById('divPages').childNodes[0].value;
    if (pagesValue == "") pagesValue = "1";
    var pagesIntValue = parseInt(pagesValue);
    if (!isNaN(pagesIntValue))
        return pagesIntValue;
    else
        return 1;
}

function isOrderExpedited() {
    var deliveryTime = document.getElementById('divExpedited').childNodes[1].value
    return (deliveryTime == "expYes");
}

function getPackageOptionsIds() {

    var packageOptions = new Array();
    var optionItemControl = null;
    var start = document.getElementById("lblBasicPackage").childNodes[0].checked ? 'Basic_'.length : 'Pro_'.length;

    //per page
    var pageOptionCollection = document.getElementById("lblBasicPackage").childNodes[0].checked ? basicItemsPrices : proItemsPrices;

    for (key in pageOptionCollection) {
        optionItemControl = $('#'.concat(key));
        if (optionItemControl.attr('checked')) {
            packageOptions.push(parseInt(key.substring(start)));
        }
    }

    //per order
    var orderOptionCollection = !basicPackageContainer.hasClass('hide') ? basicItemsPricesOrder : proItemsPricesOrder;

    for (key in orderOptionCollection) {
        optionItemControl = $('#'.concat(key));
        if (optionItemControl.attr('checked')) {
            packageOptions.push(parseInt(key.substring(start)));
        }
    }

    return packageOptions;
}
