﻿/// <reference path="jquery-1.4.1-vsdoc.js" />

var shopType;
var maxCirculation;
var hasCover;
var initializing;
var isops;
var init;
var navigateTo;
//var offerevent;
var prevcirc;
var groovehintdisplayed = false;
var designEnabled = false;

$(document).ready(function ()
{
    // Tooltips befüllen
    $('.tooltip').html($('.ToolTipImg').html());

    // ShopTyp auslesen
    if (!shopType)
    {
        shopType = $('.ShopType').html();
    }

    isops = shopType == 2;

    // Konfigurator mit Shoptyp und Produktgruppe initialisieren
    initializing = true;
    Request(shopType, $('.ProductGroup').html(), false);
    init = true;
    Calculate();
    init = false;

    $('.quantity').ForceNumericOnly();
    $('#articleamounttxt').ForceNumericOnly();
    $('.quantity').bind('paste', function (e)
    {
        e.preventDefault();
    });

    //    //$('.quantity').bind('blur focusout', function (event)
    //    $('.quantity').bind('blur', function (event)
    //    {
    //       
    //    });

    $('.quantity').bind('keyup', function (event)
    {
        $('.quantity').css('background-color', null);
        $('div.errorDiv').hide();
        $('div.pricetableDIV').show();

        LockActions();
    });

    // onchange Eventhandler für die Dropdowns
    $('.styleddl, .FinishedSize, .Pages, .DegreeOfColour, .Paper, .Processing, .Perforation').change(function ()
    {
        LockActions();
        Request(shopType, this.value, false);
    });

    $('.PagesCover, .DegreeOfColourCover, .PaperCover').change(function ()
    {
        LockActions();
        Request(shopType, this.value, true);
    });

    $('.Refinement').change(function ()
    {
        var e = $('.Refinement').val() != "0";

        if (e)
        {
            $('#refinementAdditions').slideDown('slow');
        }
        else
        {
            $('#refinementAdditions').hide();
        }

        $('.RefinementType').trigger('change');
    });

    $('.RefinementType, .RefinementPage').change(function ()
    {
        LockActions();

        var e = $('.Refinement').val() != "0";
        var l = $('.RefinementType').val();
        var p = $('.RefinementPage').val();

        var x = $.sync(wsconf + 'UvLacquerChanged', '{e: ' + e + ',l:' + l + ',p:' + p + '}');

        if (x[0] == "error")
        {
            return false;
        }
        
        SetProductionForRefinement($.parseJSON(x[2]));                   

        CalculateResult(x[0]);
    });

    $('.ProductionTime').change(function ()
    {
        LockActions();
        var x = $.sync(wsconf + 'ProductionChanged', '{production: "' + this.value + '"}');
        if (!x || x == "")
        {
            return false;
        }

        var object = $.parseJSON(x);

        $('#ProcessingDate #std').html(object[2][0]);
        $('#ProcessingDate #exp').html(object[2][1]);
        $('#ProcessingDate #nd').html(object[2][2]);

        var mincirc = parseInt(object[0], 10);
        $('.quantityrange').attr('minimumvalue', '' + mincirc + '');
        $('.mincirc').html(mincirc);

        var maxcirc = parseInt(object[1], 10);
        $('.quantityrange').attr('maximumvalue', '' + maxcirc + '');
        $('.maxcirc').html(maxcirc);

        if ($('#ddltext:visible').length == 0)
        {
            if ($('.quantityddl').val() != "0")
            {
                $('.quantity').val($('.quantityddl').val());
            }

            HandleQuantityErrorDisplay(GetCirculation(), true);
        }
        else
        {
            var ddlcirc = parseInt(RemovePoints($('#ddltext').text()), 10);
            if (ddlcirc > maxcirc)
            {
                $('#ddltext').text(maxcirc);
                HandleQuantityErrorDisplay(ddlcirc, true);
            }
        }

        GetEstimatedProductionTime();

        FillTopseller(object[3]);
    });

    $('.Shipping').change(function ()
    {
        LockActions();
        Request(shopType, this.value, false);
    });

    // Service Options
    $('.FileCheckDdl, .ProofDdl, .VoucherDdl, .SponsoringDdl, .ResellerDdl').change(function (e)
    {
        try
        {
            SetService(this.value);
        }
        catch (ex)
        {
            location.reload(true);
        }

        Calculate();
    });

    $('.DeliverySplittingDdl').change(function (e)
    {
        // Lieferauftelung anzeigen wenn eine Lieferaufteilung gewählt wurde
        $('#DeliverySplittingdiv').toggle(this.value != "NOSHPP");

        $('#articleamount').toggle(this.value == "NOSHPP");

        HandleSplittingChangeLogic(this.value);

        if (this.value != "NOSHPP")
        {
            sum();
        }

        Calculate();
    });

    $('a#calculate').click(function () { Calculate });

    $('a#ShoppingCartBtn').click(function (e) { if (AddToCart(e) == true) { ToCart(); } });
    $('a#Checkout').click(function (e) { if (AddToCart(e) == true) { ToCheckOut(); } });
    $('.MyDesignBtnDiv').click(function () { _gaq.push(['_trackEvent', 'Shop', 'Kalkulation', 'KalenderDesigner']); });

    //    $('a#ShoppingCartLayerBtn').click(function (e) { if (AddToCart(e) == true) { ToCart(); } });
    $('a#CheckoutLayer').click(function () { ToCheckOut(); });
    $('a#ShoppingLayer').click(function () { HideLayer(); });
    // $('#MyDesignDivBtn').click(function() { MyDesign });

	$('li.std, li#std').click(function () { $('.ProductionTime').val($('.ProductionTime').children().eq(0).val()).trigger('change'); });
    $('li.exp, li#exp').click(function () { $('.ProductionTime').val($('.ProductionTime').children().eq(1).val()).trigger('change'); });
    $('li.nd, li#nd').click(function () { $('.ProductionTime').val($('.ProductionTime').children().eq(2).val()).trigger('change'); });

    ReleaseActions();

    $.timer(300000, function (timer)
    {
        $.async(wsweb + 'KeepAlive');
        timer.reset(300000);
    });

    $("a.MyDesignBtnInactiveDiv").live("mouseover", function ()
    {
        TagToTip('DesignerHint', ABOVE, 'true', WIDTH, 220, CENTERMOUSE, 'true', OFFSETX, 0, OFFSETY, 20, FADEIN, 300, FADEOUT, 300);
    });
    $("a.MyDesignBtnInactiveDiv").live("mouseout", function ()
    {
        UnTip();
    });

    /// Start: Topseller (neu) 15.08.2011) - Funktionen
    $("#ddlcontent li").live("click", function ()
    {
        $('#netSPAN').html('');
        $('#vatSPAN').html('');
        $('#finalPriceSPAN').html('');
        $('#ddltext').text($(this).text());
        $(".outsideclick").remove();
        $("#ddlcontent").hide();
        $('#ddltext').css('background-color', null);
        Calculate();

        var num = RemovePoints($(this).text());

        $.sync(wsconf + 'SetCirculation', '{circulation: ' + num + '}');
        GetEstimatedPackageWeight();

    });

    $("#quantityddlbtn, #ddltext").click(function ()
    {
        $('body').append("<div class='outsideclick'></div>");
        $(".outsideclick").height($('body').height());
        $("#ddlcontent").show();
    });

    $(".outsideclick").live("click", function ()
    {
        $(".outsideclick").remove();
        $("#ddlcontent").hide();
    });
    /// Ende: Topseller (neu) 15.08.2011) - Funktionen

    // Für IE8, IE7 und IE6 => siehe Bug 0010162
    $(".ResellerDdl").val("SHPSXP");
});

function quantityblur(e)
{
    var num = parseInt(RemovePoints(e), 10);

    if (HandleQuantityErrorDisplay(num) == false)
    {
        return;
    }

    $.sync(wsconf + 'SetCirculation', '{circulation: ' + num + '}');

    if (SplittingSelected() == true)
    {
        $('.totalamount').html(num);
        sum();
    }

    GetEstimatedPackageWeight();
    blur = true;
}

function HandleQuantityErrorDisplay(q, isddl)
{
    if (isddl == true)
    {
        q = RemovePoints(q);
    }

    $('div.pricetableDIV').show();
    $('div.errorDiv').hide();
    if (isNaN(q) || q < parseInt($('.quantityrange').attr('minimumvalue'),10))
    {
        $('.quantity').val($('.quantityrange').attr('minimumvalue'));
        $('div.errorMsg').html(GetMaxCirculationText());
        $('div.pricetableDIV').hide();
        $('div.errorDiv').show();

        $('.quantity').css('background-color', '#ffd482');
        $('#ddltext').css('background-color', '#ffd482');

        return false;
    }
    else if (q > parseInt($('.quantityrange').attr('maximumvalue'),10))
    {
        $('div.errorMsg').html(GetOverMaxCirculationText());
        $('div.pricetableDIV').hide();
        $('div.errorDiv').show();

        $('.quantity').css('background-color', '#ffd482');
        $('#ddltext').css('background-color', '#ffd482');
        $('.quantity').val($('.quantityrange').attr('maximumvalue'));
             
        return false;
    }

    $('.quantity').css('background-color', null);
    $('#ddltext').css('background-color', null);
    $('div.errorDiv').hide();
    $('div.pricetableDIV').show();
    $('a#calculate').bind('click', null, Calculate);
    return true;
}

function ToCheckOut()
{
    _gaq.push(['_trackEvent', 'Shop', 'Kalkulation', 'Direkt zur Kasse']);
    var to = new String(navigateTo);
    var v = to.split(/;/);
    Navigate(v[0]);
}

function ToCart()
{
    _gaq.push(['_trackEvent', 'Shop', 'Kalkulation', 'In den Warenkorb']);
    var to = new String(navigateTo);
    var v = to.split(/;/);
    Navigate(v[1]);
}

function GetMaxCirculationText()
{
    var org = $('#WrongImpostError .org').html();
    var text = org.replace(/\{0\}/g, $('.mincirc').html()).replace(/\{1\}/g, $('.maxcirc').eq(0).html());    
    return text;
}

function GetOverMaxCirculationText()
{
    var org = $('#OverMaxImpostError .org').html();
    var text = org.replace(/\{0\}/g, $('.maxcirc').eq(0).html());
    return text;
}

function HandleOPSDisplay(isops)
{
    $('.processing_div #Perforationdiv').toggle(!isops);
    $('#Coverdiv').toggle(!isops);
    $('#Pagesdiv').toggle(!isops);
    $('#Colordiv').toggle(!isops);
    $('#stylediv').toggle(!isops);
    $('#Sizediv').toggle(!isops);
    $('#FileCheck').toggle(!isops);
    $('#Sponsoring').toggle(!isops);
    $('#Proof').toggle(!isops);
}

// Sperrt den Warenkorb und Meindesign Button
function LockActions()
{
    $('.offerDIV').block({ message: null }).css('visibility', 'hidden');
    $('#netSPAN,#vatSPAN,#finalPriceSPAN').css('visibility', 'hidden');
    $('#PointsSpan').html("--");
	$('.discountRow').hide();
    $('a#ShoppingCartBtn').unbind('click').hide();
    $('#Checkout').unbind('click').hide();
    $('a#calculate').bind('click', null, Calculate).show();
}

// Gibt den Warenkorb und Meindesign wieder frei
function ReleaseActions()
{
    $('.offerDIV').unblock().css('visibility', 'visible');
    $('#netSPAN,#vatSPAN,#finalPriceSPAN').css('visibility', 'visible');
    $('a#ShoppingCartBtn').show().bind('click', null, function (e) { if (AddToCart(e)) { ToCart(); } });
    $('#Checkout').show().bind('click', null, function (e) { if (AddToCart(e) == true) { ToCheckOut(); } });
    $('a#calculate').unbind('click').hide();
}

function HksIsValid()
{
    var conhk1 = $('#ContentPagesHks1Ddl');
    var conhk2 = $('#ContentPagesHks2Ddl');
    var covhk1 = $('#CoverPagesHks1Ddl');
    var covhk2 = $('#CoverPagesHks2Ddl');

    if (conhk1.is(':visible') && conhk1.val() == "0")
    {
        return false;
    }

    if (conhk2.is(':visible') && conhk2.val() == "0")
    {
        return false;
    }

    if (covhk1.is(':visible') && covhk1.val() == "0")
    {
        return false;
    }

    if (covhk2.is(':visible') && covhk2.val() == "0")
    {
        return false;
    }
    
    return true;
}

function GetHksValue(element)
{
    if (element.is(':visible') == false)
    {
        return null;
    }

    return element.val();
}

// Aktuelles Produkt in den Warenkorb transferieren
function AddToCart(evnt)
{
    // Econda 
    try {
        var send = '{trimmedSize: "' + $(".FinishedSize").val() + '",pages: "' + $(".Pages").val() + '",paper: "' + $(".Paper").val() + '",productType: "' + $(".ProductGroup").html() + '"}';
        CartTrek($.sync(wsconf + 'GetArticleProperties', send));
    }
    catch (ex) {
        if (console != undefined) console.log(ex);
    }

    //mehrmaliges auslösen des Events verhindern
    evnt.stopImmediatePropagation();

    // Auf gültige Lieferaufteilung prüfen
    if (SplittingSelected() == true && (IsValidSplittingInput() == false || IsValidSplittingSum() == false))
    {
        $('div.errorMsg').html($('.splittingerror').html());
        $('div.pricetableDIV').hide();
        $('div.redx').show();
        $('div.errorDiv').show();       
        return false;
    }

    $('div.errorDiv').hide();
    $('div.redx').hide();
    $('div.pricetableDIV').show();

    if (HksIsValid() == false)
    {
        $('div.errorMsg').html($('#HksError').html());
        $('div.pricetableDIV').hide();
        $('div.errorDiv').show();
		$('div.errorCross').show();

        return false;
    }

    var hks = '{content1:' + GetHksValue($('#ContentPagesHks1Ddl')) + ',content2:' + GetHksValue($('#ContentPagesHks2Ddl')) + ',cover1:' + GetHksValue($('#CoverPagesHks1Ddl')) + ',cover2:' + GetHksValue($('#CoverPagesHks2Ddl')) + '}'

    // In den Warenkorb
    var x = $.sync(wsconf + 'AddToShoppingCart', hks);
    if (x == "error" || x == "")
    {
        alert('error');
        location.reload(true);
    }

    var ac = new Number($('#ac').text());
    ac++;
    $('#ac').text(ac);

    navigateTo = x;

    return true;
}
// Econda
function CartTrek(o) {
    if (o == null || window.emosPropertiesEvent == undefined) return;
    eTrek('c_add', o, false);
}

// Trekking-Methode für Econda
function eTrek(t, o, b) {
	var v = $('#finalPriceSPAN').html();
    var price = 0.00;
    if (v != '' && v != 'NaN') {
        price = parseFloat(v.replace(/[^0-9]/g, ''));
        price = price / 100;
    }
    var pageId = $("#EcondaHelperPageId").html();
    var content = $("#EcondaHelperContent").html();
    var langId = $("#EcondaHelperLangId").html();
    var sideId = $("#EcondaHelperSideId").html();
    var emospro = {};
    emospro.content = content;
    emospro.pageId = pageId;
    emospro.siteid = sideId;
    emospro.langid = langId;
    emospro.countryid = sideId;
    emospro.ec_Event = [
            [t, o.Format, o.ProductType, price.toString(), o.ProductType, '1', GetCirculation().toString(), o.NumberOfPages, o.Paper]
        ];
    if (b) emospro.Target = [['Kalkulatoren', o.ProductType, '1', 'a']];
    window.emosPropertiesEvent(emospro);
}

// speichert den Service in der Session
function SetService(article)
{
    try
    {
        //Syncron wegen evtl überschneidung
        var x = $.sync(wsconf + 'SetService', '{articleNumber: "' + article + '"}');
        HandleCalendarDesign(x);
}
    catch (ex)
    {
        location.reload(true);
    }
}

function HandleCalendarDesign(value)
{
    designEnabled = value != null ? value : false;
    var el = $("div.ctbbuttons div.buttontable a");
    if (designEnabled == true)
    {
        el.removeClass();
        el.addClass("MyDesignBtnDiv");        
    } 
    else
    {
        el.removeClass();
        el.addClass("MyDesignBtnInactiveDiv");        
    }
}

// berechnet den aktuellen Preis.
function Calculate()
{
    $('.quantity').css('background-color', null);
    if (SplittingSelected() == true && (IsValidSplittingInput() == false || IsValidSplittingSum() == false))
    {
        $('div.errorMsg').html($('.splittingerror').html());
        $('div.pricetableDIV').hide();
        $('div.redx').show();
        $('div.errorDiv').show();      
        return;
    }

    $('#ddltext').css('background-color', null);
    $('div.errorDiv').hide();
    $('div.redx').hide();
    $('div.pricetableDIV').show(); 

    try
    {
        var send = '{circulation: "' + GetCirculation() + '"}';
        if (!init) {
            // Econda
			$.async(wsconf + 'Calculate', send, CalculateResult);
            var blub = '{trimmedSize: "' + $(".FinishedSize").val() + '",pages: "' + $(".Pages").val() + '",paper: "' + $(".Paper").val() + '",productType: "' + $(".ProductGroup").html() + '"}';
            $.async(wsconf + 'GetArticleProperties', blub, CalcTrek);
            //var value = $.sync(wsconf + 'Calculate', send);
        }
        else
        {
            $.async(wsconf + 'InitialCalculate', send, CalculateResult);
            //var value = $.sync(wsconf + 'InitialCalculate', send);
        }
    }
    catch (ex)
    {
        location.reload(true);
    }
}

function CalculateResult(value)
{
        if (value == "" || value == "error")
        {

        //location.reload(true);
            return;
        }

        var price = $.parseJSON(value);
        // alert(price.error);
        $('div.productpreview').show();
        $('#netSPAN').html(price.n);
        $('#vatSPAN').html(price.v);
        $('#finalPriceSPAN').html(price.g);
        $('#PointsSpan').html(price.p);
		
		if (price.dp && price.dp != "(0%)")
		{
		    $('#discountSPAN').html(price.dv);
		    //$('#percentSPAN').html(price.dv);
		    $('.discountRow').show();
        }
		
        ReleaseActions();

    }
    // Econda
    function CalcTrek(o) {
        if (o == null || window.emosPropertiesEvent == undefined) return;
        eTrek('view', o, true);
    }

// Liest die aktuelle Auflage aus.
function GetCirculation()
{
    var quantityTxt = $('.quantity');
    var topsellerDdl = $('#ddltext');

    if (quantityTxt.is(':hidden'))
    {
        var topseller = RemovePoints(topsellerDdl.text());        
        if (topseller == "0")
        {
            topsellerDdl.text("1000")
            return 1000;
        }

        return topseller;
    }
    else
    {
        var x = TryParseInt(RemovePoints(quantityTxt.val()), null);
        if (!x)
        {
            return 1000;
        }

        return x;
    }
}

// Gibt die zahl oder den Standardwert zurück
function TryParseInt(str, defaultValue)
{
    var retValue = defaultValue;
    if (str != null && str.length > 0 && !isNaN(str))
    {
        retValue = parseInt(str);
    }

    return retValue;
}

// Anfrage für die Konfiguration
function Request(shopType, value, isCover)
{
    $.blockUI({ overlayCSS: { backgroundColor: '#fff', opacity: 0, cursor: 'wait'} });
    var send = '{shopType: "' + shopType + '", changedValue: "' + value + '", isCover: "' + isCover + '" }';
    var value = $.sync(wsconf + 'GetConfiguration', send);

    if (value == "error")
    {
        //location.reload(true); <-- funktioniert hier nicht
        __doPostBack('');
        return;
    }

    FillLists($.parseJSON(value)); //JQuery 1.41
    $.unblockUI();
}

function FillHksDdl(element,l, select)
{
    element.children().remove();

    if (select)
    {
        AO(element, true, false, '0', selection);
                
        for (var i = 0; i < hksColors.length; i++)
        {
            if (select == hksColors[i] + ' ' + l)
            {
                AO(element, true, true, hksColors[i], hksColors[i] + ' ' + l);
            }
            else
            {
                AO(element, true, false, hksColors[i], hksColors[i] + ' ' + l);
            }
        }
    }
    else
    {
        AO(element, true, true, '0', selection);

        for (var i = 0; i < hksColors.length; i++)
        {
            AO(element, true, false, hksColors[i], hksColors[i] + ' ' + l);
        }
    }
}

// Konfigurationsergebnis verarbeiten
function FillLists(object)
{
    // Cover
    HandleCoverDisplay(object.c);

    // Initialauflage
    if (object.ic)
    {
        $('.quantity').val(RemovePoints(object.ic));
        $('#ddltext').text(object.ic);
    }

    if (object.mc)
    {
        $('.maxcirc').html(object.mc);
        $('.quantityrange').attr('maximumvalue', '' + object.mc + '');
    }
        
    $('.mincirc').html(object.mic);
    $('.quantityrange').attr('minimumvalue', '' + object.mic + '');
    HandleQuantityErrorDisplay(GetCirculation());    

    // Topseller
    FillTopseller(object.t);

    if (initializing)
    {
        // Style
        if (object.s && !isops)
        {
            SetStyle(object.s);
        }
        else
        {
            $('#stylediv').addClass('hidden');
        }
    }

    HandleCalendarDesign(object.a);

    if (object.uv)
    {
        $('div.refinement_div').toggle(object.uv);
    }
    
    //Dropdowns
    FillDropdowns(object.l, false);

    FillRefinement(object.re);
    
    if (object.pww === true)
    {        
        if (groovehintdisplayed == false)
        {
            TagToTip('GrooveHint', WIDTH, 346, BORDERWIDTH, 0, PADDING, 0, FIX, ['Paperdiv', 40, -20], FADEIN, 300, FADEOUT, 150, EXCLUSIVE, true, STICKY, true);
        }        
        groovehintdisplayed = true;
    }

    // Serviceoptionen Dropdowns
    if (object.v)
    {
        // Serviceoptionen eintragen
        FillDropdowns(object.v, true);

        // Basisdatencheck
        $('.FileCheckDdl').children().eq(0).text($('#basedc').text());
        // kein Korrekturabzug
        $('.ProofDdl').children().eq(0).text($('#noproof').text());
        // kein Belegexemplar
        $('.VoucherDdl').children().eq(0).text($('#novoucher').text());
        // kein Sponsoring
        $('.SponsoringDdl').children().eq(0).text($('#nosponsoring').text());
        // standard Absendeaddresse
        AO($('.ResellerDdl'), false, true, 'SHPSXP', $('#sxpadress').text());
        
        // Lieferaufteilung anlegen
        $('.DeliverySplittingDdl').children().remove();
        AO($('.DeliverySplittingDdl'), true, true, 'NOSHPP', $('#nosplitting').text());

        for (var i = 2; i <= 10; i++)
        {
            AO($('.DeliverySplittingDdl'), true, false, i, i + ' ' + $('#moresplitting').text());
    }
    }

    if (object.h)
    {
        var conhk1 = $('#ContentPagesHks1Ddl');
        var conhk2 = $('#ContentPagesHks2Ddl');
        var covhk1 = $('#CoverPagesHks1Ddl');
        var covhk2 = $('#CoverPagesHks2Ddl');

        var conhk1lbl = $('#ContentPagesHks1Lbl');
        var conhk2lbl = $('#ContentPagesHks2Lbl');
        var covhk1lbl = $('#CoverPagesHks1Lbl');
        var covhk2lbl = $('#CoverPagesHks2Lbl');
        
        conhk1.toggle(object.h.ccon == 1 || object.h.ccon == 2);
        conhk2.toggle(object.h.ccon == 2);
        conhk1lbl.hide(object.h.ccon == 0);
        conhk2lbl.hide(object.h.ccon == 0);

        covhk1.toggle(object.h.ccov == 1 || object.h.ccov == 2);
        covhk2.toggle(object.h.ccov == 2);
        covhk1lbl.hide(object.h.ccon == 0);
        covhk2lbl.hide(object.h.ccon == 0);

        if (object.h.ccon == 1)
        {
            FillHksDdl(conhk1, object.h.lcon, object.h.scon1);
            conhk1.width(268);
            conhk1lbl.show();
            conhk2lbl.hide();
        }
        else if (object.h.ccon == 2)
        {
            FillHksDdl(conhk1, object.h.lcon, object.h.scon1);
            FillHksDdl(conhk2, object.h.lcon, object.h.scon2);
            conhk1.width(134);
            conhk2.width(134);
            conhk1lbl.hide();
            conhk2lbl.show();
        }

        if (object.h.ccov == 1)
        {
            FillHksDdl(covhk1, object.h.lcov, object.h.scov1);
            covhk1.width(268);
            covhk1lbl.show();
            covhk2lbl.hide();
        }
        else if (object.h.ccov == 2)
        {
            FillHksDdl(covhk1, object.h.lcov, object.h.scov1);
            FillHksDdl(covhk2, object.h.lcov, object.h.scov2);
            covhk1.width(134);
            covhk2.width(134);
            covhk1lbl.hide();
            covhk2lbl.show();
        }
    }

    GetEstimatedPackageWeight();

    if (initializing == true)
    {
        GetEstimatedProductionTime();
    }

    if (object.p)
    {
        $('#perma').html(object.p);
    }

    initializing = false;
}

// Umschlag ein oder aus-blenden
function HandleCoverDisplay(value)
{
    $('span.cover').toggle(value == 0);
    $('.cover').toggleClass('hidden', value == 0);
    $('#ContentHeader').toggle(value == 1);
    $('.nocover').toggleClass('hidden', value == 1);

    hasCover = value != 0;
}

// Topseller auflagen eintragen
function FillTopseller(list)
{
    // vorher leeren für Neubefüllung
    $('#ddlcontent').html('');

    $('.txtinput').toggle(list == null);
    $('.ddlinput').toggle(list != null);

    if (list)
    {
        var count1 = (Math.ceil(list.length / 3));        
        var count2 = count1 * 2;
        
        
        var ul1html = "<div><ul class='top1'>";
        for (var i = 0; i < count1; i++)
        {
            ul1html += "<li>" + list[i] + "</li>";
        }
        ul1html += "</ul>";

        var ul2html = "<ul class='top2'>";
        for (count1; count1 < count2; count1++)
        {
            ul2html += "<li>" + list[count1] + "</li>";
        }
        ul2html += "</ul>";

        var ul3html = "<ul class='top3'>";
        for (count2; count2 < list.length; count2++)
        {
            ul3html += "<li>" + list[count2] + "</li>";
        }
        ul3html += "</ul><div class='clear'></div></div>";

        html = ul1html + ul2html + ul3html

        $('#ddlcontent').html(html);        

    }


















//    var quantityddl = $('.quantityddl');
//    var oldval = $('.quantityddl').val();
//    quantityddl.children().remove();
//    var foundvalue = false;

//    for (var t = 0; t < list.length; t++)
//    {
//        var selected = list[t].v == oldval;
//        if (selected && oldval != "0")
//        {
//            foundvalue = true;
//        }

//        AO(quantityddl, true, selected, list[t].v, list[t].t);
//    }
}

// Produktausführungen eintragen
function SetStyle(list)
{
    $('#stylediv').toggleClass('hidden', list == null);
    var style = $('.styleddl');

    if (!list)
    {
        return;
    }

    style.children().remove();
    for (var s = 0; s < list.length; s++)
    {
        AO(style, true, list[s].s, list[s].v, GetText(list[s].v));
    }
}

// Mein Design Button ein oder aus-blenden
function HandleMyDesignDisplay(value)
{
    if (!value)
    {
        $('#MyDesign').hide();
        return;
    }

    $('#MyDesign').toggle(value == 1);
}

// Konfigurations Dropdowns füllen
function FillDropdowns(lists, isService)
{
    // list = Eine Liste mit mehreren Listen von Dropdown Inhalten
    for (var i = 0; i < lists.length; i++)
    {
        // currentList Ein Dictionary (Key,Value) mit Werten für ein Dropdown -> Value = Liste mit Artikelnummern
        var currentList = lists[i];

        if (currentList.Key == "ProductionTime")
        {
            var nextday = false;
            var express = false;
            for (var c = 0; c < currentList.Value.length; c++)
            {
                if (currentList.Value[c].v == "PRDEXP")
                {
                    nextday = true;                    
                }

                if (currentList.Value[c].v == "PRDRSH") 
                {
                    express = true;                    
                }
            }

            $('#ProcessingDate .nd').toggle(nextday);
            $('.confvalue #nd').toggle(nextday);
            $('.ttul').children().eq(2).toggle(nextday);

            $('#ProcessingDate .exp').toggle(express);
            $('.confvalue #exp').toggle(express);
            $('.ttul').children().eq(1).toggle(express);
        }

        // Elemente löschen
        var dropDown = $('.' + (isService ? 'so' : '') + currentList.Key);
        dropDown.children().remove();

        var valueList = new Array();
        for (var b = 0; b < currentList.Value.length; b++)
        {
            var element = currentList.Value[b];
            if (isService && b == 0)
            {
                AO(dropDown, true, true, element.v, GetText(element.v));
            }
            else
            {
            AO(dropDown, true, element.s, element.v, GetText(element.v));
        }
        }

        if (isService == false)
        {
            if (currentList.Value.length <= 1)
            {
                dropDown.attr('disabled', 'disabled');
            }
            else
            {                
                dropDown.attr('disabled', null);
            }
        }
    }
    }

// AO = Options an ein Dropdown anhängen
// dropdown, append, selected, value, text
function AO(e, a, s, v, t)
{
    var c = $("<option" + (s === 1 || s === true ? " selected='selected'" : "") + "></option>").val(v).html(t);
    if (a == true) { e.append(c); }
    else { e.prepend(c); }
        }

// text aus Cache auslesen
function GetText(x) { for (var i = 0; i < cache.length; i++) { if (cache[i].Key == x) { return cache[i].Value; } } return "notfound"; }

function SetProductionForRefinement(list)
{    
    var dropDown = $('.ProductionTime');
    dropDown.children().remove();

    var valueList = new Array();
    for (var b = 0; b < list.length; b++)
    {
        var element = list[b];
        AO(dropDown, true, element.s, element.v, GetText(element.v));
    }

    if (list.length <= 1)
    {
        dropDown.attr('disabled', 'disabled');
    }
    else
    {
        dropDown.attr('disabled', null);
    }

    var nextday = $('.ProductionTime option[value="PRDEXP"]').length > 0;
    var express = $('.ProductionTime option[value="PRDRSH"]').length > 0;

    $('#ProcessingDate .nd').toggle(nextday);
    $('.confvalue #nd').toggle(nextday);
    $('.ttul').children().eq(2).toggle(nextday);

    $('#ProcessingDate .exp').toggle(express);
    $('.confvalue #exp').toggle(express);
    $('.ttul').children().eq(1).toggle(express);
}

function FillRefinement(ref)
{
    if (ref == null || ref == 'undefined')
    {
        $('.refinement_div').hide();
        return false;
    }

    $('.refinement_div').show();

    $('.Refinement').children().remove();
    $('.RefinementType').children().remove();
    $('.RefinementPage').children().remove();

    for(var i = 0; i<refinement.length;i++)
    {
        if ($.inArray(refinement[i].Key, ref.rt) != -1)
        {
            AO($('.Refinement'), true, false, refinement[i].Key, refinement[i].Value);
        }
    }

    for (var j = 0; j < lacquer.length; j++)
    {
        if ($.inArray(lacquer[j].Key, ref.uvt) != -1)
        {
            AO($('.RefinementType'), true, false, lacquer[j].Key, lacquer[j].Value);
        }
    }    

    for (var k = 0; k < refPage.length; k++)
    {
        if ($.inArray(refPage[k].Key, ref.rp) != -1)
        {
            AO($('.RefinementPage'), true, false, refPage[k].Key, refPage[k].Value);
        }
    }

    if (ref.ds)
    {
        $('.Refinement').val(ref.ds[0]);

        $('#refinementAdditions').slideDown('slow');

        $('.RefinementType').val(ref.ds[1]);
        $('.RefinementPage').val(ref.ds[2]);        
    }
    else
    {
        $('#refinementAdditions').hide();
    }

    if ($('.RefinementType').children().length <= 1)
    {
        $('.RefinementType').attr('disabled', 'disabled');
    }
    else
    {
        $('.RefinementType').attr('disabled', null);
    }

    if ($('.RefinementPage').children().length <= 1)
    {
        $('.RefinementPage').attr('disabled', 'disabled');
    }
    else
    {
        $('.RefinementPage').attr('disabled', null);
    }

    if (ref.p)
    {
        SetProductionForRefinement(ref.p);
    }
}

function RefreshBlock()
{
    $('.properties').block(
    {
        message: $('img.displayBox'),
        css: {
            top: ($(window).height() - 500) / 2 + 'px',
            left: ($(window).width() - 500) / 2 + 'px',
            width: '26px',
            height: '26px',
            border: '0px',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5
        },
        overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.6 }
    });
}

function Unblock() { $('.properties').unblock(); }
function IsAllowedInputKey(keycode) { return IsNumeric(keycode) || keycode == 0; }
function IsNumeric(keycode) { return (keycode > 47 && keycode < 58) || (keycode > 95 && keycode < 106); }

// splitting.js //
var splittingInitialized;

// Gibt an ob Lieferaufteilung gewählt ist.
function SplittingSelected() { return $('.DeliverySplittingDdl').val() != "NOSHPP"; }

// Anzahl der vorhanden Lieferaufteiungen
function PartCount() { return parseInt($('.DeliverySplittingDdl').val(), 10); }

// Gibt die Gesamtauflage anhand der aktuellen Auflage zurück
function TotalAmount() { return GetCirculation(); }

// Gibt an ob die Lieferungsaufteilung gültige eingaben hat
function IsValidSplittingInput()
{
    var valid = new Boolean(true);

    // Alle Lieferaufteilungs Eingabefelder
    $(".value").each(function (i, e)
{
        var number = new Number(parseInt(e.value, 10));

        // Check for invalid splittings
        if (isNaN(number) || number == 0)
        {
            valid = false;
}
    });

    return valid;
}

// Gibt ob die Lieferauteilung eine gültige Gesamtsumme hat
function IsValidSplittingSum()
{
    var s = new Number();
    $(".value").each(function (i, e)
    {
        var number = new Number(parseInt(e.value, 10));
        s += number;
    });

    return s == TotalAmount();
}

// Anzeigen des OK Button
function ShowOk(element) { $(element.parentNode).addClass("selected"); }

// ausblenden des OK Button
function HideOk(element) { $(element.parentNode).removeClass("selected"); sum(); }

// Initialisiert oder ändert die Aufteilung der Lieferaufteilung
function HandleSplittingChangeLogic(value)
{
    // Prüfen ob die Lieferauteilung schon initialisiert wurde
    if (splittingInitialized == undefined ||
            splittingInitialized == null ||
            splittingInitialized == false)
    {
        // bisher wurde keine Lieferauteilung gewählt - Initialisiere die Lieferauteilung mit der gewählten Anzahl
        var number = new Number(parseInt(value, 10));
        if (number == 2)
        {
            splittingInitialized = true;

            SetService(value);

        return;
    }

        SetService(value);
        AddParts(number - $('.part').length);
        splittingInitialized = true;

        return;
}

    // Die Lieferung ist initialisiert

    SetService(value);

    // Die Lieferauteilung wurde wieder entfernt
    if (value == "NOSHPP")
{
        return;
}

    // Die Aufteilung wurde geändert
    var number = new Number(parseInt(value, 10));
    if (number > $('.part').length)
{
        // füge weitere Aufteilungen hinzu
        AddParts(number - $('.part').length);
}
    else
{
        // entferne Aufteilungen
        RemoveParts($('.part').length - number);
    }
}

// fügt eine neue Lieferaufteilung hinzu
function AddParts(count)
{
    var partcount = new Number($('.part').length);
    for (var i = 1; i <= count; i++)
    {
    // Element Clonen
    var element = $(".part:last").clone(true);

    // Id neu setzen
        element[0].id = "p" + (partcount + i);

    // Element nach letztem einfügen
        $(".part:last").after(element).after("<div class='clear'></div>");

    // Lieferaufteilung Text setzen
        $(".part:last .splittingtext").html($(".parttext").html() + "&nbsp;" + (partcount + i) + ":");
}
}

function RemoveParts(count)
{
    for (var i = 0; i < count; i++)
    {
        $(".part:last").remove();
    }
}

$(document).ready(function ()
{
    // Nur Zahleneingaben bei Lieferaufteilung zulassen
    $('input.value').ForceNumericOnly();
    //    $('input.value').keydown(function(e)
    //    {
    //        if (IsValidKey(e.keyCode) == false)
    //        {
    //            e.preventDefault();
    //        }
    //    });

    // Text (Lieferung)
    var content = $('.parttext').html();

    // Alle Teillieferungen mit Text befüllen
    $('span.splittingtext').each(function (i, e) { $(e).html(content + '&nbsp;' + (i + 1) + ':'); });
});

//function IsValidKey(keyCode)
//{
//    //     backspace       tabl            del              numbers                              keypad
//    return keyCode == 8 || keyCode == 9 || keyCode == 46 || (keyCode >= 48 && keyCode <= 57) || (keyCode >= 96 && keyCode <= 105);
//}

function sum(el)
    {
    var s = new Number();
    $(".value").each(function (i, e)
    {
        var number = new Number(parseInt(e.value, 10));
        if (isNaN(number))
        {
            number = 0;
    }
        s += number;
    });

    $("#remaining").text(TotalAmount() - s);

    // Wenn die Eingabe ungültig ist oder die Gesamtsumme nicht stimmt wird ein Fehler angezeigt
    if (IsValidSplittingInput() == false || IsValidSplittingSum() == false)
    {
        $('div.errorMsg').html($('.splittingerror').html());
        $('div.pricetableDIV').hide();
        $('div.redx').show();
        $('div.errorDiv').show();     
        return;
        }

    $('div.errorDiv').hide();
    $('div.redx').hide();
    $('div.pricetableDIV').show();  

    SendSplitting();

    if (el)
        {
        Calculate();
        }
    }

function SendSplitting()
    {
    var send = '{splittings:[';

    $('.value').each(function (i, e)
        {
        send += e.value;
        if (i < $('.value').length - 1)
            {
                send += ',';
            }
    });

        send += ']}';

    var r = $.sync(wsconf + 'SetSplitting', send);

    if (r == "x")
        {
        // Fehlerhafte Lieferaufteilung
            location.reload(true);
            return;
        }
    else if (r == "noconf")
        {
        // Session ist abgelaufen
        location.reload(true);
            return;
        }
}

function GetEstimatedProductionTime()
    {
    $.async(wsconf + 'GetEstimatedCompletionDate', null, function (r)
    {
        if (r)
        {
            $('#ProcessingDate #std').html(r[0]);
            $('#ProcessingDate #exp').html(r[1]);
            $('#ProcessingDate #nd').html(r[2]);
    }
    });
}

function GetEstimatedPackageWeight()
{
    $.async(wsconf + 'GetEstimatedWeight', null, function (r)
    {
        if (r)
        {
            $('#Weight #piece').html(r[0]);
            $('#Weight #total').html(r[1]);
        }
    });
    }

function DisplayProductDetails()
        {
    $.async(wsconf + 'GetProductDetails', null, function (r)
    {
        var o = $.parseJSON(r);

        $('#illurl').html(o.illurl);
        $('#indurl').html(o.indurl);
        $('#phourl').html(o.phourl);
        $('#pdfurl').html(o.pdfurl);

        $('#pw').html(o.pw);
        $('#fsp').html(o.fsp);
        $('#fswgp').html(o.fswgp);
        $('#fsm').html(o.fsm);
        $('#fswgm').html(o.fswgm);
    });
}

function RemovePoints(value)
{    
    var val = new String(value);
    val = val.replace(/[^0-9]/g, "");     
    return val;
}

// Numeric only control handler
jQuery.fn.ForceNumericOnly =
function ()
{
    return this.each(function ()
    {
        $(this).keydown(function (e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 ||
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

