﻿
var cache;
var shopType;
var maxCirculation;
var hasCover;
var initializing;
var isops;
var init;
//var offerevent;

function pageLoad()
{
    $('#loader').html('lädt');
    LoadCache();
}

$(document).ready(function() {
    $('.tooltip').html($('.ToolTipImg').html());

    // initiale Anzeige der Buttons
    $(".choosePropertiesTR").hide();
    $(".chooseServiceTR").show();

    // Textcache laden
    if (!cache) { LoadCache(); }

    // ShopTyp auslesen
    if (!shopType) { shopType = $('.ShopType').html(); }
    isops = shopType == 2;
    HandleOPSDisplay(isops);

    // Konfigurator mit Shoptyp und Produktgruppe initialisieren
    initializing = true;
    Request(shopType, $('.ProductGroup').html(), false);
    init = true;
    Calculate();
    init = false;

    $('#QuantityDet').html($('.quantity').val());

    $('.quantity').ForceNumericOnly();
    $('.quantity').bind('paste', function(e) {
        e.preventDefault();
    });

    $('.quantity').keyup(function(event) {
        if (event.keyCode == 13) {
            OnQuantityChanged(this);
        }
    });

    $('.quantity').blur(function() {
        OnQuantityChanged(this);
    });
    
    $('.quantity').focus(function() {
        $('.quantity').css('background-color', null);
        $('#OverMaxCirculationText').hide();
    });

    function OnQuantityChanged(q) {
        LockActions();
        if (q.value == "" && $('.quantityddl').val() == "0") {
            $('#MaxCirculationText').show();
            return;
        }

        if (isNaN(q.value)) {
            $('#MaxCirculationText').show();
            return;
        }

        $('.quantityddl').val("0");
        var c = parseInt(q.value, 10);

        if (c < 1) {
            $('#MaxCirculationText').html(GetMaxCirculationText());
            $('#MaxCirculationText').show();
            $('.quantity').css('background-color', '#ffd482');
            $('.quantity').val('1');
            $('#OverMaxCirculationText').hide();
            return;
        }
        else if (c > $('.quantityrange').attr('maximumvalue')) {
            $('#OverMaxCirculationText').html(GetOverMaxCirculationText());
            $('#OverMaxCirculationText').show();
            $('.quantity').css('background-color', '#ffd482');
            $('.quantity').val($('.quantityrange').attr('maximumvalue'));
            $('#MaxCirculationText').hide();
            return;
        }

        $('.quantity').css('background-color', null);
        $('#MaxCirculationText').hide();
        $('#OverMaxCirculationText').hide();
        $('#QuantityDet').html(c);
        $('.totalamount').html(c);
        sum();
    }

    $('.quantityddl').change(function() {
        LockActions();
        $('#MaxCirculationText').hide();
        $('#OverMaxCirculationText').hide();
        if (this.value == "0") {
            $('.quantity').val($('.quantity')[0].defaultValue);
            $('#QuantityDet').html($('.quantity')[0].defaultValue);
            return;
        }

        $('.quantity').val("");
        $('.quantity').css('background-color', null);
        $('#QuantityDet').html(this.value);
        $('.totalamount').html(this.value);
        sum();
    });

    // onchange Eventhandler für die Dropdowns
    $('.styleddl, .FinishedSize, .Pages, .DegreeOfColour, .Paper, .Processing, .Perforation').change(function() {
        HandleMyDesignBtn();
        LockActions();
        Request(shopType, this.value, false);
    });

    $('.PagesCover, .DegreeOfColourCover, .PaperCover').change(function() {
        LockActions();
        Request(shopType, this.value, true);
    });

    $('.ProductionTime').change(function() {
        LockActions();
        var send = '{production: "' + this.value + '"}';
        var x = CoreRequestConfiguration("GetMaxCirculation", send, false);
        if (!x || x == "" || isNaN(x)) {
            return false;
        }

        var maxcirc = parseInt(x, 10);
        $('.maxcirc').html(maxcirc);

        if ($('.quantityddl').val() != "0") {
            $('.quantity').val($('.quantityddl').val());
        }

        $('.quantityrange').attr('maximumvalue', '' + maxcirc + '');
        $('.quantity').trigger('change');

        Request(shopType, this.value, false);
    });

    $('.Shipping').change(function() {
        LockActions();
        Request(shopType, this.value, false);
    });

    // Service Options
    $('#FileCheckChk').click(function(e) { DataCheck(e); });
    $('#NoProofRb').change(function(e) { NoProof(e); });
    $('#HardProofRb').change(function(e) { HardProof(e); });
    $('#VoucherChk').click(function(e) { Voucher(e); });
    $('#SponsoringChk').click(function(e) { Sponsoring(e); });
    $('#SxpRb').change(function(e) { Sxp(e); });
    $('#OwnRb').change(function(e) { YourAddress(e); });
    $('#DeliverySplittingChk').click(function(e) { Splitting(e); });

    $('a#calculate').click(function() { Calculate });

    $('a#ShoppingCartBtn').click(function() { AddToCart });
    // ToDo: MeinDesign wieder einbauen wenn es mehrere Produkte gibt
    // $('a#MyDesignBtn').click(function() { MyDesign });

    ReleaseActions();

    $(".tab").click(function(e) {
        var target = e.currentTarget.id; //tab 1 / tab2
        if (target == "tab1" && $("#" + target).hasClass("inactive") || target == "chooseProperties") {
            $("#tab1").removeClass("inactive").addClass("active");
            $("#tab2").removeClass("active").addClass("inactive");

            $(".properties").toggle();
            $(".servicespanel").toggle();
            $(".choosePropertiesTR").toggle();
            $(".chooseServiceTR").toggle();
            $("#spaceRow").toggle();
        }

        if (target == "tab2" && $("#" + target).hasClass("inactive") || target == "chooseService") {
            $("#tab1").removeClass("active").addClass("inactive");
            $("#tab2").removeClass("inactive").addClass("active");

            $(".properties").toggle();
            $(".servicespanel").toggle();
            $(".choosePropertiesTR").toggle();
            $(".chooseServiceTR").toggle();
            $("#spaceRow").toggle();
            Calculate();
        }
    });
    $('#configuratorzone').show();
    $('#loader').hide();
    HandleMyDesignBtn();
});

function GetMaxCirculationText()
{
    var org = $('#WrongImpostError .org').html();
    var text = org.replace(/\{0\}/g,$('.maxcirc').eq(0).html());
    return text;
}

function GetOverMaxCirculationText()
{
    var org = $('#OverMaxImpostError .org').html();
    var text = org.replace(/\{0\}/g, $('.mincirc').html()).replace(/\{1\}/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('opacity', 0.5);
    $('#netSPAN,#vatSPAN,#finalPriceSPAN').css('visibility', 'hidden');
    $('#PointsSpan').html("--");
    $('#ShoppingCartBtn').unbind('click').hide();    
    $('a#calculate').bind('click', null, Calculate).show();
    // $('a#MyDesignBtn').unbind('click');
}

// Gibt den Warenkorb und Meindesign wieder frei
function ReleaseActions()
{
    $('.offerDIV').unblock().css('opacity', 1);
    $('#netSPAN,#vatSPAN,#finalPriceSPAN').css('visibility', 'visible');
    $('#ShoppingCartBtn').show().bind('click', null, AddToCart);    
    $('a#calculate').unbind('click').hide();
    // $('a#MyDesignBtn').bind('click', null, MyDesign);
}

// Aktuelles Produkt in den Warenkorb transferieren
function AddToCart()
{
    if (SplittingChecked() == true && isValidSplitting == false)
    {
        $('#splittingerror').show();        
        return;
    }

    $('#splittingerror').hide();
    var send = '{x: ""}';
    var x = CoreRequestConfiguration("AddToShoppingCart", send, false);
    if (x == "error" || x == "")
    {
        alert('error');
        DoPostback();
    }

    Navigate(x);
}

function MyDesign()
{
    return false;
}

// Textcache laden
function LoadCache()
{
    var send = '{a: ""}';
    cache = eval(CoreRequestConfiguration("LoadTextCache", send));
}

// speichert den Service in der Session
function SetService(article)
{    
    var send = '{articleNumber: "' + article + '"}';
    CoreRequestConfiguration("SetService", send); //Syncron wegen evtl überschneidung
}

// Blendet den Text (kein Service) ein uns aus.
function DisplayNoService()
{
    var invisible = $('#FileCheckChk')[0].checked || $('#HardProofRb')[0].checked || $('#VoucherChk')[0].checked ||
    $('#SponsoringChk')[0].checked || $('#OwnRb')[0].checked || $('#DeliverySplittingChk')[0].checked;

    $('.noservice').toggle(!invisible);    
}

// berechnet den aktuellen Preis.
function Calculate()
{    
    try
    {
        if ($('#DeliverySplittingChk')[0].checked && !isValidSplitting)
        {
            $('#splittingerror').show();
            return;
        }

        $('#splittingerror').hide();

        var send = '{circulation: "' + GetCirculation() + '"}';
        if (!init)
        {
            var value = CoreRequestConfiguration("Calculate", send);
        }
        else
        {
            var value = CoreRequestConfiguration("InitialCalculate", send);
        }

        if (value == "" || value == "error")
        {
            DoPostBack();
            return;
        }

        var price = $.parseJSON(value);
        // alert(price.error);
        $('#netSPAN').html(price.n);
        $('#vatSPAN').html(price.v);
        $('#finalPriceSPAN').html(price.g);
        $('#PointsSpan').html(price.p);
    }
    catch(ex)
    {
        DoPostBack();
    }
    finally
    {
        ReleaseActions();
    }
}

// Liest die aktuelle Auflage aus.
function GetCirculation()
{
    var quantityTxt = $('.quantity');
    var topsellerDdl = $('.quantityddl');

    if (quantityTxt.val() == "")
    {
        var topseller = topsellerDdl.val();
        if (topseller == "0")
        {
            return 1000;
        }

        return topseller;
    }
    else
    {
        var x = TryParseInt(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();
	var send = '{shopType: "' + shopType + '", changedValue: "' + value + '", isCover: "' + isCover + '" }';
    var value = CoreRequestConfiguration("GetConfiguration", send);

    if (value == "error")
    {
        DoPostBack();
        return;
    }

    FillLists($.parseJSON(value));	//JQuery 1.41
	$.unblockUI();
}

// Konfigurationsergebnis verarbeiten
function FillLists(object)
{
    // Cover
    HandleCoverDisplay(object.c);
    
    // Initialauflage
    if (object.ic)
    {
        $('.quantity').val(object.ic);
    }

    if (object.mc)
    {
        $('.maxcirc').html(object.mc);
    }
    
    // Topseller
    FillTopseller(object.t);

    if (initializing)
    {
        // Style
        if (object.s && !isops)
        {
            SetStyle(object.s);
        }
        else
        {
            $('#stylediv').addClass('hidden');
        }
    }

    // HandleMyDesignDisplay(object.o);

    //Dropdowns
    FillDropdowns(object.l);

    // Serviceoptionen setzen
    if (object.v)
    {
        SetServices(object.v);
    }

    if (object.p)
    {
        $('#perma').remove();
        $('<div id="perma">' + object.p + '</div>').insertBefore($('#configtop'));
    }

    SetDetailsText();
    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)
{
    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;
        }

        AppendOptions(quantityddl, 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++)
    {
        AppendOptions(style, list[s].s, list[s].v, GetText(list[s].v));
    }
}

// Mein Design Button ein oder aus-blenden
function HandleMyDesignDisplay(value)
{
    if (!value)
    {
        $('#MyDesignBtn').hide();
        return;
    }
    
    $('#MyDesignBtn').toggleClass('hidden', value == 0);
}

// Konfigurations Dropdowns füllen
function FillDropdowns(lists)
{
    for (var i = 0; i < lists.length; i++)
    {
        // Liste
        var currentList = lists[i];

        // Elemente löschen
        var dropDown = $('.' + currentList.Key);
        dropDown.children().remove();

        var valueList = new Array();
        for (var b = 0; b < currentList.Value.length; b++)
        {
            valueList.push(currentList.Value[b]);
        }

        for (var j = 0; j < valueList.length; j++)
        {
            var z = valueList[j];
            var selected = valueList[j].s;
                        
            AppendOptions(dropDown, selected, z.v, GetText(z.v));
        }
    }
}

function SetServices(list)
{
    for (var i = 0; i < list.length; i++)
    {
        $(':input[value=' + list[i] + ']').click();
        SetService(list[i]);

        switch (list[i])
        {
            case "DATENK":
                $('.datacheck').toggle();
                break;
            case "HARDPR":
                $('.hardproof').toggle();
                break;
            case "BELEGE":
                $('.voucher').toggle();
                break;
            case "SPONSO":
                $('.sponsoring').toggle();
                break;
            case "SHPANO":
                $('.youraddress').toggle();
                break;
            case "SHPPRT":
                $('.dsplitting').toggle();
                $('#DeliverySplittingdiv').show();
                break;                            
        }
    }
    
    DisplayNoService();
}

function DataCheck(e) { $('.datacheck').toggle(); DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function NoProof(e) { if ($('#NoProofRb')[0].checked) { $('.hardproof').hide(); } DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function HardProof(e) { $('.hardproof').toggle(); DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function Voucher(e) { $('.voucher').toggle(); DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function Sponsoring(e) { $('.sponsoring').toggle(); DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function Sxp(e) { if ($('#SxpRb')[0].checked) { $('.youraddress').hide(); } DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function YourAddress(e) { $('.youraddress').toggle(); DisplayNoService(); SetService(e.currentTarget.value); Calculate(); }
function Splitting(e)
{    
    $('.dsplitting').toggle();
    var elem = $('#DeliverySplittingChk');
    var div = $('#DeliverySplittingdiv');
    if (elem[0].checked)
    {
        div.show();
        sum();
    }
    else
    {
        div.hide();
        SetService(elem[0].value);
    }

    DisplayNoService(); 
    Calculate();
  }

// Options an ein Dropdown anhängen
function AppendOptions(element, selected, value, text)
{
    if (selected == 1)
    {
        element.append($('<option selected=\'selected\'></option>').val(value).html(text));
    }
    else
    {
        element.append($('<option></option>').val(value).html(text));
    }
}

// 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";
}

// Details Text setzen
function SetDetailsText()
{
    $('#FinishedSizeDet').html(GetText($('.FinishedSize').val()));

    $('#PagesDet').html(GetText($('.Pages').val()));
    $('#DegreeOfColourDet').html(GetText($('.DegreeOfColour').val()));
    $('#PaperDet').html(GetText($('.Paper').val()));

    $('.coverdet').toggle(hasCover);

    if (hasCover)
    {
        $('#PagesCoverDet').html(GetText($('.PagesCover').val()));
        $('#DegreeOfColourCoverDet').html(GetText($('.DegreeOfColourCover').val()));
        $('#PaperCoverDet').html(GetText($('.PaperCover').val()));
    }
    else
    {
        $('#PagesCoverDet').html("");
        $('#DegreeOfColourCoverDet').html("");
        $('#PaperCoverDet').html("");
    }

    $('#ProcessingDet').html(GetText($('.Processing').val()));
    $('#PerforationDet').html(GetText($('.Perforation').val()));

    $('#ProductionTimeDet').html(GetText($('.ProductionTime').val()));
    $('#ShippingDet').html(GetText($('.Shipping').val()));
}


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);
}

function HandleMyDesignBtn() {
    var temp = $(".MyDesignBtnDiv");
    if (temp != null) {
        if ($('.Pages').val() == '00001Q') {
            $(temp).show();
        }
        else {
            $(temp).hide();  
        }
    }
}
