/**
 * Dirty Browser Detection for CSS3Pie Issue in IE7
 */
var ddCss3Fix = function (options) {

    if ($.browser.msie && $.browser.version.indexOf(7) !== -1) {
        var elementToChange = options.element;
        $(elementToChange).css("top", "1px");
        window.setTimeout(function () {
            $(elementToChange).css("top", "0px");
        }, 50);
    }
};

/**
 * get called when document is ready
 */
var dd_loggedIn = false;
var cartData = null;
var isOneStep = false;
var dd_counter;

var trimInputFields = function (formId) {
    $('#' + formId + ' input').each(function () {
        $(this).val($.trim($(this).val()));
    });
};

var addClickLink = function (element, linkTarget)
{
    $(element).css('cursor', 'pointer');
    $(element).live('click', function (event) {
        window.location.href = linkTarget;
        return false;
    });
};

var updateAdition = function (data) {
    $('#adition-pixel').attr('src',
        'https://adfarm1.adition.com/track' +
        '?tid=1441&sid=4588&type=image&orderid=' +
        '&itemno='   + escape(encodeURIComponent(data.city)) +
        '&descr='    + escape(encodeURIComponent(data.ctTitle)) +
        '&quantity=' + escape(encodeURIComponent(data.ctQty)) +
        '&price='    + escape(encodeURIComponent(data.ctBasePrice)) +
        '&total='    + escape(encodeURIComponent(data.ctQtySum))
    );
};

var setClickColorboxOrLink = function (element, colorboxTarget, linkTarget) {
    if ($(colorboxTarget).length > 0) {
        $(element).click(function () {
            $.colorbox({
                inline: true,
                href: colorboxTarget
            });
            return false;
        });
    }
    else
    {
        addClickLink(element, linkTarget);
    }
    $(element).css('cursor', 'pointer');
};

var disableSubmits = function () {
    $('input[type=submit]').attr('disabled', 'disabled');
    $('input[type=button]').attr('disabled', 'disabled');
};

var enableSubmits = function () {
    $('input[type=submit]').removeAttr('disabled');
    $('input[type=button]').removeAttr('disabled');
};

var mailFunction = function () {
    parent.location = 'mailto:?Subject=' + encodeURIComponent($('#MBetreff').val()) + '&Body=' + encodeURIComponent($('#MNachricht').val());
    $.colorbox.close();
    return false;
};


var countUpTo = function (to) {
    var cnt = parseInt($('.dealsalesonp strong').text(), 10);
    var diff = to - cnt;
    if (to > cnt) {
        var add = Math.ceil(diff / 25);
        cnt += add;
        var wait = 4 + parseInt(80 / add, 10);
        $('.dealsalesonp strong').text(cnt);
        window.setTimeout('countUpTo(' + to + ');', wait);
    } else {
        $('.dealsalesonp strong').text(cnt);
        $('.dealsalesonp strong').fadeOut().fadeIn();
    }
};

var getCookie = function (c_name)
{
    if (document.cookie.length > 0) {
        var c_start = document.cookie.indexOf(c_name + "=");
        if (c_start !== -1) {
            c_start = c_start + c_name.length + 1;
            var c_end = document.cookie.indexOf(";", c_start);
            if (c_end === -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
};

var setCloseButtons = function () {
    $('.notificationClose').each(function () {
        $(this).click(function () {
            var toClose = $(this).attr('close');
            $(toClose).slideUp();
        });
    });
};

jQuery.validator.addMethod("emailblacklist", function (value, element) {
    if (this.optional(element)) {
        return true;
    }
    var checkMail = false;
    if (/^((([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)) {
        $.ajax({
            type: 'get',
            url: '/fast-ajax/validateEmail/email/' + encodeURIComponent(value) + '/',
            dataType: 'json',
            async:   false,
            success: function (data) {
                // do something
                if (data.error === 0) {
                    if (data.valid === 1) {
                        checkMail = true;
                    }
                }
            }
        });
    }
    return checkMail;
}, 'You cannot register with this email address.');

$(document).ready(function () {
    var requestUrl = window.location.pathname;
    var matches = requestUrl.match(/^.checkout.onestep.*/);
    var referCategoryId, referDealId;

    if (matches && matches.length > 0) {
        isOneStep = true;
    }
    if ($('#refer-data').length > 0) {
        referCategoryId = $('#refer-data').attr('categoryId');
        referDealId     = $('#refer-data').attr('dealId');
    } else {
        // use location if not on deal page
        referCategoryId = $('.yourcity').text();
        referDealId = '';
    }

    if ($('#nlsidebox').length === 0) {
        $('#nlheaderbox').hide();
    }

    $('#kaufen').live('click', function (event) {
        $(this).blur();
    });

    $('.dealinfoboxtop').live('click', function (event) {
        $(this).parent().find('.dib_body').slideToggle();
    });

    $('.diba1, .diba2, .diba3').live('click', function (event) {
        event.preventDefault();
    });
    setCloseButtons();
    var emailPlaceholder     = $('#defaultPlaceholders').attr('emailAddress');
    var passwordPlaceholder  = $('#defaultPlaceholders').attr('password');
    var msgRequired          = $('#error-messages').attr('required');
    var msgCcExpired         = $('#error-messages').attr('cc-expired');
    var msgPasswordMinlength = $('#error-messages').attr('password-minlength');
    var msgPasswordMin5      = $('#error-messages').attr('password-minlength5');
    var msgPasswordMatch     = $('#error-messages').attr('password-match');
    var msgZipcode           = $('#error-messages').attr('zipcode');
    var msgEmail             = $('#error-messages').attr('email');
    var msgEmailBlacklist    = $('#error-messages').attr('emailblacklist');
    var msgDob               = $('#error-messages').attr('dob');
    var msgConnectionProblem = $('#error-messages').attr('connectionProblem');

    var insertDob = function () {
        var dobDay = $('#choadress select[name=dobday]').val();
        var dobMonth = $('#choadress select[name=dobmonth]').val();
        var dobYear = $('#choadress select[name=dobyear]').val();
        var dob = dobYear + '-' + dobMonth + '-' + dobDay;

        if (dobDay.length > 0 && dobMonth.length > 0 && dobYear.length > 0) {

            var $dob = ($('#choadress input[name=dob]').length === 0) ?
                $('<input type="hidden" name="dob"/>').appendTo('#choadress') :
                $('#choadress input[name=dob]').first();

            $dob.val(dob);
        }
    };

    updateAdition = function (data) {
        $('#adition-pixel').attr('src', 'https://adfarm1.adition.com/track' +
            '?tid=1441&sid=4588&type=image&orderid=' +
            '&itemno='   + escape(encodeURIComponent(data.city)) +
            '&descr='    + escape(encodeURIComponent(data.ctTitle)) +
            '&quantity=' + escape(encodeURIComponent(data.ctQty)) +
            '&price='    + escape(encodeURIComponent(data.ctBasePrice)) +
            '&total='    + escape(encodeURIComponent(data.ctQtySum))
        );
    };

    if (!isOneStep) {
        addClickLink('#refer-bar', '/wie-funktioniert-freunde-empfehlen');
        addClickLink('#sideb-refer', '/wie-funktioniert-freunde-empfehlen');
        referCategoryId = referCategoryId.replace('/', '_');

        jQuery.getJSON('/fast-ajax/getDealData/c/' + referCategoryId + '/i/' + referDealId, function (data) {

            if (data.error === 0) {
                if ($('#deal').length > 0) {
                    data.soldItems = 0 + data.soldItems;
                    if (data.soldItems > 1 || data.soldItems === 0) {
                        var useCountUp = false;
                        if (data.soldItems > 1) {
                            useCountUp = true;
                        }
                        if (useCountUp) {
                            $('#dealcounter').html('<p class="verkauftedeals_on">' + txtDealsAlreadySold + '</p><p class="dealsalesonp roundedCorners"><strong>0</strong></p>');
                            if (data.soldItems > 0) {
                                countUpTo(data.soldItems);
                            }
                        } else {
                            $('#dealcounter').html('<p class="verkauftedeals_on">' + txtDealsAlreadySold + '</p><p class="dealsalesonp roundedCorners"><strong>' + data.soldItems + '</strong></p>');
                        }
                    } else {
                        $('#dealcounter').html('<p class="verkauftedeals_on">' + txtDealAlreadySold + '</p><p class="dealsalesonp roundedCorners"><strong>' + data.soldItems + '</strong></p>');
                    }

                    if (data.remainingTime <= 0) {  // run out, missed deal
                        $('#buynow').hide();
                        // Remove #buynow action from onclick (title and image)
                        $('#deal div.dealbild').unbind('click');
                        $('#deal div.dealbild').css('cursor', 'default');
                        $('h1.dealhead').unbind('click');
                        $('h1.dealhead').css('cursor', 'default');
                        $('#misseddetail').show();
                        $('.timebox').addClass('timebox_v').removeClass('timebox');
                        $('#giftButton').hide();
                        $('#menu li:nth-child(1) a').removeClass('current');
                        $('#menu li:nth-child(3) a').addClass('current');
                    } else { // deal still active

                        if (data.multideal) {
                            // Open Multi-Layer Deal //
                            $('#buynow, .dealbild, .dealhead').colorbox({
                                inline    : true,
                                href      : '#showmultideal',
                                width     : '750px',
                                iframe    : false,
                                scrolling : false
                            });
                            // Adjustments in the multi-layer Deal//
                            $('#buynow, .dealhead, .dealbild').colorbox({onLoad: function () {
                                $('#cboxClose').remove();
                                $('.showListing').hover(
                                    function () {
                                        $(this).addClass("optionColorHover").find(".dealTitle").addClass("optionColorFont");
                                    },
                                    function () {
                                        $(this).removeClass("optionColorHover").find(".dealTitle").removeClass("optionColorFont");
                                    });
                            }});

                            // show Buy button "options" //
                            $('.multidealButtonOption').show();
                            $('#kaufen').addClass('multibuttonTextRight');

                            $(data.multideal).each(function (index) {
                                // Calculation deals sold//
                                var hasMaximum = data.multideal[index].maximum_quantity !== 0;
                                var itemsLeft = 0;
                                var hasItemsLeft = true;

                                if (hasMaximum) {
                                    itemsLeft = (data.multideal[index].maximum_quantity - data.multideal[index].sold_items);
                                    hasItemsLeft = itemsLeft > 0;
                                }
                                var response = '';
                                var responseLink ='';
                                if (hasItemsLeft) {

                                    responseLink = '/checkout/onestep/index/product/' + data.multideal[index].id + '/category/' + referCategoryId;
                                    response += '<div class="buyButton gradientGreen roundedCorners">' +
                                        'kaufen' +
                                        '</div><div class="availableDeals">';


                                    if (hasMaximum) {
                                        response += 'noch verfügbar: ' + itemsLeft + '';
                                    }

                                } else {
                                    response += '<div class="availableDealsFinish">Ausverkauft</div>';
                                    responseLink = '#';
                                }

                                // Assembling the Multidealbox (<li> elements) //
                                $('ul#multiList').append('<a style="color:#666 !important" href="'+responseLink+'"><li class="showListing clearfix"><div class="dealTitle clearfix">' + data.multideal[index].description  +
                                        '<div class="optionSaving clearfix">' + data.multideal[index].discount + ' Rabatt - Sie sparen ' + data.multideal[index].you_save + '</div></div>'+
                                        '<div class="rightBox"><div class="multidealPrice"><span class="finalPrice"><span class="smallPrice">Preis: </span>' + data.multideal[index].price + '</span></div>' +
                                        '<div class="multidealBuy">' + response + '</div></li></a>');
                            }); // end multideal colorbox
                        } // end multideal

                        if (data.locked) {
                            $('#locked').show();
                            $('#kaufen').removeClass('kaufbutton roundedCorners gradientGreen ').addClass('kaufbuttonLocked lockedDeal lockedGoldButton').val('');

                            $('.lockedDeal, .dealbild, .dealhead').colorbox({
                                    inline    : true,
                                    href      : '#showlockeddeal',
                                    width     : '685px',
                                    height    : '400px',
                                    iframe    : false,
                                    scrolling : false
                              });

                        }

                        // Price only
                        if(0 === data.show_discount) {
                            // verpasste Deals
                            $(".dealprice br").remove();
                            var dealPriceValue = ($(".dealprice").html());
                            $('.saved').html(dealPriceValue);
                            $('.dealDiscountInfo').hide();
                            // Startseite
                            $('#sparinfosinglelayer').show().addClass('singleLayerSpecial');
                            $('.sparinfop').addClass('sparinfopSingle');
                            // Multideal Layer //
                            $('.optionSaving').html('');
                        } else {
                            $('#sparinfolayer').show();
                        }

                        $('#buynow').show();
                        ddCss3Fix({element: "#kaufen"});
                        // Bind #buynow action to onclick (title and image)
                        var buyNowAction = function () {
                            if ($('#buynow').attr('target') === '_blank') {
                                window.open($('#buynow').attr('action'), '_blank');
                            } else {
                                window.location.href = $('#buynow').attr('action');
                            }
                        };
                        if(!data.locked && !data.multideal) {
                            $('#deal div.dealbild, h1.dealhead').click(buyNowAction);
                        }

                        $('#deal div.dealbild').css('cursor', 'pointer');
                        $('h1.dealhead').css('cursor', 'pointer');
                        $('#giftButton').show();
                        ddCss3Fix({element: ".geschenkbutton"});
                        $('#misseddetail').hide();
                    } // end deal active

                    countdownIntervalId = window.setInterval(do_dd_countdown, 1000);
                }

                // checks if a maximum quantity is provided for the deal. if so, the counter will
                // switch to a different one.
                if (dd_counter !== null) {
                    var showLimited = data.maximumQuantity && data.maximumQuantity > 0;

                    dd_counter.show(showLimited ? dd_counter.limited : dd_counter.origin);

                    if (showLimited) {
                        dd_counter.setCounterValue(data.soldItems, data.maximumQuantity);
                    }
                }
            }
        });
    }

    $('#MSendEmail').click(function () {
        trimInputFields('modalempfehlung');
        $('#modalempfehlungJsonError').remove();
        if ($('#modalempfehlung').valid()) {
            disableSubmits();
            $('#msendemailLoader').show();
            $('label.validation-failed').remove();
            $('#refer-msg').hide();
            var postUrl = '';
            if (dd_loggedIn) {
                postUrl = '/referafriend/index/inviteSendAjax/';
            } else {
                postUrl = '/sendfriend/product/sendmail/';
            }
            $.ajax({
                type: 'post',
                url: postUrl,
                data: $('#modalempfehlung').serialize(),
                success: function (data) {
                    $('#msendemailLoader').hide();
                    if (data.error === 0) {
                        $.colorbox({inline: true, href: '#refer-sent'});
                    } else {
                        $('#refer-msg').html(
                            '<p id="modalempfehlungJsonError" class="infop errorp">' +
                            data.message + '</p>').show();
                        $.colorbox.resize();
                    }
                    enableSubmits();
                },
                error: function () {
                    $('#msendemailLoader').hide();
                    enableSubmits();
                },
                dataType: "json"
            });
        } else {
            $.colorbox.resize();
        }
    });

    $.validator.setDefaults({
        errorClass: 'mandatory180 mandatorytxt',
        onkeyup: false,
        onfocusout: false,
        onclick: false,
        focusCleanup: false,
        invalidHandler: function (form, validator) {
            $('label.mandatorytxt').remove();
        }
    });

    $('#mini-login-form').validate({
        rules: {
            'login[username]': {
                required: true,
                email: true
            },
            'login[password]': {
                required : true,
                minlength: 5
            }
        },
        messages: {
            'login[username]':  {
                required  : msgEmail,
                email     : msgEmail
            },
            'login[password]': {
                required   : msgPasswordMin5,
                minlength  : msgPasswordMin5
            }
        },
        errorClass: 'nothing',
        errorLabelContainer: "#loginerror",
        wrapper: 'p',
        invalidHandler: function () {
            /// $('#loginerror').empty();
        }
    });

    $('#pwdforget').validate({
        rules: {
            'fpwemail': {
                required: true,
                email: true
            }
        },
        messages: {
            'fpwemail':  {
                required  : msgEmail,
                email     : msgEmail
            }
        },
        errorClass: 'mandatorytxt'
    });

    $('#chokdlogin').validate({
        rules: {
            'login[username]': {
                required: true,
                email: true
            },
            'login[password]': {
                required : true,
                minlength: 5
            }
        },
        messages: {
            'login[username]':  {
                required  : msgEmail,
                email     : msgEmail
            },
            'login[password]': {
                required  : msgPasswordMinlength,
                minlength : msgPasswordMinlength
            }
        },
        errorClass: 'mandatory180 mandatorytxt',
        errorLabelContainer: "#myaccountloginerrors",
        wrapper: 'p',
        invalidHandler: function () {
            $('#myaccountloginerrors').empty();
        }

    });
    $('#choadress').validate({
        rules: {
            'prefix': 'required',
            'firstname': 'required',
            'lastname': 'required',
            'street': 'required',
            'postcode': {
                required : true,
                minlength: 4,
                maxlength: 5,
                digits   : true
            },
            'city': 'required',
            'country_id': 'required',
            'email': {
                required: true,
                email: true,
                emailblacklist: true
            },
            'password': {
                required : true,
                minlength: 6
            },
            'confirmation': {
                required: true,
                equalTo: "#Passwort"
            },
            'dob': {
                required: false,
                dateISO: true
            }
        },
        messages: {
            'prefix': {
                required: msgRequired,
                errorClass: 'mandatory180 mandatorytxt'
            },
            'firstname': {
                required: msgRequired,
                errorClass: 'mandatory180 mandatorytxt'
            },
            'lastname': {
                required: msgRequired,
                errorClass: 'mandatory180 mandatorytxt'
            },
            'street': {
                required: msgRequired,
                errorClass: 'mandatory180 mandatorytxt'
            },
            'postcode': {
                required  : msgRequired,
                minlength : msgZipcode,
                maxlength : msgZipcode,
                digits    : msgZipcode,
                errorClass: 'mandatory180 mandatorytxt'
            },
            'city': {
                required  : msgRequired
            },
            'country_id': {
                required: msgRequired
            },
            'email':  {
                required  : msgRequired,
                email     : msgEmail,
                emailblacklist: msgEmailBlacklist
            },
            'password': {
                required  : msgRequired,
                minlength : msgPasswordMinlength
            },
            'confirmation': {
                required  : msgRequired,
                equalTo   : msgPasswordMatch
            },
            'dob': {
                dateISO: msgDob
            }
        },
        errorClass: 'mandatorytxt mandatory180'
    });

    $('#myaaddress').validate({
        rules: {
            'prefix':  "required",
            'firstname':  "required",
            'lastname':   "required",
            'street':   "required",
            'postcode':   "required",
            'city':   "required",
            'country_id':   "required"

        },
        messages:  {
            'prefix':  msgRequired,
            'firstname':  msgRequired,
            'lastname':   msgRequired,
            'street':   msgRequired,
            'postcode':   msgRequired,
            'city':   msgRequired,
            'country_id':  msgRequired
        },
        errorClass: 'mandatorytxt mandatory180'
    });

    $('#contactform-submit').live('click', function (event) {
        if ($(event.target).is('input')) {
            event.preventDefault();
        }
        disableSubmits();
        jQuery.ajax({
            type: 'post',
            url: '/contacts/index/post/',
            data: $('#contactform').serialize(),
            dataType: 'json',
            success: function (data) {
                if (data.error === 0) {
                    $('#text-message').text(contactSendSuccess).show();
                    $('#error-message').hide();
                } else {
                    $('#error-message').text(data.errorMessage).show();
                    $('#text-message').hide();
                }
                enableSubmits();
            },
            error: function () {
                $('#error-message').text(contactSendFailure).show();
                $('#text-message').hide();
                enableSubmits();
            }
        });
    });

    // My account information forms and validation
    $('#myaccount-view-submit').live('click', function (event) {
        if ($(event.target).is('input')) {
            event.preventDefault();
        }
        $('#myaccount-view').hide();
        $('#myaccount-do').show();
    });

    $('#changemyaccount').validate({
        onkeyup: false,
        onfocusout: false,
        onclick: false,
        onblur: false,
        focusCleanup: true,
        ignore: '.ignore-validation',
        rules: {
            'customer[firstname]':  "required",
            'customer[lastname]':   "required",
            'customer[email]': {
                required:   true,
                email:      true,
                emailblacklist: true
            },
            'customer[password]': {
                required:   true,
                minlength:  5   // qype can has a 5 digit password
            },
            'customer[newpassword]': {
                required:   true,
                minlength:  6   // we want 6 digits though
            },
            'customer[newpassword2]': {
                required:   true,
                equalTo:    '#newpwd'
            }
        },
        messages:  {
            'customer[firstname]':  msgRequired,
            'customer[lastname]':   msgRequired,
            'customer[email]': {
                required:   msgRequired,
                email:      msgEmail,
                emailblacklist: msgEmailBlacklist
            },
            'customer[password]': {
                required:   msgRequired,
                minlength:  msgPasswordMin5
            },
            'customer[newpassword]': {
                required:   msgRequired,
                minlength:  msgPasswordMinlength
            },
            'customer[newpassword2]': {
                required:   msgRequired,
                equalTo:    msgPasswordMatch
            }
        },
        errorClass: 'mandatorytxt mandatory180',
        invalidHandler: function () {
            $('label.mandatorytxt').remove();
        }
    });


    $('#changepwd').live('click', function () {
        if ($('#changepwd').is(':checked')) {
            // switch validator on changed password change state
            $('#currentpwd').removeClass('ignore-validation');
            $('#newpwd').removeClass('ignore-validation');
            $('#newpwd2').removeClass('ignore-validation');

            $('#myaccountnpasswordchange').show();
        } else {
            // and switch the validator back
            $('#currentpwd').addClass('ignore-validation');
            $('#newpwd').addClass('ignore-validation');
            $('#newpwd2').addClass('ignore-validation');

            $('#myaccountnpasswordchange').hide();
        }
    });

    $('#myaccount-do-submit').live('click', function (event) {
        if ($(event.target).is('input')) {
            event.preventDefault();
        }
        $('label.mandatorytxt').remove();
        if ($('#changemyaccount').valid()) {
            disableSubmits();
            $('#address-edit-save-loader').show();
            $.ajax({
                type: 'post',
                url: '/ajax/request/customer/c/saveInfo/',
                data: $('#changemyaccount').serialize(),
                success: function (data) {
                    if (data.error === 0) {
                        $('#account-first').text($('#Vorname').attr('value'));
                        $('#account-last').text($('#Nachname').attr('value'));
                        $('#account-email').text($('#EMail').attr('value'));

                        $('#myaccount-view').show();
                        $('#myaccount-do').hide();
                        $('#error-message').hide();
                        $('#text-message').text(accountSavedSuccess).show();
                    } else {
                        $('#error-message').html(data.errorMessage);
                        $('#error-message').show();
                    }
                    enableSubmits();
                    $('#address-edit-save-loader').hide();
                },
                error: function () {
                    $('#error-message').text(msgConnectionProblem);
                    $('#error-message').show();
                    enableSubmits();
                    $('#address-edit-save-loader').hide();
                },
                dataType: 'json'
            });
        }
    });
    // End My account information forms and validation

    $('#chokdlogin').submit(function (event) {
        event.preventDefault();
        trimInputFields('chokdlogin');
        $('label.mandatorytxt').remove();
        if ($('#chokdlogin').valid()) {
            disableSubmits();
            $('#myaccountloginerrors').slideUp().empty();
            $('#submitloginLoader').show();
            $.ajax({
                type: 'POST',
                url: '/ajax/request/loginPost/',
                data: $('#chokdlogin').serialize(),
                success: function (data) {
                    if (data.error === 0) {
                        window.location.href = data.gotourl;
                    } else {
                        var error = $('<p class="error"></p>').html(data.message);
                        $('#myaccountloginerrors').append(error).slideDown();
                        $('#submitloginLoader').hide();
                        $.colorbox.resize();
                        var colorboxTimeout = function () {
                            $.colorbox.resize();
                        };
                        window.setTimeout(colorboxTimeout, 600);
                    }
                    enableSubmits();
                },
                error: function () {
                    var error = $('<p></p>').text(msgConnectionProblem);
                    $('#myaccountloginerrors').append(error).slideDown();
                    $('#submitloginLoader').hide();
                    $.colorbox.resize();
                    enableSubmits();
                },
                dataType: 'json'
            });
        } else {
            $.colorbox.resize();
        }
        $.colorbox.resize();
        return false;
    });



    $('#choadress').submit(function (event) {
        event.preventDefault();
        trimInputFields('choadress');
        insertDob();
        $('label.mandatorytxt').remove();
        if ($('#choadress').valid()) {
            disableSubmits();
            $('#submitregisterLoader').show();
            $('#registererrors').slideUp().empty();
            $.ajax({
                type: 'POST',
                url: '/ajax/request/createAccount/',
                data: $('#choadress').serialize(),
                success: function (data) {
                    if (data.error === 0) {
                        window.location.href = data.gotourl;
                    } else {
                        $('#registererrors').text(data.message).slideDown('normal', function () {
                            $.colorbox.resize();
                        });
                        $('#submitregisterLoader').hide();
                    }
                    enableSubmits();
                },
                error: function () {
                    $('#registererrors').text(msgConnectionProblem).slideDown();
                    $.colorbox.resize();
                    $('#submitregisterLoader').hide();
                    enableSubmits();
                },
                dataType: 'json'
            });
        } else {
            $.colorbox.resize();
        }
        return false;
    });


    $('#nlemail, #nlemail2, #loginmail, #myaccountloginmail, #fpwemail, #email, #ndvemail, #lpemail' +
        ', #nlSubscribeEmail').live('blur', function (event) {
        if ($(event.target).is('input') && $.trim($(this).val()) === '') {
            $(this).val(emailPlaceholder);
        }
    });
    $('#nlemail, #nlemail2, #loginmail, #myaccountloginmail, #fpwemail, #email, #ndvemail, #lpemail' +
        ', #nlSubscribeEmail').live('focus', function (event) {
        if ($(event.target).is('input') && $.trim($(this).val()) === emailPlaceholder) {
            $(this).val('');
        }
    });
    $('#loginpasswd, #myaccountloginpasswd, #Passwort').live('blur', function (event) {
        if ($(event.target).is('input') && $.trim($(this).val()) === '') {
            $(this).val(passwordPlaceholder);
        }
    });
    $('#loginpasswd, #myaccountloginpasswd, #Passwort').live('focus', function (event) {
        if ($(event.target).is('input') && $.trim($(this).val()) === passwordPlaceholder) {
            $(this).val('');
        }
    });
    $('#forgotpasswordloginlink, .fpwdlink').live('click', function (event) {
        if ($(event.target).is('a')) {
            var useFB = false;
            if ($(event.target).attr('rel') && $(event.target).attr('rel') === 'fb_pw_recover') {
                useFB = true;
            }
            if (!dd_loggedIn) {
                event.preventDefault();
                $.fn.colorbox({
                    inline: true,
                    maxWidth: 500,
                    href: '#forgotpassword'
                }, function () {
                    if (useFB) {
                        $('.dd_pw').hide();
                        $('.fb_pw').show();
                    } else {
                        $('.dd_pw').show();
                        $('.fb_pw').hide();
                    }
                    $.fn.colorbox.resize();
                });
                $('#fb_recover').val(useFB ? 1 : 0);
                $('#fpwemail').val($('#loginmail').val());
                $('#backToRegister').hide();
            }
        }
    });
    $('#registerForgotPassword, #registerForgotPassword_fb').live('click', function (event) {
        if ($(event.target).is('a')) {
            var useFB = false;
            if ($(event.target).attr('rel') && $(event.target).attr('rel') === 'fb_pw_recover') {
                useFB = true;
            }
            if (!dd_loggedIn) {
                event.preventDefault();
                $.fn.colorbox({
                    inline: true,
                    maxWidth: 500,
                    href: '#forgotpassword'
                }, function () {
                    if (useFB) {
                        $('.dd_pw').hide();
                        $('.fb_pw').show();
                    } else {
                        $('.dd_pw').show();
                        $('.fb_pw').hide();
                    }
                    $.fn.colorbox.resize();
                });
                $('#fb_recover').val(useFB ? 1 : 0);
                $('#fpwemail').val($('#myaccountloginmail').val());
                $('#backToRegister').show();
            }
        }
    });
    $('#backToRegisterLink').live('click', function (event) {
        if ($(event.target).is('a')) {
            if (!dd_loggedIn) {
                event.preventDefault();
                $.fn.colorbox({
                    inline: true,
                    href: '#customerCreate'
                });
                $('#myaccountloginmail').val($('#fpwemail').val());
            }
        }
    });

    $(".cityslide").click(function () {
        $('body , html').scrollTop(0);
        $("#city-panel").slideToggle("slow");
        return false;
    });

    $("#fb_box_follow_us, #blog_follow_us, #fb_follow_us, #tw_follow_us, #rss_follow_us, #googleplus_follow_us").click(function () {
        window.open(this.href);
        wt_sendinfo($(this).attr('ti'), 'click');
        return false;
    });

    $("#enlargemaplink, #enlargemapimage").colorbox({
        width: "600",
        height: "400",
        iframe: true,
        href: $('#enlargemaplink').attr('href')
    });

    var keks = document.cookie;
    if (!keks || keks.indexOf("NLBoxed") < 0) {
        $.cookie('NLBoxed', '1', {expires: 30, path: '/'});
        // ck: avoid nl teaser on reminder landing pages
        if (!window.location.href.match('newsletter/subscriber/remind/id')) {
            $.colorbox({
                inline    : true,
                href      : '#nlbox',
                width     : '790px',
                iframe    : false,
                scrolling : false
            });
        }
    }


    if (!isOneStep) {
        // login box loader and update for location select
        var customerStateCall, isCart;
        if (($('#checkoutSteps').length > 0)) {
            customerStateCall = '/ajax/request/customerState/pg/cart';
            isCart = true;
        } else {
            customerStateCall = '/fast-ajax/getCustomerState';
            isCart = false;
        }
        if ($('#refer-data').length > 0) {
            customerStateCall += "/product/" + referDealId;
            customerStateCall += "/category/" + referCategoryId;
        }

        $.getJSON(customerStateCall, function (data) {
            if (data.error === 0) {
                // social networking stuff, only on deal view
                if ($('#refer-data').length > 0) {
                    if ($("#modalempfehlung").length > 0) {

                        if (data.social.fbLink === "none") {
                            $("#modalempfehlung").validate({
                                rules: {
                                    'sender[name]':  "required",
                                    'sender[email]':  {
                                        required: true,
                                        email:    true,
                                        emailblacklist: true
                                    },
                                    'recipients[name][]':   "required",
                                    'recipients[email][]':  {
                                        required: true,
                                        email:    true,
                                        emailblacklist: true
                                    },
                                    'sender[subject]': "required",
                                    'sender[message]': "required"
                                },
                                messages: {
                                    'sender[name]' : msgRequired,
                                    'sender[email]': {
                                        required: msgRequired,
                                        email: msgEmail,
                                        emailblacklist: msgEmailBlacklist
                                    },
                                    'recipients[name][]' : msgRequired,
                                    'recipients[email][]':  {
                                        required: msgRequired,
                                        email: msgEmail,
                                        emailblacklist: msgEmailBlacklist
                                    },
                                    'sender[subject]': msgRequired,
                                    'sender[message]': msgRequired
                                },
                                errorClass: 'validation-advice-refer validation-failed',
                                invalidHandler: function () {
                                    $('label.validation-failed').remove();
                                }
                            });
                        } else {
                            $("#modalempfehlung").validate({
                                rules: {
                                    'recipients[name][]' : "required",
                                    'recipients[email][]': {
                                        required: true,
                                        email:    true,
                                        emailblacklist: true
                                    },
                                    'sender[subject]': "required",
                                    'sender[message]': "required"
                                },
                                messages: {
                                    'recipients[name][]' : msgRequired,
                                    'recipients[email][]': {
                                        required: msgRequired,
                                        email: msgEmail,
                                        emailblacklist: msgEmailBlacklist
                                    },
                                    'sender[subject]': msgRequired,
                                    'sender[message]': msgRequired
                                },
                                errorClass: 'validation-advice-refer validation-failed',
                                invalidHandler: function () {
                                    $('label.validation-failed').remove();
                                }
                            });
                        }
                    }

                    if (data.social.fbLink === "none") {
                        $(".view_fb_link").colorbox({inline: true, href: "#social-anon-popup"});
                        $(".view_tw_link").colorbox({inline: true, href: "#social-anon-popup"});
                        $(".view_sv_link").colorbox({inline: true, href: "#social-anon-popup"});

                        $("#mview_fb_link").attr("href", data.social.fbAnonLink);
                        $("#mview_tw_link").attr("href", data.social.twAnonLink);
                        $("#mview_sv_link").attr("href", data.social.svAnonLink);
                        $("#mview_em_link").colorbox({inline: true, href: "#recommend-email-popup", innerWidth: "695px"});
                    } else {
                        $('.view_fb_link').attr("href", data.social.fbLink);
                        $('.view_fb_link').attr("target", '_blank');
                        $('.view_sv_link').attr("href", data.social.svLink);
                        $('.view_sv_link').attr("target", '_blank');
                        $('.view_tw_link').attr("href", data.social.twLink);
                        $('.view_tw_link').attr("target", '_blank');
                        $('#refer-anon-msg').hide();
                        $('#refer-anon-sender').hide();
                    }
                    $('.view_em_link').colorbox({inline: true, href: "#recommend-email-popup", innerWidth: "695px"});

                    setClickColorboxOrLink('#msnlogin',    '#customerCreate', '/customer/account');
                    setClickColorboxOrLink('#msnregister', '#customerCreate', '/customer/account');
                    setClickColorboxOrLink('#memlogin',    '#customerCreate', '/customer/account');
                    setClickColorboxOrLink('#memregister', '#customerCreate', '/customer/account');

                    $('#memmail').click(mailFunction);
                    if (data.social.dealName === null)
                    {
                        $('#MBetreff').val(dailydeal);
                        $('#MNachricht').val(mightInterest2 + '\n\n' + clickIfInterested2 + '\n\n' + data.social.emLink + '\n\n' + bestRegards);
                    }
                    else
                    {
                        $('#MBetreff').val(data.mailSubject);
                        $('#MNachricht').val(mightInterest + '\n\n' + data.social.dealName + '\n\n' + clickIfInterested + '\n\n' + data.social.emLink + '\n\n' + bestRegards);
                    }

                    $('.view_fb_link img').show();
                    $('.view_em_link img').attr("innerWidth", "688px");
                    $('.view_em_link img').show();
                    $('.view_tw_link img').show();
                    $('.view_sv_link img').show();
                }

                // cart stuff
                if (isCart) {
                    updateAdition(data.cart);
                    loadCartData(data.cart);
                } else { // tracking stuff
                    if (data && data.mcParameter && data.mcParameter !== '') {
                        if (typeof(wt_setTrackingSwitchMcParameter) !== 'undefined' && wt_setTrackingSwitchMcParameter) {
                            if (data.mcTrackerId && data.mcTrackerId !== '') {
                                wt_setTrackingSwitchMcParameter(data.mcParameter, data.mcTrackerId);
                            } else {
                                wt_setTrackingSwitchMcParameter(data.mcParameter, '');
                            }
                        }
                    }
                }

                // for the newsletter email input fields
                // $('#email, #nlemail, #nlemail2').val(data.email);
                // for newsletter header wording
                if (data.loggedIn === 1) {
                    if (typeof SnapABug !== 'undefined' && SnapABug && data.email !== '') {
                        SnapABug.setUserEmail(data.email);
                    }
                    if (1 === data.nlGetBonus) {
                        /* Enable Bonus title, if user can get bonus */
                        $('#yournlp').text(newsletterBonus);
                        $('#newsletter_sidebar').text(newsletterBonusSidebar);
                    }
                    else {
                        /* Disable Bonus title, if user cannot get bonus */
                        $('#yournlp').text(newsletter);
                        $('#newsletter_sidebar').text(newsletterSidebar);
                    }
                    $('#loginerror').hide();
                    $('#register-now-text').text(greetingLoggedIn.replace('%name%', data.name));
                    dd_loggedIn = true;
                    $('#login-slider-button-text')
                        .text($('#defaultPlaceholders')
                        .attr('logout'));
                    $("#login-slider-button, #login-logout").click(function (event) {
                        if (dd_loggedIn) {
                            $.colorbox({
                                inline: true,
                                href: '#dologout',
                                width: '500px'
                            });
                            window.location.href = '/customer/account/logout/';
                        }
                        return false;
                    });
                    addClickLink('#register-now-text', '/customer/account/');
                    $('#nlemail2').val(data.email);
                } else {
                    /* Disable Bonus title, if user is nott logged in */
                    $('#yournlp').text(newsletter);
                    $('#newsletter_sidebar').text(newsletterSidebar);
                    dd_loggedIn = false;
                    $('#register-now-text').text(greetingUnknown);
                    $('#login-slider-button-text')
                        .text($('#defaultPlaceholders')
                        .attr('login'));
                    $("#login-slider-button, #login-logout").click(function (event) {
                        $("#login-panel").slideToggle("slow");
                    });
                    setClickColorboxOrLink('#register-now-text',    '#customerCreate', '/customer/account/');
                }
                $('#myAccount').click(function (event) {
                    if (!dd_loggedIn) {
                        event.preventDefault();
                        $.fn.colorbox({
                            inline: true,
                            href: '#customerCreate'
                        });
                    } else {
                        addClickLink('#myAccount', '/customer/account/coupons');
                    }
                });
            }
        });
    }


    var updatePager = function () {
        var pageId = $('#page_id').text();
        var pageCount = $('#page_count').text();
        if (pageId <= 1) {
            $('#page_left').hide();
        } else {
            $('#page_left').show();
        }
        if (pageId >= pageCount) {
            $('#page_right').hide();
        } else {
            $('#page_right').show();
        }
    };

    var updatePage = function (pageId) {
        var itemsPerPage = parseInt($('#page_items').text(), 10);
        var oldPageId = $('#page_id').text();
        $('#page_id').text(pageId);
        var firstItem = ((oldPageId - 1) * itemsPerPage) + 1;
        var lastItem  = firstItem + itemsPerPage - 1;
        var i;
        for (i = lastItem; i >= firstItem; --i) {
            $('#page_item_' + i).hide();
        }
        firstItem = ((pageId - 1) * itemsPerPage) + 1;
        lastItem  = firstItem + itemsPerPage - 1;
        for (i = firstItem; i <= lastItem; ++i) {
            $('#page_item_' + i).show();
        }
        updatePager();
    };


    if ($('#page_left').length > 0) {
        updatePager();
        $('#page_right').live('click', function (event) {
            event.preventDefault();
            var newPage = parseInt($('#page_id').text(), 10) + 1;
            updatePage(newPage);
        });
        $('#page_left').live('click', function (event) {
            event.preventDefault();
            var newPage = parseInt($('#page_id').text(), 10) - 1;
            updatePage(newPage);
        });

    }

    $('#mini-login-form').submit(function (event) {
        event.preventDefault();

        if ($('#mini-login-form').valid()) {
            disableSubmits();
            $('#loginerror').slideUp().empty();
            $.ajax({
                type: 'POST',
                url: '/ajax/request/loginPost/',
                data: $('#mini-login-form').serialize(),
                success: function (data) {
                    enableSubmits();
                    if (data.error === 0) {
                        // for newsletter header wording
                        $('#yournlp').text(data.nlheadertext);
                        window.location.href = data.gotourl;
                    } else {
                        var error = $('<p></p>').html(data.message);
                        $('#loginerror').append(error).slideDown();
                        var closeButton = $('<span></span>').html('<span close="#loginerror" class="notificationClose" />');
                        $('#loginerror p').prepend(closeButton).slideDown();
                        setCloseButtons();
                    }
                },
                error: function () {
                    enableSubmits();
                    var error = $('<p></p>').text(msgConnectionProblem);
                    $('#loginerror').append(error).slideDown();
                },
                dataType: 'json'
            });
        } else {
            var closeButton = $('<p></p>').html('<span close="#loginerror" class="notificationClose" />');
            $('#loginerror p label').prepend(closeButton).slideDown();
            setCloseButtons();
            enableSubmits();
        }
        return false;
    });

    $('#pwdforget input[type=submit]').live('click', function (event) {
        event.preventDefault();

        
        if ($('#pwdforget').valid()) {
            disableSubmits();
            $('#forgotpwconnectionerror').hide();
            $('#forgotpwerrors').hide();
            $.colorbox.resize();
            $('#forgotpwloading').show();
            $.ajax({
                type: 'POST',
                url: '/ajax/request/forgotPassword/',
                data: $('#pwdforget').serialize(),
                success: function (data) {
                    $('#forgotpwloading').hide();
                    if (data.error === 0) {
                        $.colorbox({
                            inline: true,
                            href: '#forgotpwsent'
                        });
                        $('#loginerror').slideUp().empty();
                    } else {
                        $('#forgotpwerrors').show();
                        $.colorbox.resize();
                    }
                    enableSubmits();
                },
                error: function () {
                    $('#forgotpwloading').hide();
                    $('#forgotpwconnectionerror').show();
                    $.colorbox.resize();
                    enableSubmits();
                },
                dataType: 'json'
            });
        } else {
            $.colorbox.resize();
        }
        return false;
    });

    setClickColorboxOrLink('#loginlink',    '#customerCreate', '/customer/account');

    $("#recommend_store_button").click(function (event) {
        $.colorbox({
            inline: false,
            href: '/partner/recommend',
            width: '730px',
            height: '556px'
        });
        return false;
    });

    // padlock
    $("#sendCode").click(function() {
        var code = escape($('#codeNumberField').val());
        $('#sendCode').hide();
        $('.ajaxLoaderScreen').show();
        $.get('/fast-ajax/padlock/product/' + referDealId + '/code/' + code, {}, function(data) {

            if (data.error != 0 || data.valid == false) {
                var errorMessage ='';
                errorMessage ='Dieser Deal-Key ist leider nicht gültig. Bitte gib Deinen Deal-Key erneut ein!';
                $('#sendCode').show();
                $('.ajaxLoaderScreen').hide();
                $('.errorCode').text(errorMessage).show();

            } else {
                location.href = $('#buynow').attr('action') + 'code/' + code;
            }
        });
    });
});

$('#dashboardDeletePaymentOption').live('click', function (event) {
    event.preventDefault();
    $('#deletePayment-please-wait').show();
    $.ajax({
        type: 'post',
        url: '/customer/account/deletePaymentData',
        data: null,
        success: function (data) {
            $('#deletePayment-please-wait').hide();
            if (data.error == 0) {
                window.setTimeout(function () {
                    $('#dashboard-stored-payment').show().html(data.success);
                    window.setTimeout(function () {
                        $('#dashboard-stored-payment').fadeOut();
                    }, 5000);
                }, 500);
            } else {
                // error handling
            }
        },
        error: function () {
            $('#deletePayment-please-wait').hide();
            alert(contactSendFailure);
        },
        dataType: "json"
    });
});

$(document).ready(function () {
    $('#finalCustomerLink').click(function () {
        $('#finalCustomer').show();
        $('#finalBusiness').hide();
        $('#text-message-new').hide();
    });

    $('#businessCustomerLink').click(function () {
        $('#finalCustomer').hide();
        $('#finalBusiness').show();
        $('#text-message-new').hide();
    });


    $('#showButtonInfoBox').click(function () {
        $('#showContentLayer').show();
        $(this).hide();

        $('#closeButtonInfoBox').show();
    });
    $('#closeButtonInfoBox').click(function () {
        $('#showContentLayer').hide();
        $(this).hide();
        $('#showButtonInfoBox').show();
    });

    // Auslesen get Parameter //

    var HTTP_GET_VARS = [];
    var strGET = document.location.search.substr(1, document.location.search.length);
    if (strGET !== '') {
        var gArr = strGET.split('&');
        for (var i = 0; i < gArr.length; ++i) {
            var v = '';
            var vArr = gArr[i].split('=');
            if (vArr.length > 1) {
                v = vArr[1];
            }
            HTTP_GET_VARS[unescape(vArr[0])] = unescape(v);
        }
    }

    function GET(v) {
        return !HTTP_GET_VARS[v] ? 'undefined' : HTTP_GET_VARS[v];
    }

    if (GET('success') === 1) {
        $('#text-message-new').text(contactSendSuccess).show();
    }

    $('#salesforces_submit').click(function () {
        $('.mandatory_business').each(function () {
            if ($(this).val() === "") {
                $(this).addClass('errorBorder');
            } else {
                $(this).removeClass('errorBorder');
            }
        });
        if ($('.errorBorder').length === 0) {
            $('#salesforces').submit();
        }
    });

    $("#00ND0000003Traf").change(function() {

        $('#00ND0000003Tsvi option').hide();
        var currentClassSub = $("#00ND0000003Traf option:selected").attr("id");
        $("#00ND0000003Tsvi option[class='firstElement']").attr('selected', true);
        $('#00ND0000003Tsvi .' + currentClassSub).show();
    });

});

