﻿
var Format = {
    basePaper: "A4", maxWidth: config.paperSize.A4.width, maxHeight: config.paperSize.A4.height, minHeight: 50, minWidth: 50, paperType: "A4", customFormat: true, width: 0, height: 0,
    update: function() {
        var f = $("format").value.split('#', 1)[0];
        if (f != config.paperSize.Custom.type) {
            this.basePaper = f;
            this.paperType = config.paperSize[f].type;
            this.width = config.paperSize[f].width;
            this.height = config.paperSize[f].height;
            $("dcut").hide();
            this.customFormat = false;
        }
        else {
            var cut1 = +$("cutWidth").value, cut2 = +$("cutHeight").value;
            this.width = Math.min(cut1, cut2);
            this.height = Math.max(cut1, cut2);
            var matchingFormat = null;
            for (var i = config.paperSize.formats.length - 1; i >= 0; i--) {
                var temp = config.paperSize[config.paperSize.formats[i]];
                if (temp.name == "Custom")
                    continue;

                if (this.width != this.height) {
                    if (temp.name.substr(-1) == "q")
                        continue;
                }
                else
                    if (temp.name.substr(-1) != "q")
                        continue;

                if (this.width <= temp.width && this.height <= temp.height) {
                    matchingFormat = temp;
                    break;
                }
            }
            this.basePaper = (matchingFormat == null) ? null : matchingFormat.name;
            if (this.basePaper) {
                this.paperType = matchingFormat.type;
                $("ppaperFormat").getElementsByTagName("dfn")[0].firstChild.data = matchingFormat.display;
            }
            $("dcut").show();
            this.customFormat = true;

        }
        // console.log("selected paper: " + this.basePaper + " paperType: " + this.paperType);
    }
};

function getMul(paperType) // not used yet!
{
    if (paperType != config.paperSize.Custom.type)
    {
        return config.paperSize[paperType].mul;
    }
    else
    {
        
    }
}


var rules = {
    "#buchtyp, #seitenzahlen": function (e) {
        e.addValidator(function (e) {
            updatePauschale();
            updateRecommandations();
        });
    },

    "#shipUntil": function (e) {
        e.addValidator(function (e) {
            if (document.getElementById("prizeOnly").checked == false)
                if (!/^\s*\d\d?\s*\.\s*\d\d?\s*\.\s*\d\d(\d\d)?\s*$/.test(e.value))
                    return "Bitte geben Sie das Datum in der Form Tag.Monat.Jahr ein.";
        });
    },

    "#editions": function (e) {
        e.addValidator(function (e) {
            if (!Format.basePaper) return "Bitte wählen Sie ein anderes Papierformat";
            var n = +e.value, mul = config.paperSize[Format.basePaper].mul;
            var r = n % mul, s = n - r;
            if (isNaN(n) || n < 2 || r)
                return "Bitte wählen Sie " + mul + " oder ein Vielfaches davon" + (s > mul ? ", z.B. " + s + "." : ".");
        });
    },

    "#project": function (e) {
        e.addValidator(function (e) {
            if (+e.value == "") return "Bitte geben Sie einen Projektnamen an.";
        });
    },

    "#format": function (e) {
        e.addValidator(function (e) {
            //calc_shipping();
        });
    },
    "#cutWidth": function (e) {
        e.addValidator(function (e) {
            if (!Format.customFormat)
                return null;

            if (+e.value > Format.maxWidth) return "Bitte wählen Sie einen Wert unter " + Format.maxWidth + ".";
            if (e.value < Format.minWidth) return "Mindestmaß 50x50 mm oder 50 mm kurze Seite.";
        });
    },
    "#cutHeight": function (e) {
        e.addValidator(function (e) {
            if (!Format.customFormat)
                return null;

            if (+e.value > Format.maxHeight) return "Bitte wählen Sie einen Wert unter " + Format.maxHeight + ".";
            if (e.value < Format.minHeight) return "Mindestmaß 50x50 mm oder 50 mm kurze Seite.";
        });
    },
    //    	"#cutWidth, #cutHeight" : function( e ) { e.addValidator( function( e ) {
    //    		var other = $(e.id == "cutHeight" ? "cutWidth" : "cutHeight");
    //    		var max = Math[(+other.value >= +e.value) ? "min" : "max"](Format.maxWidth, Format.maxHeight);
    //    		if( Format.basePaper == "A6" ) other.value = e.value;
    //    		if( +e.value > max ) return "Bitte wählen Sie einen Wert unter " + max + ".";
    //    	} ); },

    "#pagesWhite, #pagesBlack, #pagesColor": function (e) {
        e.addValidator(function (e) {
            var n = +e.value;
            if (isNaN(n) || n<0) return "Bitte geben sie eine Zahl größer oder gleich 0 an.";
            return updatePaperThickness() ? "Das Buch ist zu dick \u2012 bitte wählen Sie eine kleinere Seitenzahl." : null;
        });
    },

    "#paperBlack, #pagesWhite, #paperColor, #pagesDouble, #rabatt, #country, #pagesColor, #pagesBlack": function (e) { e.addValidator(function (e) { updatePaperThickness(); }); },
    //"#seitenzahlen": function(e) { e.addValidator(function(e) { updatePrize(); }); },

    "#coverType": function (e) {
        e.addValidator(function (e) {
            updateRecommandations();
            var is_soft = e.value.indexOf("Paperback") == 0;
            $("plamination")[is_soft ? "show" : "hide"]();
            $("plamination").checked = is_soft;
        });
    },

    "#dataType": function (e) {
        e.addValidator(function (e) {
            //$("ddesign")[e.value == config.designPrize.individual ? "show" : "hide"]();
            if (e.value.split('#', 1)[0] == "moreInfos") {
                $("ddesign").style.display = "block";
                $("divColorSpace").style.display = "none";
            }
            else {
                $("ddesign").style.display = "none";
                $("divColorSpace").style.display = "block";
            }

            //$("ddesign")[e.value == config.designPrize.individual ? "show" : "hide"]();

        });
    },
    "#photoCount": function (e) {
        e.addValidator(function (e) {
            if ($("ddesign").style.display == "none")
                return;
            var n = +e.value;
            if (isNaN(n) || n < 1) return "Bitte geben Sie die Zahl der Fotos ein.";
        });
    },
    "#lamination, #foil, #photoDigital, #textDigital, #vat, #off, #paperBlack, #paperColor, #drpVorsatzPaper, #drpSortingBelt": function (e) { e.addValidator(null); },

    "#name": function (e) {
        e.addValidator(function (e) {
            if (e.value.strip().length < 3) return "Bitte geben Sie ihren Vor- und Nachnamen an.";
        });
    },
    "#email": function (e) {
        e.addValidator(function (e) {
            if (!/\S+\@\S+\.[a-z]+/i.test(e.value.strip()))
                return "Bitte geben Sie ihre eMail-Adresse an.";
        });
    },
    "#sendToMe": function (e) {
        e.addValidator(function (e) {
            $("send").disabled = !((e.checked && !$("email").errorMessage) || $("sendToThem").checked);
            return (e.checked && $("email").errorMessage) ? "Bitte geben Sie oben ihre eMail-Adresse an" : null;
        });
    },
    "#sendToThem": function (e) { e.addValidator(null); },
    "#shipAddress": function (e) {
        e.addValidator(function (e) {
            if (e.value.strip().length < 10) return "Bitte geben Sie ihre Postadresse an.";
        });
    },
    "#tel": function (e) {
        e.addValidator(function (e) {
            if (e.value.strip().length < 5)
                return "Bitte geben Sie ihre Telefonnummer an, damit wir Sie ggf. persönlich erreichen können.";
        });
    }
};

function isLaminated() {
    return ($("coverType").value.indexOf("Paperback") == 0 && $("lamination").checked) ? 1 : 0;
}

function paperCount(e) {
    return value = +$(e).value / ($("pagesDouble").checked ? 2 : 1);
}

function blackSheets() { return Math.ceil(+$("editions").value * (+paperCount("pagesBlack") + +paperCount("pagesWhite")) / (Format.basePaper == null ? 2 : config.paperSize[Format.basePaper].mul)); }
function colorSheets() { return Math.ceil(+$("editions").value * +paperCount("pagesColor") / (Format.basePaper == null ? 2 : config.paperSize[Format.basePaper].mul)); }

function updatePauschale() {
    var total = config.buchtyp[$("buchtyp").value.split('#', 1)[0]].prize + parseInt($("seitenzahlen").value.split('#', 1)[0]);
    $("hPrizeOnce").value = total;
    return total;
}

function updateRecommandations() {
    var sCategory = $("buchtyp").value.split('#', 1)[0];
    var hohlrueckenR = (config.buchtyp[sCategory].hohlrueckenRecommended == "yes");

    if (!hohlrueckenR) {
        var pagesTotal = paperCount("pagesBlack") + paperCount("pagesWhite") + paperCount("pagesColor");

        var minPages = config.buchtyp.hohlrueckenHardcoverMinPagesR;        
        var minPages = 250; // direct assignment though config-value is not read properly

        if (pagesTotal >= minPages) {
            var sCoverType = $("coverType").value.split('#', 1)[0];
            if (!config.cover[sCoverType].ishr && !config.cover[sCoverType].ishc)
                hohlrueckenR = true;
        }
    }

    $("phardcover").style.display = hohlrueckenR ? "block" : "none";

    var isHohlruecken = config.cover[$("coverType").value.split('#', 1)[0]].ishr;
    var isSortingBeltSelected = (parseInt($("drpSortingBelt").value) > 0);

    $("pSortingBeltWarning").style.display = (isSortingBeltSelected && !isHohlruecken) ? "block" : "none";
}

function updatePaperThickness() {
    var blackInfo = config.paperType[$("paperBlack").value.split('#', 1)[0]];
    var colorInfo = config.paperType[$("paperColor").value.split('#', 1)[0]];
    $("paperBlackInfo").firstChild.data = blackInfo.thick.toCurrency(3, "mm", 1) + " dick. " +
	  blackInfo.prize.toCurrency(4) + " pro Bogen, insgesamt " + blackSheets() + " Bögen.";
    $("paperColorInfo").firstChild.data = colorInfo.thick.toCurrency(3, "mm", 1) + " dick. " +
	  colorInfo.prize.toCurrency(4) + " pro Bogen, insgesamt " + colorSheets() + " Bögen.";

    var blackThick = blackInfo.thick * paperCount("pagesBlack");
    var colorThick = colorInfo.thick * paperCount("pagesColor");
    var whiteThick = blackInfo.thick * paperCount("pagesWhite");
    var coverThick = parseFloat(config.cover[$("coverType").value.split('#', 1)[0]].thick) + (isLaminated() ? parseFloat(config.cover.softLamination.thick) : 0);
    var totalThick = blackThick + colorThick + whiteThick;
    
    // $("hthickInner").value = totalThick.toCurrency(3, "mm", 1);
    $("pcoverPrize").setPrize(coverThick, 1, 1, 3, "mm");
    // $("hthickCover").value = coverThick.toCurrency(3, "mm", 1);
    $("pagesTotal").setPrize(totalThick + coverThick, 1, 1, 3, "mm");
    $("pagesTotal").setPrize(config.maxThickness + coverThick, 3, 1, 2, "mm");
    // $("hthickTotal").value = (totalThick + coverThick).toCurrency(3, "mm", 1);
    $("pBookInfo").setPrize(totalThick + coverThick, 0, 1, 3, "mm");

    $("hBookThickness").value = totalThick + coverThick;
    return totalThick <= config.maxThickness
		? null : ("Die Dicke des Innenteils übersteigt " + config.maxThickness.toCurrency(0, "mm", 1) + "!");
}

function updatePaperPrize() { // returns paper print&material costs for one book
    if (!Format.basePaper) return NaN;
    var editions = +$("editions").value;
    var mul = config.paperSize[Format.basePaper].mul;
    // console.log("mul: " + mul);
    var _blackSheets = blackSheets();
    var _colorSheets = colorSheets();
    var _blackPaperPrize = config.paperType[$("paperBlack").value.split('#', 1)[0]].prize;
    var _colorPaperPrize = config.paperType[$("paperColor").value.split('#', 1)[0]].prize;
    var _totalBlackPaperPrize = _blackSheets * _blackPaperPrize;
    var _totalColorPaperPrize = _colorSheets * _colorPaperPrize;
    var _totalPaperPrize = _totalBlackPaperPrize + _totalColorPaperPrize;
    var _bookPaperPrize = _totalPaperPrize / editions;

    var _blackPrintPages = +$("pagesBlack").value;
    var _colorPrintPages = +$("pagesColor").value;
    var _blackPrintPrize = config.printPrize.black / mul;
    var _colorPrintPrize = config.printPrize.color / mul;
    var _bookBlackPrintPrize = _blackPrintPages * _blackPrintPrize;
    var _bookColorPrintPrize = _colorPrintPages * _colorPrintPrize;
    var _bookPrintPrize = _bookBlackPrintPrize + _bookColorPrintPrize;

    var total = _bookPaperPrize + _bookPrintPrize;

    var e;
    e = $("paperTotalPrize");
    e.setValue(_blackSheets, 0); e.setPrize(_blackPaperPrize, 1, null, 4); e.setPrize(_totalBlackPaperPrize, 2);
    e.setValue(_colorSheets, 3); e.setPrize(_colorPaperPrize, 4, null, 4); e.setPrize(_totalColorPaperPrize, 5);
    e.setPrize(_totalPaperPrize, 6); e.setValue(editions, 7); e.setPrize(_bookPaperPrize, 8);

    e = $("printTotalPrize");
    e.setValue(_blackPrintPages, 0); e.setPrize(_blackPrintPrize, 1, null, 4); e.setPrize(_bookBlackPrintPrize, 2);
    e.setValue(_colorPrintPages, 3); e.setPrize(_colorPrintPrize, 4, null, 4); e.setPrize(_bookColorPrintPrize, 5);
    e.setPrize(_bookPrintPrize, 6);

    e = $("pagesTotalPrize");
    e.setPrize(_bookPaperPrize, 0); e.setPrize(_bookPrintPrize, 1); e.setPrize(total, 2);

    // $("hprizeInner").value = total.toCurrency();

    $("pagesTotal").setValue(paperCount("pagesBlack") + paperCount("pagesWhite") + paperCount("pagesColor"));

    return total;
}

function updateCoverPrize() {
    if (!Format.basePaper) return NaN;
    var total = config.cover[$("coverType").value.split('#', 1)[0]].prize[Format.basePaper] + isLaminated() * config.cover.softLamination.prize[Format.basePaper];
    if ($("foil").checked) total += config.special.foil;

    var vorsatzPrice = parseInt($("drpVorsatzPaper").value.split('#', 1)[0]);
    var beltPrice = parseInt($("drpSortingBelt").value.split('#', 1)[0]);

    total += vorsatzPrice;
    total += beltPrice;

    $("pcoverPrize").setPrize(total);
    // $("hprizeCover").value = total.toCurrency();
    return total;
}

function updateDesignPrize() { // Design-Kosten
    var total = 0; if ($("dataType").value.split('#', 1)[0] == "moreInfos") {
        total = config.designPrize[$("bookType").value.split('#', 1)[0]]; var numPhotos = +$("photoCount").value;
        var photoPrize = ($A(config.designPrize.photoTotal).find(function(e) {
            return numPhotos > e.min && numPhotos <= e.max;
        }) || { prize: NaN }).prize;
        total += photoPrize + config.aquisitionPrize.text[$("textDigital").checked ? "digital" : "analog"] + numPhotos * config.aquisitionPrize.photo[$("photoDigital").checked ? "digital" : "analog"];
    }
    var p = $("pdataPrize");
    p[total == 0 ? "hide" : "show"]();
    p.firstChild.data = isNaN(total) ? "Bitte hinterlassen Sie weitere Informationen im Kommentarfeld" : "Preis für Datenannahme und Gestaltung: ";
    if (isNaN(total)) $(p.getElementsByTagName("var")[0]).hide(); else p.setPrize(total);
    return total;
}

//function vatFreeChange() {
//    var element = document.getElementById("pformat_booktype");

//    if (document.getElementById("vatFree").checked)
//        element.style.display = "none";
//    else
//        element.style.display = "block";

//    updatePrize();
//}

function updatePrize() {
    updatePaperThickness();
    var editionCount = parseInt($("editions").value);
    var costsOnce = parseInt(updateDesignPrize() + updatePauschale());
    var costsPerBook = parseInt(updatePaperPrize() + updateCoverPrize() + (costsOnce / editionCount));
    var versand = calc_shipping();

    $("pPriceInfo").setPrize(costsPerBook, 0);

    var total = editionCount * costsPerBook;
    var rabatt = parseInt(parseInt($("rabatt").value.split('#', 1)[0] * 100) / 100 * total);

    if (rabatt > 0) {
        $("pTotal").setPrize(rabatt, 2);
        $("pTotal").setValue(parseInt($("rabatt").value.split('#', 1)[0] * 100) + "%", 1);
        document.getElementById("spanRabatt").style.display = "inline";
    }
    else {
        document.getElementById("spanRabatt").style.display = "none";
    }

    var reducedTotal = total - rabatt;
    reducedTotal += versand;
    var sVat = $("vat").value.split('#', 1)[0].split('_', 1)[0];
    var vat = parseFloat(sVat) / 100 * reducedTotal;
    
    var reducedTotalVAT = reducedTotal + vat;

    total = parseInt(total);
    versand = parseInt(versand);
    vat = parseInt(vat);
    reducedTotalVAT = parseInt(reducedTotalVAT);
    costsPerBook = parseInt(costsPerBook);
    rabatt = parseInt(rabatt);
    reducedTotal = parseInt(reducedTotal);

    $("pTotal").setPrize(total, 0);
    $("pTotal").setPrize(versand, 3);
    $("pTotal").setPrize(reducedTotal, 4);
    $("pTotal").setPrize(vat, 5);
    $("pTotal").setPrize(reducedTotalVAT, 6);

    // set hidden variables to make them available at server side
    $("hBookPrize").value = costsPerBook;
    $("hBookPrizeTotal").value = total;
    $("hPrizeRabatt").value = rabatt;
    $("hPrizeShipping").value = versand;
    $("hPrizeTotal").value = reducedTotal;
    $("hPrizeVAT").value = vat;
    $("hPrizeTotalVAT").value = reducedTotalVAT;
}

Event.observe(window, "load", function() {
    $("jswarn").remove();
    Validator.first = function() { Format.update(); };
    Validator.last = function() { updatePrize(); };
    Validator.run();
    EventSelectors.start(rules);
}, false);

function start_app() {
    $("ppagesTotal").setValue(config.maxThickness.toCurrency(0, "mm", 1), 2);
    updatePrize();
    updatePaperThickness();
    Validator.run();
}

function calc_shipping() {
    /// var f_type = config.paperSize[$("format").value.split('#', 1)[0]].type;
    var f_type = Format.paperType;
    // console.log("f_type: " + f_type);
    var color_paper = config.paperType[$("paperColor").value.split('#', 1)[0]].weight;
    var sw_paper = config.paperType[$("paperBlack").value.split('#', 1)[0]].weight;
    var paper_size = (Format.width / 1000) * (Format.height / 1000);
    var cover_weight = config.cover[$("coverType").value.split('#', 1)[0]].prizes[f_type];
    var color_pages_weight = paperCount("pagesColor") * (paper_size * color_paper);
    var black_pages_weight = (paperCount("pagesBlack") + paperCount("pagesWhite")) * (paper_size * sw_paper);

    var shipping = ((((color_pages_weight + black_pages_weight) / 100) + (cover_weight / 100)) / 10).toFixed(2); // in kg
    var total_shipping_weight = $("editions").value * shipping * 1000; // in g
    $("pBookInfo").setValue(shipping, 1);
    $("hBookWeight").value = shipping;
    $("pBookInfo").setValue2(shipping * parseInt($("editions").value), 2);  
    /*START SHIPPING COST*/

    var shippingCost = 0;
    var sockel = parseInt(document.getElementById("country").value.split('#', 1)[0]);
    if (sockel != -1) // -1 indicates, that there are no shipping costs at all
    {
        shippingCost += sockel;
        var aboveMaxPerKG = parseInt(config.versandkosten.abovePerKG);
        var aboveMaxOnceAdditional = parseInt(config.versandkosten.aboveMaxOnceAdditional);
        
        for (var i = 1; i != -1; i++) {
            if (config.versandkosten.data[i] == undefined) // last entry in data.xml reached, not breaked before
            {
                shippingCost += (aboveMaxOnceAdditional + (total_shipping_weight / 1000) * aboveMaxPerKG);
                break;
            }

            if ((total_shipping_weight >= config.versandkosten.data[i].min) && (total_shipping_weight <= config.versandkosten.data[i].max)) {
                shippingCost += config.versandkosten.data[i].cost;
                break;
            }
        }
    }
    return parseInt(shippingCost);
}
