﻿$.IsValidEmail = function(value) { return (/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(value)); };
var NavigationObjHover = new Array();
var NavigationObjShow = new Array();
var Navigation = {
    ShowDelayMS: 400,
    HideDelayMS: 400,
    Show: function(ObjBtn) {
        NavigationObjHover.push(ObjBtn);
        window.setTimeout(this.ShowDelayed, this.ShowDelayMS);
    },
    Hide: function(ObjBtn) {
        NavigationObjHover.pop();
        window.setTimeout(this.HideDelayed, this.HideDelayMS);
    },
    ShowDelayed: function() {
        for (var i = 0; i < NavigationObjHover.length; i++) {
            if (NavigationObjShow.indexOf(NavigationObjHover[i]) == -1) {
                NavigationObjShow.push(NavigationObjHover[i]);
                NavigationObjHover[i].className = 'active';
                break;
            }
        }
    },
    HideDelayed: function() {
        for (var i = NavigationObjShow.length-1; i > -1; i--) {
            if (NavigationObjHover.indexOf(NavigationObjShow[i]) == -1) {
                NavigationObjShow[i].className = '';
                NavigationObjShow.splice(i, 1);
                break;
            }
        }
    }
};

$.Page = {
    AsyncPostback: function (eventName, eventArgs, onComplete) {
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        if (!Array.contains(prm._asyncPostBackControlIDs, eventName)) {
            prm._asyncPostBackControlIDs.push(eventName);
        }
        if (!Array.contains(prm._asyncPostBackControlClientIDs, eventName)) {
            prm._asyncPostBackControlClientIDs.push(eventName);
        }
        if (typeof onComplete === "function") {
            $.Page.AddAsyncPostbackHandler(onComplete);
        }
        __doPostBack(eventName, eventArgs);
    },
    AddAsyncPostbackHandler: function (handler) {
        Sys.WebForms.PageRequestManager.getInstance().add_endRequest(handler);
    }
};

addLoadEventHandler = function(func) {
    var previous_handler = window.onload;
    if (typeof window.onload != "function") 
        window.onload = func;
    else window.onload = function() {
        previous_handler();
        func();
    }
}

function ContentNavToggle(Obj_Ref, altGoTo, altP1) {
    var cn = document.getElementById("CONTENT_NAVIGATION");
    var lis = cn.getElementsByTagName("td");
    var kl = cn.getAttribute("name").split("|");
    if (!Obj_Ref && altGoTo) {
        Obj_Ref = lis[altGoTo].getElementsByTagName("a")[0];
    } else if (!Obj_Ref && !altGoTo && altP1) {
        if (kl.indexOf(altP1) == -1) {
            Obj_Ref = lis[0].getElementsByTagName("a")[0];
        } else {
            Obj_Ref = lis[kl.indexOf(altP1)].getElementsByTagName("a")[0];
        }
    }
    for (var i = 0; i < lis.length; i++) {
        var td = lis[i];
        var btn = td.getElementsByTagName("a")[0];
        var content = document.getElementById("ctl00_CPH_Content_ctl00_PL_" + kl[i].toUpperCase()); 
        if (btn == Obj_Ref) {
            td.className = "active";
            if (content) content.className = "";
        } else {
            td.className = "";
            if (content) content.className = "hidden";
        } 
    }
}

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj) {
        for (var i = 0; i < this.length; i++)
            if (this[i] == obj)
                return i;
        return -1;
    }
}

/** Search **/
var FL_FIELDVALUE_SEARCH = "Zeitschrift / Stichwort";
var T_FLASH_SEARCH;
$(document).ready(function () {
    var $SearchEle = $('input#search'), BaseColor = $('input#search').css("color");
    var SearchFlashTimer;
    SearchStartFlash = function () {
        SearchFlashTimer = setInterval(function () {
            var CurrentColor = $SearchEle.css("color");
            if (CurrentColor == BaseColor) {
                $SearchEle.css("color", "white");
            } else {
                $SearchEle.css("color", BaseColor);
            }
        }, 1000);
    }
    SearchStartFlash();
    $('input#search').focus(function () {
        if ($(this).val() == FL_FIELDVALUE_SEARCH) {
            $(this).val("");
            $(this).removeClass("validate-empty");
            clearInterval(SearchFlashTimer);
            $SearchEle.css("color", BaseColor);
        }
    });
    $('input#search').blur(function () {
        if ($(this).val().trim() == "") {
            $(this).val(FL_FIELDVALUE_SEARCH);
            $(this).addClass("validate-empty");
            SearchStartFlash();
        }
    });
    $('input#search').keyup(function (e) {
        if ((e.keyCode || e.which) == 13) {
            if ($(this).val().trim() != "") {
                window.location.href = SYS_URL_SEARCH + $.ProductKeywordList.Query();
            }
            return false;
        } else {
            try {
                $.ProductKeywordList.Get();
            } catch (exc) {
                // do nothing
            }
        }
    });
    $('#search_btn').click(function () {
        if ($('input#search').val().trim() != "" && $('input#search').val() != FL_FIELDVALUE_SEARCH) {
            window.location.href = SYS_URL_SEARCH + $.ProductKeywordList.Query();
        }
        return false;
    });
});

$.Presseplus = {
    Config: {
        RootPath: ('https:' == document.location.protocol ? 'https' : 'http') + '://' + document.location.host,
        SvcPath: ('https:' == document.location.protocol ? 'https' : 'http') + '://' + document.location.host + '/Public/Service/PresseplusService.svc',
        CoversPath: ('https:' == document.location.protocol ? 'https' : 'http') + '://' + document.location.host + '/Covers/e10e483d-9b8b-4e52-aa4d-16e6eb7cf6cc/{size}/{productCode}/{releaseCode}/{productNameUnique}.jpg',
        CartPath: '/Warenkorb',
        AccountPath: '/Account',
        UserPasswordRememberPath: "/Ich-habe-mein-Passwort-vergessen"
    }
}

var ProductKeywordList_Get_Timer;
$.ProductKeywordList = {
    Get: function () {
        clearTimeout(ProductKeywordList_Get_Timer);
        var strKeyword = $.ProductKeywordList.Query();
        if (strKeyword != "") {
            ProductKeywordList_Get_Timer = setTimeout(function () {
                $("div#SearchKeywords").hide();
                $("div#SearchKeywords").html('');
                $.ajax({
                    contentType: "application/json; charset=utf-8",
                    url: $.Presseplus.Config.SvcPath + '/ProductNamesByKeyword',
                    data: {
                        keyword: strKeyword
                    },
                    success: function (r) {
                        var jObj = JSON.parse(r.d);
                        var htmlString = '';
                        $.each(jObj, function (k, v) {
                            htmlString += '<li><a href="' + SYS_URL_SEARCH + $.ProductKeywordList.UrlQuery(v.ProductName) + '">' + v.ProductName + '</a></li>';
                        });
                        if (htmlString != '') {
                            $("div#SearchKeywords").html('<ul>' + htmlString + '</ul>');
                            $("div#SearchKeywords").slideDown(300);
                        }
                    }
                });
            }, 400);
        } else {
            $("div#SearchKeywords").hide();
            $("div#SearchKeywords").html('');
        }
    },
    UrlQuery: function (str) {
        return $.trim(str.replace(/\s/g, "+"));
        //return encodeURIComponent(q.replace(/\s/g, "+"));
    },
    Query: function () {
        return $.trim($('input#search').val());
    }
}

$.Covers = {
    GetPath: function(size, productCode, productNameUnique, releaseCode) {
        releaseCode = releaseCode || "Aktuelle-Ausgabe";
        return $.Presseplus.Config.CoversPath.replace("{size}", size).replace("{productCode}", productCode).replace("{releaseCode}", releaseCode).replace("{productNameUnique}", productNameUnique);
    }
}

$.Cart = {
    Load: function () {
        $.ajax({
            contentType: "application/json; charset=utf-8",
            url: $.Presseplus.Config.SvcPath + '/CartSelectTable',
            data: {},
            cache: false,
            success: function (r) {
                var jObj = JSON.parse(r.d);
                var htmlString = '';
                $("div#CphToolCart").hide();
                $("div#CphToolCart").html('');
                if (jObj.length > 0) {
                    $("div#tb1_cart").removeClass("cartempty");
                    $("div#tb1_cart a[class!='notempty']").addClass("notempty");
                    $("div#tb1_cart a").html(jObj.length);
                    if (SYS_PARAM_P1 == "warenkorb" || SYS_PARAM_P1 == "startseite") {
                        return false;
                    }
                    htmlString = '<div class="title"><h2>Mein Warenkorb</h2><a href="' + $.Presseplus.Config.CartPath + '">Zur Kasse gehen</a></div><table cellpadding="0" cellspacing="0">';
                    $.each(jObj, function (k, v) {
                        htmlString += '<tr><td colspan="2"><h3>' + v.Name + '</h3></td></tr>';
                        htmlString += '<tr><td><a href="/' + v.Name_Unique + '"><img alt="' + v.Name + '" src="' + $.Covers.GetPath("Small", v.Code, v.Name_Unique) + '" /></a></td>';
                        htmlString += '<td>' + v.Option + '<br />';
                        htmlString += '<font class="price_old">' + v.PriceOld_With_Currency_Symbol + '</font><br />';
                        htmlString += '<div class="inline"><font class="price">' + v.Price_With_Currency_Symbol + '</font>&nbsp;&nbsp;&nbsp;</div>';
                        htmlString += '<div class="inline"><a class="btn_cart_delete" href="javascript:$.Cart.Remove(' + v.Cart_ID + ');" title="löschen">&nbsp;</a></div><br class="clear" />';
                        htmlString += '</td></tr>';
                    });
                    htmlString += '</table><div class="footer">';
                    htmlString += '<p><a href="' + $.Presseplus.Config.CartPath + '">Zur Kasse gehen</a></p>';
                    htmlString += '<p><a href="javascript:$.Cart.Clear();">Warenkorb leeren</a></p></div>';
                    $("div#CphToolCart").html(htmlString);
                    $("div#CphToolCart").slideDown(300);
                } else {
                    $("div#tb1_cart[class!='cartempty']").addClass("cartempty");
                    $("div#tb1_cart a").removeClass("notempty");
                    $("div#tb1_cart a").html(0);
                }
            }
        });
    },
    Refresh: function () {
        if (SYS_PARAM_P1 == 'warenkorb') {
            location.reload();
        } else {
            $.Cart.Load();
        }
    },
    Add: function (Product_ID, Category_ID, ProductOption_ID) {
        $.ajax({
            contentType: "application/json; charset=utf-8",
            url: $.Presseplus.Config.SvcPath + '/CartAddItem',
            cache: false,
            data: { Product_ID: Product_ID, Category_ID: Category_ID, ProductOption_ID: ProductOption_ID },
            success: function (r) {
                $.Cart.Refresh();
                $.Msg.Show('Der Artikel wurde in den Warenkorb gelegt.<br/><a href="' + $.Presseplus.Config.CartPath + '">Zur Kasse gehen</a>');
            }
        });
    },
    Remove: function (Cart_ID) {
        $.ajax({
            contentType: "application/json; charset=utf-8",
            cache: false,
            url: $.Presseplus.Config.SvcPath + '/CartRemoveItem',
            data: { Cart_ID: Cart_ID },
            success: function (r) {
                $.Cart.Refresh();
                $.Msg.Show("Der Artikel wurde aus dem Warenkorb entfernt.");
            }
        });
    },
    Clear: function () {
        $.ajax({
            contentType: "application/json; charset=utf-8",
            cache: false,
            url: $.Presseplus.Config.SvcPath + '/CartClear',
            data: {},
            success: function (r) {
                $.Cart.Refresh();
                $.Msg.Show("Der Warenkorb wurde geleert.");
            }
        });
    },
    SelectPaymentType: function (objSelect) {
        var PaymentType_ID = $(objSelect).val();
        $("#dc_cartpaymentedit").find("div[class*='type_']").addClass('hidden');
        $("#dc_cartpaymentedit").find("div.type_" + PaymentType_ID).removeClass('hidden');
        return false;
    },
    SetPaymentType_ID: function (PaymentType_ID) {
        __doPostBack('AJAX_PaymentType_ID_Set', PaymentType_ID);
        $.Dialog.Close($("#dc_cartpaymentedit"));
        return false;
    },
    SelectCustomerPayment: function (CustomerPayment_ID) {
        __doPostBack('AJAX_CustomerPayment_Select', CustomerPayment_ID);
        $.Dialog.Close($("#dc_cartpaymentedit"));
        return false;
    },
    SelectEVT: function (selVal, Cart_ID) {
        __doPostBack('AJAX_EVT_Select', Cart_ID + "|" + selVal + "|" + $("#txt_special_request_" + Cart_ID).val());
        if (selVal > 0) {
            $("#txt_special_request_" + Cart_ID).css({ display: "hidden" });
            $("#txt_special_request_" + Cart_ID).val("");
        } else {
            $("#txt_special_request_" + Cart_ID).css({ display: "block" });
        }
        return false;
    },
    BillingAddress: {
        Form: {
            Show: function (anchor) {
                $.BillingAddress.Form.Reset();
                $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
            }
        },
        Update: function (billingAddressId) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/CartSetBillingAddress',
                data: JSON.stringify({
                    billingAddressId: billingAddressId
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    switch (errorCode) {
                        case -1: // success
                            $.Dialog.Close();
                            __doPostBack($("div#[id*='Up_BillingAddress']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Zuordnung Rechnungsadresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    },
    ShippingAddress: {
        Form: {
            Show: function (anchor, Cart_ID) {
                $.ShippingAddress.Form.Reset();
                $("input[id*='Hf_Cart_ID']").val(Cart_ID);
                $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
            }
        },
        Update: function (cartId, shippingAddressId) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/CartSetShippingAddress',
                data: JSON.stringify({
                    cartId: cartId,
                    shippingAddressId: shippingAddressId
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    switch (errorCode) {
                        case -1: // success
                            $.Dialog.Close();
                            __doPostBack($("div#[id*='Up_Cart_Items']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Zuordnung Lieferadresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    },
    Payment: {
        Update: function (paymentId) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/CartSetPayment',
                data: JSON.stringify({
                    paymentId: paymentId
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    switch (errorCode) {
                        case -1: // success
                            $.Dialog.Close();
                            __doPostBack($("div#[id*='Up_Payment']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Zuordnung Zahlungsart!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    },
    PaymentType: {
        Form: {
            Show: function (anchor) {
                $.Payment.Form.Reset();
                $("input[id*='Hf_UpdateCart']").val(Cart_ID);
                $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
            }
        },
        Update: function (paymentTypeId) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/CartPaymentType',
                data: JSON.stringify({
                    paymentTypeId: paymentTypeId
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    switch (errorCode) {
                        case -1: // success
                            
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Zuordnung Lieferadresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    }
}

$.Customer = {
    Form: {
        Show: function (anchor, Title_ID, Firstname, Lastname, Company, Street, ZIP, City, Country_ID, Phone, Fax, Email) {
            $.Customer.Form.Reset();
            $("div#dc_customer h1").html('Kundenadresse bearbeiten');
            $("select[id*='Dd_C_Title']").val(Title_ID);
            $("input[id*='Tb_C_Firstname']").val(Firstname);
            $("input[id*='Tb_C_Lastname']").val(Lastname);
            $("input[id*='Tb_C_Company']").val(Company);
            $("input[id*='Tb_C_Street']").val(Street);
            $("input[id*='Tb_C_ZIP']").val(ZIP);
            $("input[id*='Tb_C_City']").val(City);
            $("select[id*='Dd_C_Country']").val(Country_ID);
            $("input[id*='Tb_C_Phone']").val(Phone);
            $("input[id*='Tb_C_Fax']").val(Fax);
            $("input[id*='Tb_C_Email']").val(Email);
            $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
        },
        Hide: function () {
            $.Dialog.Close();
        },
        Reset: function () {
            $("form").each(function () {
                this.reset();
            });
            $("select[id*='Dd_C_Title']").val('');
            $("input[id*='Tb_C_Firstname']").val('');
            $("input[id*='Tb_C_Lastname']").val('');
            $("input[id*='Tb_C_Company']").val('');
            $("input[id*='Tb_C_Street']").val('');
            $("input[id*='Tb_C_ZIP']").val('');
            $("input[id*='Tb_C_City']").val('');
            $("select[id*='Dd_C_Country']").val('');
            $("input[id*='Tb_C_Phone']").val('');
            $("input[id*='Tb_C_Fax']").val('');
            $("input[id*='Tb_C_Email']").val('');
        }
    },
    Update: function (options) {
        if (!Page_ClientValidate('Vg_C'))
            return false;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            cache: false,
            url: $.Presseplus.Config.SvcPath + '/CustomerUpdate',
            data: JSON.stringify({
                titleId: $("select[id*='Dd_C_Title']").val(),
                firstname: $("input[id*='Tb_C_Firstname']").val(),
                lastname: $("input[id*='Tb_C_Lastname']").val(),
                company: $("input[id*='Tb_C_Company']").val(),
                street: $("input[id*='Tb_C_Street']").val(),
                zip: $("input[id*='Tb_C_ZIP']").val(),
                city: $("input[id*='Tb_C_City']").val(),
                countryId: $("select[id*='Dd_C_Country']").val(),
                phone: $("input[id*='Tb_C_Phone']").val(),
                fax: $("input[id*='Tb_C_Fax']").val(),
                email: $("input[id*='Tb_C_Email']").val()
            }),
            success: function (r) {
                var errorCode = parseInt(JSON.parse(r.d).errorCode);
                switch (errorCode) {
                    case -1: // success
                        $.Msg.Show("Kundendaten gespeichert.");
                        $.Dialog.Close($("#dc_customer"));
                        __doPostBack($("div#[id*='Up_Customer']").attr("id"), '');
                        break;
                    default:
                        $.Msg.Show("Fehler beim Ändern der Daten!<br/>Fehlercode: " + errorCode, 1);
                        break;
                }
            }
        });
    }
}
$.User = {
    Login: function () {
        var userName = $("input[id*='Tb_L_Email']").val();
        var passwd = $("input[id*='Tb_L_Password']").val();
        var persistant = $("input[id*='Cb_L_Persistant']").attr("checked");
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            cache: false,
            url: $.Presseplus.Config.SvcPath + '/UserLogin',
            data: JSON.stringify({
                userName: userName,
                passwd: passwd,
                persistant: persistant ? 1 : 0
            }),
            success: function (r) {
                var errorCode = parseInt(JSON.parse(r.d));
                switch (errorCode) {
                    case -2: // success Bib
                    case -1: // success Standard
                        var redir = '/';
                        if (SYS_PARAM_P2 == 'weiterleiten' && SYS_PARAM_P3 != '') {
                            redir += SYS_PARAM_P3 + '/';
                            if (SYS_PARAM_P4 != '') {
                                redir += SYS_PARAM_P4;
                            }
                            window.location = redir;
                        } else {
                            window.location = $.Presseplus.Config.AccountPath;
                        }
                        break;
                    case 1: // error
                        $.Msg.Show("Emailadresse oder Passwort ungültig.<br/>Bitte versuchen Sie es erneut.<br/>Sie können jeder Zeit ein <a href=\"" + $.Presseplus.Config.UserPasswordRememberPath + "/" + userName + "\">neues Passwort anfordern</a>.", 1);
                        break;
                    case 2: // activation error
                        $.Msg.Show("Dieser Account ist noch nicht freigeschaltet,<br/>bitte folgen Sie den Anweisungen in der Email zur Registrierung.", 1);
                        break;
                    default:
                        $.Msg.Show("Fehler bei Anmeldung!<br/>Fehlercode: " + errorCode, 1);
                        break;
                }
            }
        });
    },
    Update: function (data) {
        var errorCode = -1;
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            cache: false,
            url: $.Presseplus.Config.SvcPath + '/UserUpdate',
            data: JSON.stringify(data),
            success: function (r) {
                errorCode = parseInt(JSON.parse(r.d));
                switch (errorCode) {
                    case -1: // success
                        $.Msg.Show("Daten aktualisiert.");
                        break;
                    case 1: // error
                        $.Msg.Show("Diese Email-Adresse ist bereits bei uns registriert und kann nicht verwendet werden.", 1);
                        break;
                    case 2: // activation error
                        $.Msg.Show("Es wurden keine Änderungen vorgenommen.", 1);
                        break;
                    default:
                        $.Msg.Show("Fehler bei Aktualisierung!<br/>Fehlercode: " + errorCode, 1);
                        break;
                }
            }
        });
        return (errorCode == -1);
    }
}

$.ShippingAddress = {
    Form: {
        Show: function (anchor, ShippingAddress_ID, Title_ID, Firstname, Lastname, Company, Street, ZIP, City, Country_ID, BookmarkChanges_DT) {
            $.ShippingAddress.Form.Reset();
            if (ShippingAddress_ID > 0) {
                $("div#dc_shippingaddress h1").html('Lieferadresse bearbeiten');
                $("div.BookmarkChanges").show();
                $("input[id*='E_SA_BookmarkChanges_DT']").val(BookmarkChanges_DT);
                $("input[id*='E_SA_ID']").val(ShippingAddress_ID);
                $("select[id*='Dd_SA_Title']").val(Title_ID);
                $("input[id*='Tb_SA_Firstname']").val(Firstname);
                $("input[id*='Tb_SA_Lastname']").val(Lastname);
                $("input[id*='Tb_SA_Company']").val(Company);
                $("input[id*='Tb_SA_Street']").val(Street);
                $("input[id*='Tb_SA_ZIP']").val(ZIP);
                $("input[id*='Tb_SA_City']").val(City);
                $("select[id*='Dd_SA_Country']").val(Country_ID);
            }
            $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
        },
        Hide: function () {
            $.Dialog.Close();
        },
        Reset: function () {
            $("div#dc_shippingaddress h1").html('Lieferadresse hinzufügen');
            $("div.BookmarkChanges").hide();
            $("form").each(function () {
                this.reset();
            });
            $("input[id*='E_SA_ID']").val('-1');
            $("input[id*='Hf_Cart_ID']").val('');
            $("select[id*='Dd_SA_Title']").val('');
            $("input[id*='Tb_SA_Firstname']").val('');
            $("input[id*='Tb_SA_Lastname']").val('');
            $("input[id*='Tb_SA_Company']").val('');
            $("input[id*='Tb_SA_Street']").val('');
            $("input[id*='Tb_SA_ZIP']").val('');
            $("input[id*='Tb_SA_City']").val('');
            $("select[id*='Dd_SA_Country']").val('');
            $("input[id*='E_SA_BookmarkChanges_DT']").val('');
        }
    },
    Save: function (options) {
        if (!Page_ClientValidate('Vg_SA'))
            return false;
        if ($("input[id*='E_SA_ID']").val() > 0) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/ShippingAddressUpdate',
                data: JSON.stringify({
                    shippingAddressId: $("input[id*='E_SA_ID']").val(),
                    titleId: $("select[id*='Dd_SA_Title']").val(),
                    firstname: $("input[id*='Tb_SA_Firstname']").val(),
                    lastname: $("input[id*='Tb_SA_Lastname']").val(),
                    company: $("input[id*='Tb_SA_Company']").val(),
                    street: $("input[id*='Tb_SA_Street']").val(),
                    zip: $("input[id*='Tb_SA_ZIP']").val(),
                    city: $("input[id*='Tb_SA_City']").val(),
                    countryId: $("select[id*='Dd_SA_Country']").val(),
                    bookmarkChanges_DT: $("input[id*='E_SA_BookmarkChanges_DT']").val()
                }),
                success: function (r) {
                    var errorCode = parseInt(JSON.parse(r.d).errorCode);
                    switch (errorCode) {
                        case -1: // success
                            $.Msg.Show("Lieferadresse gespeichert.");
                            $.Dialog.Close($("#dc_shippingaddress"), true);
                            __doPostBack($("div#[id*='Up_ShippingAddress']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Adresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        } else {
            var cartId = parseInt($("input[id*='Hf_Cart_ID']").val());
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/ShippingAddressInsert',
                data: JSON.stringify({
                    titleId: $("select[id*='Dd_SA_Title']").val(),
                    firstname: $("input[id*='Tb_SA_Firstname']").val(),
                    lastname: $("input[id*='Tb_SA_Lastname']").val(),
                    company: $("input[id*='Tb_SA_Company']").val(),
                    street: $("input[id*='Tb_SA_Street']").val(),
                    zip: $("input[id*='Tb_SA_ZIP']").val(),
                    city: $("input[id*='Tb_SA_City']").val(),
                    countryId: $("select[id*='Dd_SA_Country']").val()
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    var shippingAddressId = parseInt(ret.shippingAddressId);
                    switch (errorCode) {
                        case -1: // success
                            $.Msg.Show("Lieferadresse hinzugefügt.");
                            $.Dialog.Close($("#dc_shippingaddress"), true);
                            if (cartId > 0) {
                                $.Cart.ShippingAddress.Update(cartId, shippingAddressId);
                            } else {
                                __doPostBack($("div#[id*='Up_ShippingAddress']").attr("id"), '');
                            }
                            break;
                        default:
                            $.Msg.Show("Fehler beim Hinzufügen der Adresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    }
}

$.BillingAddress = {
    Form: {
        Show: function (anchor, options, BillingAddress_ID, Title_ID, Firstname, Lastname, Company, Street, ZIP, City, Country_ID, Phone, Fax, Email) {
            $.BillingAddress.Form.Reset();
            if (BillingAddress_ID > 0) {
                $("div#dc_billingaddress h1").html('Rechnungsadresse bearbeiten');
                $("input#Hf_BA_ID").val(BillingAddress_ID);
                $("select[id*='Dd_BA_Title']").val(Title_ID);
                $("input[id*='Tb_BA_Firstname']").val(Firstname);
                $("input[id*='Tb_BA_Lastname']").val(Lastname);
                $("input[id*='Tb_BA_Company']").val(Company);
                $("input[id*='Tb_BA_Street']").val(Street);
                $("input[id*='Tb_BA_ZIP']").val(ZIP);
                $("input[id*='Tb_BA_City']").val(City);
                $("select[id*='Dd_BA_Country']").val(Country_ID);
                $("input[id*='Tb_BA_Phone']").val(Phone);
                $("input[id*='Tb_BA_Fax']").val(Fax);
                $("input[id*='Tb_BA_Email']").val(Email);
            }
            if(options && options.updateCard) 
                $("input#Hf_UpdateCard").val('true');
            $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
        },
        Hide: function () {
            $.Dialog.Close();
        },
        Reset: function () {
            $("div#dc_billingaddress h1").html('Rechnungsadresse hinzufügen');
            $("form").each(function () {
                this.reset();
            });
            $("input#Hf_BA_ID").val('-1');
            $("input#Hf_UpdateCard").val('false');
            $("select[id*='Dd_BA_Title']").val('');
            $("input[id*='Tb_BA_Firstname']").val('');
            $("input[id*='Tb_BA_Lastname']").val('');
            $("input[id*='Tb_BA_Company']").val('');
            $("input[id*='Tb_BA_Street']").val('');
            $("input[id*='Tb_BA_ZIP']").val('');
            $("input[id*='Tb_BA_City']").val('');
            $("select[id*='Dd_BA_Country']").val('');
            $("input[id*='Tb_BA_Phone']").val('');
            $("input[id*='Tb_BA_Fax']").val('');
            $("input[id*='Tb_BA_Email']").val('');
        }
    },
    Save: function () {
        if (!Page_ClientValidate('Vg_BA'))
            return false;
        if ($("input#Hf_BA_ID").val() > 0) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/BillingAddressUpdate',
                data: JSON.stringify({
                    billingAddressId: $("input#Hf_BA_ID").val(),
                    titleId: $("select[id*='Dd_BA_Title']").val(),
                    firstname: $("input[id*='Tb_BA_Firstname']").val(),
                    lastname: $("input[id*='Tb_BA_Lastname']").val(),
                    company: $("input[id*='Tb_BA_Company']").val(),
                    street: $("input[id*='Tb_BA_Street']").val(),
                    zip: $("input[id*='Tb_BA_ZIP']").val(),
                    city: $("input[id*='Tb_BA_City']").val(),
                    countryId: $("select[id*='Dd_BA_Country']").val(),
                    phone: $("input[id*='Tb_BA_Phone']").val(),
                    fax: $("input[id*='Tb_BA_Fax']").val(),
                    email: $("input[id*='Tb_BA_Email']").val()
                }),
                success: function (r) {
                    var errorCode = parseInt(JSON.parse(r.d).errorCode);
                    switch (errorCode) {
                        case -1: // success
                            $.Msg.Show("Rechnungsadresse gespeichert.");
                            $.Dialog.Close($("#dc_billingaddress"), true);
                            __doPostBack($("div#[id*='Up_BillingAddress']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Adresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        } else {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/BillingAddressInsert',
                data: JSON.stringify({
                    titleId: $("select[id*='Dd_BA_Title']").val(),
                    firstname: $("input[id*='Tb_BA_Firstname']").val(),
                    lastname: $("input[id*='Tb_BA_Lastname']").val(),
                    company: $("input[id*='Tb_BA_Company']").val(),
                    street: $("input[id*='Tb_BA_Street']").val(),
                    zip: $("input[id*='Tb_BA_ZIP']").val(),
                    city: $("input[id*='Tb_BA_City']").val(),
                    countryId: $("select[id*='Dd_BA_Country']").val(),
                    phone: $("input[id*='Tb_BA_Phone']").val(),
                    fax: $("input[id*='Tb_BA_Fax']").val(),
                    email: $("input[id*='Tb_BA_Email']").val()
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    var billingAddressId = parseInt(ret.billingAddressId);
                    switch (errorCode) {
                        case -1: // success
                            $.Msg.Show("Rechnungsadresse hinzugefügt.");
                            if ($("input#Hf_UpdateCard").val() == 'true') {
                                $.Cart.BillingAddress.Update(billingAddressId);
                            } else {
                                __doPostBack($("div#[id*='Up_BillingAddress']").attr("id"), '');
                            }
                            $.Dialog.Close($("#dc_billingaddress"), true);
                            break;
                        default:
                            $.Msg.Show("Fehler beim Hinzufügen der Adresse!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    }
}

$.Payment = {
    Form: {
        Show: function (anchor, paymentTypeId, paymentId, owner, bank, bsc, acNo, ccTypeId, ccNo, ccValidityDate) {
            $.Payment.Form.Reset();
            if (paymentId > 0) {
                $("input#Hd_P_ID").val(paymentId);
                if (paymentTypeId == 204) {
                    $("input[id*='Tb_PA_Owner']").val(owner);
                } else {
                    $("input[id*='Tb_PC_Owner']").val(owner);
                }
                if (paymentTypeId == 204) {
                    $("div#dc_payment_bank h1").html('Bankverbindung bearbeiten');
                    $("input[id*='Tb_P_Bank']").val(bank);
                    $("input[id*='Tb_P_BSC']").val(bsc);
                    $("input[id*='Tb_P_ACNo']").val(acNo);
                } else {
                    $("div#dc_payment_cc h1").html('Kreditkarte bearbeiten');
                    var vdtParts = ccValidityDate.split('/');
                    $("select[id*='Dd_P_CcType']").val(ccTypeId);
                    $("input[id*='Tb_P_CcNo']").val(ccNo);
                    if (vdtParts.length > 0) {
                        $("input[id*='Tb_P_CcValidityDate_m']").val(vdtParts[0]);
                        $("input[id*='Tb_P_CcValidityDate_y']").val(vdtParts[1]);
                    }
                }
            }
            $.Dialog.Open(anchor, $("div#" + $(anchor).attr("id").replace('do', 'dc')));
        },
        Hide: function () {
            $.Dialog.Close();
        },
        Reset: function () {
            $("div#dc_payment_bank h1").html('Bankverbindung hinzufügen');
            $("div#dc_payment_cc h1").html('Kreditkarte hinzufügen');
            $("form").each(function () {
                this.reset();
            });
            $("input#Hd_P_ID").val('-1');
            $("input[id*='Tb_PA_Owner']").val('');
            $("input[id*='Tb_PC_Owner']").val('');
            $("input[id*='Tb_P_Bank']").val('');
            $("input[id*='Tb_P_BSC']").val('');
            $("input[id*='Tb_P_ACNo']").val('');
            $("select[id*='Dd_P_CcType']").val('');
            $("input[id*='Tb_P_CcNo']").val('');
            $("input[id*='Tb_P_CcValidityDate_m']").val('');
            $("input[id*='Tb_P_CcValidityDate_y']").val('');
        }
    },
    Save: function (paymentTypeId) {
        if (paymentTypeId == 204) {
            if (!Page_ClientValidate('Vg_PA'))
                return false;
        } else {
            if (!Page_ClientValidate('Vg_PC'))
                return false;
        }
        if ($("input[id*='Hd_P_ID']").val() > 0) {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/PaymentUpdate',
                data: JSON.stringify({
                    paymentId: $("input#Hd_P_ID").val(),
                    paymentTypeId: paymentTypeId,
                    owner: paymentTypeId == 204 ? $("input[id*='Tb_PA_Owner']").val() : $("input[id*='Tb_PC_Owner']").val(),
                    bank: $("input[id*='Tb_P_Bank']").val(),
                    bsc: $("input[id*='Tb_P_BSC']").val(),
                    acNo: $("input[id*='Tb_P_ACNo']").val(),
                    ccTypeId: $("select[id*='Dd_P_CcType']").val(),
                    ccNo: $("input[id*='Tb_P_CcNo']").val(),
                    ccValidityDate: $("input[id*='Tb_P_CcValidityDate_m']").val() + '/' + $("input[id*='Tb_P_CcValidityDate_y']").val()
                }),
                success: function (r) {
                    var errorCode = parseInt(JSON.parse(r.d).errorCode);
                    switch (errorCode) {
                        case -1: // success
                            if (paymentTypeId == 204) {
                                $.Msg.Show("Bankverbindung gespeichert.");
                                $.Dialog.Close($("#dc_payment_bank"), true);
                            } else {
                                $.Msg.Show("Kreditkarte gespeichert.");
                                $.Dialog.Close($("#dc_payment_cc"), true);
                            }
                            __doPostBack($("div#[id*='Up_Payment']").attr("id"), '');
                            break;
                        default:
                            $.Msg.Show("Fehler beim Ändern der Zahlungsart!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        } else {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                cache: false,
                url: $.Presseplus.Config.SvcPath + '/PaymentInsert',
                data: JSON.stringify({
                    paymentTypeId: paymentTypeId,
                    owner: paymentTypeId == 204 ? $("input[id*='Tb_PA_Owner']").val() : $("input[id*='Tb_PC_Owner']").val(),
                    bank: $("input[id*='Tb_P_Bank']").val(),
                    bsc: $("input[id*='Tb_P_BSC']").val(),
                    acNo: $("input[id*='Tb_P_ACNo']").val(),
                    ccTypeId: $("select[id*='Dd_P_CcType']").val(),
                    ccNo: $("input[id*='Tb_P_CcNo']").val(),
                    ccValidityDate: $("input[id*='Tb_P_CcValidityDate_m']").val() + '/' + $("input[id*='Tb_P_CcValidityDate_y']").val()
                }),
                success: function (r) {
                    ret = JSON.parse(r.d);
                    var errorCode = parseInt(ret.errorCode);
                    var paymentId = parseInt(ret.paymentId);
                    switch (errorCode) {
                        case -1: // success
                            if (paymentTypeId == 204) {
                                $.Msg.Show("Bankverbindung gespeichert.");
                                if ($("input#Hf_P_UpdateCart").val() == 'True') {
                                    $.Cart.Payment.Update(paymentId);
                                } else {
                                    __doPostBack($("div#[id*='Up_Payment']").attr("id"), '');
                                }
                                $.Dialog.Close($("#dc_payment_bank"), true);
                            } else {
                                $.Msg.Show("Kreditkarte gespeichert.");
                                if ($("input#Hf_P_UpdateCart").val() == 'True') {
                                    $.Cart.Payment.Update(paymentId);
                                } else {
                                    __doPostBack($("div#[id*='Up_Payment']").attr("id"), '');
                                }
                                $.Dialog.Close($("#dc_payment_cc"), true);
                            }
                            break;
                        default:
                            $.Msg.Show("Fehler beim Hinzufügen der Zahlungsart!<br/>Fehlercode: " + errorCode, 1);
                            break;
                    }
                }
            });
        }
    }
}

$.News = {
    panelState: -1,
    visibleCategory: -1,
    data: false,
    type: 'tool',
    Init: function (callback) {
        if (!$.News.data) {
            $.ajax({
                contentType: "application/json; charset=utf-8",
                url: $.Presseplus.Config.SvcPath + '/NewsSelectTable',
                data: {},
                cache: false,
                success: function (r) {
                    $.News.data = JSON.parse(r.d);
                    if (typeof callback === 'function')
                        callback();
                }
            });
        } else if (typeof callback === 'function')
            callback();
    },
    Ticker: {
        Init: function (cphId) {
            var cph = cphId ? $('div#' + cphId) : $('div#CphToolNewsTicker');
            if (cph.length < 1) return false;
            $(cph).html('');
            $.News.type = $(cph).attr('class');
            $.News.Init(function () {
                if ($.News.data.length > 0) {
                    switch ($.News.type) {
                        case 'bibDefault':
                            $(cph).append('<h2>Nachrichten</h2>');
                            break;
                        default:
                            $(cph).append('<h2>Aktuelles von ' + SYS_PARAM_HOSTNAME + '</h2>');
                    }
                    $(cph).append('<div class="NewsTicker"><ul></ul></div>');
                    var nt = $('div#CphToolNewsTicker div.NewsTicker');
                    $.each($.News.data, function (k, v) {
                        switch ($.News.type) {
                            case 'bibDefault':
                                $(nt).children('ul').append('<li><a href="javascript:$.News.Panel.Show(' + v.WebNewsCategory_ID + ');">' + v.Headline + '</a></li>');
                                break;
                            default:
                                $(nt).children('ul').append('<li><h4>' + v.Category + '</h4><a href="javascript:$.News.Panel.Show(' + v.WebNewsCategory_ID + ');">' + v.Headline + '</a></li>');
                        }
                    });
                    $(nt).vTicker();
                }
            });
        }
    },
    Panel: {
        Init: function (callback) {
            $.News.panelState = 0;
            $.News.Init(function () {
                $('body').append('<div id="CphNews" class="hidden"></div>');
                var cph = $('div#CphNews');
                $(cph).append('<div id="DialogNews"><h2>Aktuelles von ' + SYS_PARAM_HOSTNAME + '</h2><ul id="NewsCategories"></ul><div id="NewsStage"></div><br class="clear" /></div>');
                var categories = $('ul#NewsCategories');
                var stage = $('div#NewsStage');
                $.each($.News.data, function (k, v) {
                    if ($(categories).children('li.newscat_' + v.WebNewsCategory_ID).length == 0) {
                        $(categories).append('<li class="newscat_' + v.WebNewsCategory_ID + '"><a href="javascript:$.News.Panel.Show(' + v.WebNewsCategory_ID + ');">' + v.Category + '</a></li>');
                    }
                });
                $.News.panelState = 1;
                if (typeof callback === 'function')
                    callback();
            });
        },
        Show: function (newsCategoryId, currentState) {
            if ($.News.panelState == currentState)
                return false;
            currentState = $.News.panelState;
            switch ($.News.panelState) {
                case -1:
                    $.News.Panel.Init(function () {
                        $.News.Panel.Show(newsCategoryId, currentState)
                    });
                    break;
                case 0: return; // ajax is loading 
                    break;
                case 1:
                    $.Dialog.Open(false, $('div#CphNews').html(), function () { $.News.panelState = 1; });
                    $.News.panelState = 2;
                    $.News.Panel.Show(newsCategoryId, currentState);
                    break;
                case 2:
                    var s = 300;
                    if ($('div#NewsStage').html() != '') {
                        $('div#NewsStage').hide();
                        $('div#NewsStage').html('');
                    }
                    $('ul#NewsCategories').children('li').each(function () { $(this).children('a').removeClass('active'); });
                    $.each($.News.data, function (k, v) {
                        if (v.WebNewsCategory_ID == newsCategoryId) {
                            $('div#NewsStage').append('<div class="item"><h2>' + v.Headline + '</h2>' + v.Text + '</div>');
                        }
                    });
                    $('ul#NewsCategories').children('li.newscat_' + newsCategoryId).children('a').addClass('active');
                    $('div#NewsStage').slideDown(s);
                    break;
            }
        }
    }
}

$.Msg = {
    Show: function (msg, type, callback) {
        type = type || 0;
        $("div#MsgDialog").detach();
        switch (type) {
            case 0: // notification
                $("body").append('<div id="MsgDialog" class="hidden">' + msg + '</div>');
                break;
            case 1: // error
                $("body").append('<div id="MsgDialog" class="hidden error">' + msg + '</div>');
                break;
            case 10: // notification - wait for action
                $("body").append('<div id="MsgDialog" class="hidden">' + msg + '</div>');
                break;
            case 11: // error - wait for action
                $("body").append('<div id="MsgDialog" class="hidden error">' + msg + '</div>');
                break;
        }
        $("#MsgDialog").css({
            top: (($(window).height() - $("#MsgDialog").outerHeight()) / 3) + $(window).scrollTop() + "px",
            left: (($(window).width() - $("#MsgDialog").outerWidth()) / 2) + $(window).scrollLeft() + "px"
        });
        if (type < 10) {
            $("#MsgDialog").fadeIn(400).delay(3000).fadeOut(400, function () {
                $("div#MsgDialog").detach();
                if (typeof (callback) === "function") {
                    callback();
                }
            });
        } else {
            $("#MsgDialog").fadeIn(400, callback);
        }
    }
}

var Utf8 = {
	encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) { utftext += String.fromCharCode(c); }
			else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); }
			else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); }
		}
		return utftext;
	},
	decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
		while ( i < utftext.length ) {
			c = utftext.charCodeAt(i);
			if (c < 128) { string += String.fromCharCode(c); i++; }
			else if((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i+1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; }
			else { c2 = utftext.charCodeAt(i+1); c3 = utftext.charCodeAt(i+2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; }
		}
		return string;
	}
}

/** Dialog **/
$.openDialogs = [];
$.Dialog = {
    Open: function (anchor, content, onClose) {
        /*
        if (anchor && $(anchor).attr("rel").length > 0) {
        var relList = $(anchor).attr("rel").split('|');
        $.each(relList, function (k, v) {
        var pair = v.split('=');
        $("input[id*='" + pair[0] + "']").val(pair[1]);
        });
        }*/
        $("#dialog div.close").click();
        $(content).appendTo("#dialog div.content");
        $("#dialog").draggable({ handle: "div.drag" });
        $("#dialog").css({
            width: $(content).width() > 0 ? $(content).width() : $(content).children('div::first-child').width(),
            top: (($(window).height() - $("#dialog").outerHeight()) * 0.3) + $(window).scrollTop() + "px",
            left: (($(window).width() - $("#dialog").outerWidth()) * 0.5) + $(window).scrollLeft() + "px"
        });
        $("#dialog div.close").click(function () {
            $.Dialog.Close(content, false, onClose);
        });
        $("#dialog").removeClass("hidden");
        $.openDialogs.push($(content).attr("id"));
    },
    Close: function (content, remove, callback) {
        $("#dialog").addClass("hidden");
        if (!remove && $.openDialogs.length > 0) {
            $("#dialog div.content").children().appendTo("#AJAX-OBJ-CACHE");
            $.openDialogs = jQuery.grep($.openDialogs, function (value) {
                return value != $(content).attr("id");
            });
        }
        $("#dialog div.content").html('');
        if (typeof (callback) === "function") {
            callback();
        }
    }
};
// Typewriter
$.fn.typewriter = function () {
    this.each(function () {
        var $ele = $(this), str = $ele.text(), progress = 0;
        $ele.text('');
        var timer = setInterval(function () {
            progress++;
            if (progress > str.length) {
                clearInterval(timer);
            } else $ele.text(str.substring(0, progress));
        }, 80);
    });
    return this;
};
/** Prepare DOM **/
$(document).ready(function () {
    try {
        $.News.Ticker.Init();
        $.Cart.Load();
        $("a.dialog-open").each(function () {
            $(this).click(function (ev) {
                $.Dialog.Open(this, $("div#" + $(this).attr("id").replace('do', 'dc')));
                return false;
            });
        });
        $('p.CHWechselkursRabatt').typewriter();
        var timer = setInterval(function () {
            $('p.CHWechselkursRabatt').typewriter();
        }, 10000);
    } catch (e) { /* do nothing */ }
});

/* http://www.JSON.org/json2.js */
var JSON;
if (!JSON) {
    JSON = {};
}
(function () {
    "use strict";
    function f(n) {
        return n < 10 ? '0' + n : n;
    }
    if (typeof Date.prototype.toJSON !== 'function') {
        Date.prototype.toJSON = function (key) {
            return isFinite(this.valueOf()) ?
                this.getUTCFullYear() + '-' +
                f(this.getUTCMonth() + 1) + '-' +
                f(this.getUTCDate()) + 'T' +
                f(this.getUTCHours()) + ':' +
                f(this.getUTCMinutes()) + ':' +
                f(this.getUTCSeconds()) + 'Z' : null;
        };
        String.prototype.toJSON =
            Number.prototype.toJSON =
            Boolean.prototype.toJSON = function (key) {
                return this.valueOf();
            };
    }
    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
        gap,
        indent,
        meta = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"': '\\"',
            '\\': '\\\\'
        },
        rep;
    function quote(string) {
        escapable.lastIndex = 0;
        return escapable.test(string) ? '"' + string.replace(escapable, function (a) {
            var c = meta[a];
            return typeof c === 'string' ? c :
                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
        }) + '"' : '"' + string + '"';
    }
    function str(key, holder) {
        var i,
            k,
            v,
            length,
            mind = gap,
            partial,
            value = holder[key];
        if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
            value = value.toJSON(key);
        }
        if (typeof rep === 'function') {
            value = rep.call(holder, key, value);
        }
        switch (typeof value) {
            case 'string':
                return quote(value);
            case 'number':
                return isFinite(value) ? String(value) : 'null';
            case 'boolean':
            case 'null':
                return String(value);
            case 'object':
                if (!value) {
                    return 'null';
                }
                gap += indent;
                partial = [];
                if (Object.prototype.toString.apply(value) === '[object Array]') {
                    length = value.length;
                    for (i = 0; i < length; i += 1) {
                        partial[i] = str(i, value) || 'null';
                    }
                    v = partial.length === 0 ? '[]' : gap ?
                    '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' :
                    '[' + partial.join(',') + ']';
                    gap = mind;
                    return v;
                }
                if (rep && typeof rep === 'object') {
                    length = rep.length;
                    for (i = 0; i < length; i += 1) {
                        if (typeof rep[i] === 'string') {
                            k = rep[i];
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                } else {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
                }
                v = partial.length === 0 ? '{}' : gap ?
                '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' :
                '{' + partial.join(',') + '}';
                gap = mind;
                return v;
        }
    }
    if (typeof JSON.stringify !== 'function') {
        JSON.stringify = function (value, replacer, space) {
            var i;
            gap = '';
            indent = '';
            if (typeof space === 'number') {
                for (i = 0; i < space; i += 1) {
                    indent += ' ';
                }
            } else if (typeof space === 'string') {
                indent = space;
            }
            rep = replacer;
            if (replacer && typeof replacer !== 'function' &&
                    (typeof replacer !== 'object' ||
                    typeof replacer.length !== 'number')) {
                throw new Error('JSON.stringify');
            }
            return str('', { '': value });
        };
    }
    if (typeof JSON.parse !== 'function') {
        JSON.parse = function (text, reviver) {
            var j;
            function walk(holder, key) {
                var k, v, value = holder[key];
                if (value && typeof value === 'object') {
                    for (k in value) {
                        if (Object.prototype.hasOwnProperty.call(value, k)) {
                            v = walk(value, k);
                            if (v !== undefined) {
                                value[k] = v;
                            } else {
                                delete value[k];
                            }
                        }
                    }
                }
                return reviver.call(holder, key, value);
            }
            text = String(text);
            cx.lastIndex = 0;
            if (cx.test(text)) {
                text = text.replace(cx, function (a) {
                    return '\\u' +
                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                });
            }
            if (/^[\],:{}\s]*$/
                    .test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
                        .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
                        .replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
                j = eval('(' + text + ')');
                return typeof reviver === 'function' ?
                    walk({ '': j }, '') : j;
            }
            throw new SyntaxError('JSON.parse');
        };
    }
} ());

/*
* vertical news ticker
* Tadas Juozapaitis ( kasp3rito@gmail.com )
* http://www.jugbit.com/jquery-vticker-vertical-news-ticker/
*/
(function($){
$.fn.vTicker = function(options) {
	var defaults = {
		speed: 4000,
		pause: 4500,
		showItems: 3,
		animation: 'fade',
		mousePause: true,
		isPaused: false,
		direction: 'up',
		height: 200
	};
	var options = $.extend(defaults, options);
	moveUp = function(obj2, height, options){
		if(options.isPaused) return;
		var obj = obj2.children('ul');
    	var clone = obj.children('li:first').clone(true);
		if(options.height > 0) {
			height = obj.children('li:first').height();
		}	
    	obj.animate({top: '-=' + height + 'px'}, options.speed, function() {
        	$(this).children('li:first').remove();
        	$(this).css('top', '0px');
        });
		if(options.animation == 'fade') {
			obj.children('li:first').fadeOut(options.speed);
			if(options.height == 0) {
			    obj.children('li:eq(' + options.showItems + ')').hide().fadeIn(options.speed).show();
			}
		}
    	clone.appendTo(obj);
	};
	moveDown = function(obj2, height, options){
		if(options.isPaused) return;
		var obj = obj2.children('ul');
    	var clone = obj.children('li:last').clone(true);
		if(options.height > 0) {
			height = obj.children('li:first').height();
		}
		obj.css('top', '-' + height + 'px').prepend(clone);
    	obj.animate({top: 0}, options.speed, function() {
        	$(this).children('li:last').remove();
        });
		if(options.animation == 'fade') {
			if(options.height == 0) {
				obj.children('li:eq(' + options.showItems + ')').fadeOut(options.speed);
			}
			obj.children('li:first').hide().fadeIn(options.speed).show();
		}
	};
	return this.each(function() {
		var obj = $(this);
		var maxHeight = 0;
		obj.css({overflow: 'hidden', position: 'relative'})
            .children('ul').css({position: 'absolute', margin: 0, padding: 0})
			.children('li').css({margin: 0, padding: 0});
		if(options.height == 0) {
			obj.children('ul').children('li').each(function(){
				if($(this).height() > maxHeight) {
					maxHeight = $(this).height();
				}
			});
			obj.children('ul').children('li').each(function(){
				$(this).height(maxHeight);
			});
			obj.height(maxHeight * options.showItems);
		}
		else {
			obj.height(options.height);
		}
    	var interval = setInterval(function(){ 
			if(options.direction == 'up') { 
				moveUp(obj, maxHeight, options); 
			}
			else { 
				moveDown(obj, maxHeight, options); 
			} 
		}, options.pause);
		if(options.mousePause) {
			obj.bind("mouseenter",function(){
				options.isPaused = true;
			}).bind("mouseleave",function(){
				options.isPaused = false;
			});
		}
	});
};
})(jQuery);
