var iContentTextSize = 11;
var sVoucherFormTpl = '';
var bIsIe6 = (/MSIE (\d+\.\d+);/.test(navigator.userAgent) && new Number(RegExp.$1) == 6) ? true : false;
var iOpacityAnimDuration = ($.support.opacity) ? 1000 : 0;

// hilfsfunktionen
formatPrice = function(iIn)
{
    return numberFormat(iIn, 2, ',', '.');
}

function numberFormat( number, laenge, sep, th_sep )
{
    number = Math.round( number * Math.pow(10, laenge) ) / Math.pow(10, laenge);
    str_number = number+"";
    arr_int = str_number.split(".");
    if(!arr_int[0]) arr_int[0] = "0";
    if(!arr_int[1]) arr_int[1] = "";
    if(arr_int[1].length < laenge)
    {
        nachkomma = arr_int[1];
        for(i=arr_int[1].length+1; i <= laenge; i++){   nachkomma += "0";   }
        arr_int[1] = nachkomma;
    }
    if(th_sep != "" && arr_int[0].length > 3)
    {
        Begriff = arr_int[0];
        arr_int[0] = "";
        for(j = 3; j < Begriff.length ; j+=3)
        {
            Extrakt = Begriff.slice(Begriff.length - j, Begriff.length - j + 3);
            arr_int[0] = th_sep + Extrakt + arr_int[0] + "";
        }
        str_first = Begriff.substr(0, (Begriff.length % 3 == 0)?3:(Begriff.length % 3));
        arr_int[0] = str_first + arr_int[0];
    }
    return arr_int[0]+sep+arr_int[1];
}

toggleDiv = function(sElementId, checkBox, hideOthers)
{
    checked = (!checkBox) ? $('#' + sElementId).css('display') == 'none' : checked = checkBox.checked || !checkBox;    
    if(checked)
    {
        $('#' + sElementId).slideDown(200);
    }
    else
    {
        $('#' + sElementId).slideUp(200).find('input').removeClass('error').qtip('destroy');
    }
}

var aCosts = {};
updateCheckoutPrice = function()
{
    if(typeof fTax19 == 'undefined')
    {
        return;
    }

    var aPreselectedValues = {};
    $(".inputradio").each(function()
    {
        if(this.checked)
        {
            aPreselectedValues[this.name] = this.value;
        }
        else
        {
            aCosts[this.name] = 0;
            $('#' + this.name + 'Price').text(formatPrice(aCosts[this.name]));
        }
        
        if(!this.onclick)
        {
            oldOnClick = this.onclick;
            this.onclick = function()
            {
                if(aIncompatible[this.value])
                {
                    var iDeliveryId = this.value;
                    $('input:radio[name="payment"]').each(function()
                    {
                        if($.inArray(this.value, aIncompatible[iDeliveryId]) > -1)
                        {
                            $(this).attr('disabled', 'disabled').val([]).parent().addClass('disabled');
                        }
                        else
                        {
                            $(this).removeAttr('disabled').parent().removeClass('disabled');
                        }
                    });
                }
                
                aCosts[this.name] = numberFormat( eval(fProductsPrice + ' ' + aCalculations[this.name][this.value]), 2, '.', '' ) - fProductsPrice;
                $('#' + this.name + 'Price').text(formatPrice(aCosts[this.name])).parent().parent().css({display: aCosts[this.name] ? 'table-row' : 'none'});
                
                // adjust price
                fTax19AddCost = ((aCosts['delivery'] + aCosts['payment']) - ((aCosts['delivery'] + aCosts['payment']) * 100 / 119));
                $('#tax19').text(formatPrice(fTax19 + fTax19AddCost));
                fTotalPrice = aCosts['delivery'] + aCosts['payment'] + fProductsPrice;
                fPriceToPay = fTotalPrice;
                
                if(typeof fVoucherValueTapir == 'number' && fVoucherValueTapir !== null)
                {
                    fPriceToPay -= fVoucherValueTapir;
                }
                if(fCreditFromAccount > 0)
                {
                    fPriceToPay -= fCreditFromAccount;
                }
                if(fPriceToPay <= 0)
                {
                    $('input[name=payment]').attr('disabled', 'disabled').val([]).parent().addClass('disabled');
                }
                if(fPriceToPay < 0)
                {
                    $('#creditToAccount').css({display: 'table-row'}).find('td:nth-child(2)').text(formatPrice(Math.abs(fPriceToPay)) + ' €');
                    fPriceToPay = 0;
                }
                else
                {
                    $('#creditToAccount').css({display: 'none'});
                }
                $('#totalPrice').text(formatPrice(fTotalPrice));
                $('#priceToPay').text(formatPrice(fPriceToPay));
            }
        }
    });
    
    for(var sNodeName in aPreselectedValues)
    {
        aCosts[sNodeName] = eval(fProductsPrice + ' ' + aCalculations[sNodeName][aPreselectedValues[sNodeName]]) - fProductsPrice;
        $('#' + sNodeName + 'Price').text(formatPrice(aCosts[sNodeName]));
    }

    // adjust price
    fTax19 = fTax19 - ((aCosts['delivery'] + aCosts['payment']) - ((aCosts['delivery'] + aCosts['payment']) * 100 / 119));
    fTotalPrice = aCosts['delivery'] + aCosts['payment'] + fProductsPrice;
    fPriceToPay = fTotalPrice;

    if(typeof fVoucherValueTapir == 'number' && fVoucherValueTapir !== null)
    {
        fPriceToPay -= fVoucherValueTapir;
    }
    if(fCreditFromAccount > 0)
    {
        fPriceToPay -= fCreditFromAccount;
    }
    if(fPriceToPay <= 0)
    {
        $('input[name=payment]').attr('disabled', 'disabled').val([]).parent().addClass('disabled');
    }
    if(fPriceToPay < 0)
    {
        $('#creditToAccount').css({display: 'table-row'}).find('td:nth-child(2)').text(formatPrice(-fPriceToPay) + ' €');
        fPriceToPay = 0;
    }
    else
    {
        $('#creditToAccount').css({display: 'none'});
    }
    $('#totalPrice').text(formatPrice(fTotalPrice));
    $('#priceToPay').text(formatPrice(fPriceToPay));
}

selectClick = function(e)
{
    if($(e.target).parent().get(0).nodeName == 'LI' || $(e.target).get(0).nodeName == 'LI')
    {   
        return;
    }

    $('.selectBox ul, .naviSelectBox ul').hide();
    $(this).find('ul').show(20, function()
    {
        $('body').bind('click.selectHide', function(e)
        {
            if($('#fancy_div').is(':visible'))
            {
                return false;
            }

            $('.selectBox ul, .naviSelectBox ul').hide();
            $('body').unbind('click.selectHide');
        });
    });
}

selectLiClick = function()
{
    if($(this).hasClass('delivery'))
    {
        return false;
    }
    $(this).parent().hide().find('li').removeClass('active');
    $(this).addClass('active').parent().parent().find('div span').text($(this).find('span').text());
}

// allgemeiner start
startApp = function()
{
    // home teaser rotator
    $('.homeTeaser').clone().appendTo('.teaserRotator').removeClass('homeTeaser');
    $('.homeTeaser').remove();
    $('.teaserRotator').teaserRotator();
    
    // form validation 
    $("button:submit").removeClass('disabled');
    $(window).unload(function(){});
    $("#content form:not(#reservationForm form, #payPalForm, #formTShops, #backInStockNotificationForm)").each(function()
    {
        // no validation required
        //if(!$(this).has('input[type=text]').length)
        //{
            $(this).bind('submit', function()
            {
                this.bSubmitted = this.bSubmitted || false;
                if (this.bSubmitted)
                {
                    return false;
                }
                else
                {
                    this.bSubmitted = true;
                    $(this).find("button:submit").addClass('disabled');
                    return true;
                }
            });
            return;
        //}
        
        /* 
        // validate
        if(typeof $.validator == 'undefined')
        {
            return;
        }
        
        $.validator.messages['required'] = 'Dieses Feld ist ein Pflichtfeld.';
        $.validator.messages['email'] = 'Bitte tragen Sie Ihre Emailadresse ein.';
        var sCurrentCountryCode = 'DE';
        $.validator.addMethod("zip", 
            function(mValue, element)
            {
                bValid = false;
                mValue = $.trim(mValue);
                if(/^\d+$/.test(mValue) == false)
                {
                    return this.optional(element) || bValid;
                }

                valid = true;
                sCurrentCountryCode = $(element).parent().parent().parent()
                    .find('select[name*="landkennzeichen"]')
                    .change(function(){$(element).qtip('destroy');})
                    .val();
                        
                $(element).attr('title', oValidatorZipMessages[sCurrentCountryCode]);
                if(sCurrentCountryCode == 'DE')
                {
                    bValid = this.getLength(mValue, element) == 5;
                }
                else if(sCurrentCountryCode == 'AT')
                {
                    bValid = this.getLength(mValue, element) == 4;
                }
                
                $(element).val(mValue);
                return this.optional(element) || bValid;
            }
        );

        $(this).validate(
        {
            ignore: ':hidden',
            success: function(errorlabel)
            {
                setTimeout(function() {
                   $('.valid').qtip('destroy');
                }, 1);
            },
            rules: {
                'aData[passwort]': {
                    minlength: 5
                },
                'aData[passwort2]': {
                    minlength: 5,
                    required: true,
                    equalTo: "#passwort"
                },
                'aData[email]': {
                    required: true,
                    email: true
                },
                'aData[email2]': {
                    required: true,
                    equalTo: "#email"
                },
                'aData[plz]': "zip",
                'aData[l_plz]': "zip",
                'aData[tel]': {
                    minlength: 8
                }
            },
            submitHandler: function(form)
            {
                form.bSubmitted = form.bSubmitted || false;
                if (form.bSubmitted)
                {
                    return false;
                }
                else
                {
                    form.bSubmitted = true;
                    $(form).find("button:submit").addClass('disabled');
                    form.submit();
                }
            },
            errorPlacement: function(errorlabel, inputelement)
            {    
                if(!$(errorlabel).text() || $(inputelement).is(':hidden'))
                {
                    $(inputelement).removeClass('error');
                    return;
                }
                var oPosition = { my: 'left center', at: 'right center' };
                if(/plz/.test($(errorlabel).attr('for')))
                {
                    oPosition = { my: 'right center', at: 'left center' };
                }
                // oPosition.adjust = {screen: true, target: $(document), resize: true};
      
                $(inputelement).filter(':not(.valid)').qtip(
                {
                   overwrite: false,
                   content: errorlabel,
                   position: oPosition,
                   show: {
                      event: false,
                      ready: true
                   },
                   hide: false,
                   style: {
                      tip: true,
                      classes: 'ui-tooltip-jtools'
                   }
                });
            }
        });
        */
    });
    
    // navi over
    $('#nav li:not(#nav li li)')
        .mouseover(function(){$(this).addClass("over");})
        .mouseout(function(){$(this).removeClass("over");});   
        
    // buttons
    $('button').wrapInner('<span><span></span></span>');
    $('a.button').wrapInner("<span></span>");
   
    // links ohne rahmen
    $('a').focus(function(){if(this.blur)this.blur();});
    
    // external
    $('a.blank').click(function(){window.open(this.href); return false;});
   
    // selectboxen
    $('.selectBox, .naviSelectBox').not(":has(div[class*='inactive'])").bind('click.selectClick', selectClick).find('ul li').not(':has(a)').bind('click.selectLiClick', selectLiClick);
    
    // voucher value form
    initVoucherForm();
    
    // suche initialisieren
    if(sSearchAjaxUrl)
    {
        $('#searchbox').autocomplete(sSearchAjaxUrl.replace(/&amp;/g, '&'));
    }

    // produktdetails toggle
    sToggleName = '';
    if($('#productDescription').length)
    {
        sToggleName = 'product';
    }
    else if($('#categoryDescription').length)
    {
        sToggleName = 'category';
    }
    if(sToggleName)
    {
        var fHeight = 162;
        var sTextDown = '';//'Details einblenden';
        var sTextUp = '';//'Details ausblenden';
        var sClassNameDn = 'blindDn';
        var sClassNameUp = 'blindUp';
        
        var fTextHeight = $('#' + sToggleName + 'Description').height();
        var bDown = false;
        
        if(fTextHeight > fHeight)
        {
            if($('#' + sToggleName + 'Description .' + sToggleName + 'Text').height() < fHeight)
            {
                $('#' + sToggleName + 'Description .' + sToggleName + 'Text').height(fHeight - 10);
            }

            var fTextHeight = $('#' + sToggleName + 'Description').height() + 30;
            var fDownPercentage = fTextHeight / fHeight * 100;
            var fUpPercentage = fHeight / fTextHeight * 100;
            
            $('#' + sToggleName + 'DescriptionToggler').css({display: 'block'}).click(function ()
            {
                if(bDown == false)
                {
                    $('#' + sToggleName + 'Description').animate(
                        {height: fTextHeight}, 
                        400, '', 
                        function(){$('#' + sToggleName + 'Description').height(fTextHeight);}
                    );
                    $(this).text(sTextUp).removeClass(sClassNameDn).addClass(sClassNameUp);
                    bDown = true;
                }
                else
                {
                    $('#' + sToggleName + 'Description').animate(
                        {height: fHeight}, 
                        400, '', 
                        function(){$('#' + sToggleName + 'Description').height(fHeight);}
                    );
                    $(this).text(sTextDown).removeClass(sClassNameUp).addClass(sClassNameDn);
                    bDown = false;
                }
            });            
            $('#' + sToggleName + 'DescriptionToggler').text(sTextDown).removeClass(sClassNameUp).addClass(sClassNameDn);
        }
        $('#' + sToggleName + 'Description').height(fHeight);
    }
    
    // tabnavi product detail
    $("#detailNavi").glider({});

    // blogticker startseite
    $('#blogTicker').blogTicker();

    // blog team table
    $('.team table').prepend($('<tr></tr>').prepend($('<th></th>').attr({colSpan: 2}).text($('.team h1').text())));
    
    // gewinnspiel / umfrage
    $('input[id*=eigeneantwort]').focus(function()
    {
        $(this).parent().prev().find('input:radio:last, input:checkbox:last')[0].checked = true;
    });
    $('input:radio[name="aData[gewinnspiel]"], input:checkbox[name="aData[gewinnspiel]"], input:radio[name*="frage"], input:checkbox[name*="frage"]').change(function()
    {
        $sInputTextField = $(this).parent().parent().parent().next().find('input[id*=eigeneantwort]');
        $sInputTextField.data('sOldVal', $sInputTextField.data('sOldVal') || $sInputTextField.val());
        if($(this).parent().parent().find('input:radio:last, input:checkbox:last')[0].checked)
        {
            $sInputTextField.val($sInputTextField.data('sOldVal')).focus();
        }
        else
        {
            $sInputTextField.data('sOldVal', $sInputTextField.val() ? $sInputTextField.val() : $sInputTextField.data('sOldVal'));
            $sInputTextField.val('');
        }
    });
    
    // nice checkboxes / radios
    $('.inputcheckboxes label, .inputradios label').not('.inputcheckboxes.none label').each(function()
    {
        $(this).contents().filter(function(){ return this.nodeType != 1 || this.nodeName == 'A'; }).wrap("<span/>");
    });

    if(typeof $.fn.qtip != 'undefined')
    {
        $('.paymentradios label').qtip(oQTipOptions);
    }
    
    // order details
    $('.ordersDetail').hide().next().each(function()
    {
        $(this).bind('click', function()
        {
            $(this).prev().slideToggle(500, function()
            {
                $(this).next().attr('class', 'toggler ' + ($(this).is(':visible') ? 'blindUp' : 'blindDn'));
            });
        });
    });
    if(location.hash && $('body ' +  location.hash + ':has(.ordersDetail)').length == 1)
    {
        $(location.hash + '').find('.ordersDetail').next().trigger('click');
    }
    
    // mouseover payment/delivery
    $('.homeInfoBox .payment, .homeInfoBox .delivery, .navInfoBox .payment, .navInfoBox .delivery').hover(function()
    {
        $(this)/* .find('.payment, .delivery') */.each(function()
        {
            sPos = $(this).css('backgroundPosition');
            aPos = sPos.split(" ");
            $(this).css({'backgroundPosition': aPos[0] + ' ' + (parseInt(aPos[1].replace('px', '')) - 100) + 'px'}).data('origpos', sPos);
        });
    }, function()
    {
        $(this)/* .find('.payment, .delivery') */.each(function()
        {
            $(this).css({'backgroundPosition': $(this).data('origpos')});
        });
    });
    
    // produktdetail: back in stock notification
    $("#backInStockNotificationButton").backInStockNotification();
        
    // img load
    $('img.lazy').jail();
}

initVoucherForm = function()
{
    sVoucherFormTpl = sVoucherFormTpl || '';
    if(!sVoucherFormTpl)
    {
        return;
    }
    
    $('#size_andererbetrag').wrapInner('<a id="voucherCustomValue" href="#voucherCustomValueFormDiv"></a>');
    $('#voucherCustomValue').css({padding: 0}).fancybox(
    {
        content: sVoucherFormTpl,
        width: 600,
        height: 250,
        onClosed: function()
        {
            if(aVariants[82116]['fPrice'] == 0)
            {
                $('#size_andererbetrag').prev().trigger('click');
            }
        },
        onComplete: function()
        {
            $('#customValue').focus().bind('keyup', function(event)
            {
                sValue = this.value;
                if (!event) event = window.event
                var key = event.keyCode || event.which;

                if(key == 37 || key == 39)
                {
                    return;
                }
                else if(key == 13)
                {
                    $('#voucherCustomValueForm a.button').trigger('click');
                }
                else if(key == 190 && sValue.indexOf('.') == sValue.lastIndexOf('.'))
                {
                    return;
                }
                else if(key == 188 && sValue.indexOf(',') == sValue.lastIndexOf(','))
                {
                    return;
                }

                sValue = sValue.replace(',', '.');
                sValue = sValue.replace(/[^0-9.]/gi, '');
                sValue = parseFloat(sValue);
                if(isNaN(sValue)) sValue = 0;
                sValue = Math.min(sValue, 9999.99);
                sValue = sValue + '';
                sValue = sValue.replace('.', ',');
                this.value = sValue;
            }); 
            $('#voucherCustomValueForm a.button').click(function(event)
            {
                fValue = parseFloat($('#customValue').val().replace(',', '.'));
                if(fValue > 0 && !isNaN(fValue))
                {
                    aVariants[82116]['fPrice'] = fValue;
                    $('#basketForm input[name=customVoucherValue]').val(fValue);
                    parent.$.fancybox.close();
                    $('#size_andererbetrag').trigger('click');
                }
                
                event.preventDefault();
            });
        },
        overlayOpacity: 0.05, 
        opacity: true
    });
}

// img runde ecken
roundImgCorners = function ()
{
    $('.popupImg').addClass('roundCornersContainer').addClass('autoclear');
    $('.roundCornersContainer').wrap('<span class="roundCorners"><span class="leftTop"></span></span>');
    $('.roundCorners')
        .append('<span class="rightTop"></span><span class="leftBottom"></span>')
        .each(function()
        {
            sFloat = $(this).find('.roundCornersContainer').css('float');
            
            if(sFloat != 'none')
            {
                $(this).css('float', sFloat);
            }            
            
            $(this).addClass($(this).find('.roundCornersContainer').attr('class')).removeClass('popupImg');
            $(this).addClass($(this).find('.roundCornersContainer img').attr('class'));
            //$(this).attr('style', $(this).find('.roundCornersContainer').attr('style'));
        }
    );

    if($.browser.msie && $.browser.version < 7)
    {
        $('.roundCornersContainer img').each(function()
        {
            $(this).parent().width($(this).width())
        })
    }
    
    $('.roundCorners img').removeAttr('align').css({'float': 'none'});
}

// carousels
var carousel = null;
loadCarousels = function ()
{
    $("#carouselContainer1 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer1 .next_button",
        btnPrev: "#carouselContainer1 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4,
        afterEnd: function(){$(window).trigger('resize');}
    });

    $("#carouselContainer2 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer2 .next_button",
        btnPrev: "#carouselContainer2 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4,
        afterEnd: function(){$(window).trigger('resize');}
    });

    $("#carouselContainer3 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer3 .next_button",
        btnPrev: "#carouselContainer3 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4,
        afterEnd: function(){$(window).trigger('resize');}
    });
    
    $("#carouselContainer4 .container").jCarouselLite(
    {
        btnNext: "#carouselContainer4 .next_button",
        btnPrev: "#carouselContainer4 .previous_button",
        easing: "easeInOutQuint",
        speed: 800,
        circular: false,
        visible: 4,
        scroll: 4,
        afterEnd: function(){$(window).trigger('resize');}
    });
}

var oQTipOptions = {
	overwrite: false,
	position: {
		my: "left center",
		at: "right center",
		effect: false,
		adjust: {
			resize: true,
			method: "flip flip"
		},
		viewport: $(window)
	},
	style: {
		tip: true,
		classes: "ui-tooltip-jtools"
	}
};

var oFancyBoxOptions = {
    transitionIn: 'elastic', transitionOut: 'elastic', hideOnContentClick: true, speedIn: 400, speedOut: 400, 
    overlayShow: true, overlayOpacity: 0.2, opacity: true, titlePosition: 'inside', overlayColor: '#000',
    'easingIn': 'easeOutQuad', 'easingOut': 'easeOutQuad',
    onStart: function()
    {
        if($.support.cssProperty('borderRadius') && $.support.cssProperty('boxShadow'))
        {
            $('.fancybox-bg').remove();
        }
    }
};

initFancyBox = function ()
{
    // images
    $(".popupImg").fancybox(oFancyBoxOptions); 
    
    // orderform sparkasse
    $("#orderForm button").fancybox($.extend(true, {}, oFancyBoxOptions, {
        overlayOpacity: 0.9, 
        width: 600, 
        height: 420,
        href: $('#orderForm').serialize(),
        onStart: function()
        {
            if($.support.cssProperty('borderRadius') && $.support.cssProperty('boxShadow'))
            {
                $('.fancybox-bg').remove();
            }
              
            ret = {};
            if(!$('input:checkbox[name=agb]').attr('checked'))
            {
                ret.content = $('#frameErrorMsg').html();
            }
            else
            {
                ret.href = $('#orderForm').attr('action') + '?' +  $('#orderForm').serialize();
                ret.type = 'iframe';
            }
                   
            return ret;
        }
    }));
    
    // popups
    $('.popupLink').each(function()
    {
        if(!document.all && this.href.indexOf(sBaseUrl) != 0 && this.href.indexOf(sSslBaseUrl) != 0)
        {
            $(this).removeClass('popupLink').click(function()
            {
                window.open(this.href);
                return false;
            });
            return;
        }
    
        if(this.href.indexOf('media=popup') == -1)
        {
            if (this.href.indexOf('?') != -1)
            {
                this.href += '&media=popup';
            }
            else
            {
                this.href += '?media=popup';
            }
        }

        this.href = this.href.replace(sBaseUrl, sPathHttp);
        this.href = this.href.replace(sSslBaseUrl, sPathHttp);
    });
    $('.popupLink:not(.popup .popupLink)').addClass('iframe').fancybox($.extend(true, {}, oFancyBoxOptions, {width: 900, height: 540}));
}

function htmlEntityDecode(str)
{
    var ta = document.createElement("textarea");
    ta.innerHTML = str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
    toReturn = ta.value;
    ta = null;
    return toReturn;
}
// alert(htmlEntityDecode("&auml;"));

if (top != self && window.location.search.indexOf('popup') == -1)
{
    top.location = self.location;
}

$(document).ready(function()
{
    loadCarousels();
    roundImgCorners();
    initFancyBox();
    startApp();
    updateCheckoutPrice();
    if (bIsIe6 && $.fn.pngFix) $('.teaserRotator').pngFix({blankgif: ("https:" == document.location.protocol ? sSslBaseUrl : sBaseUrl) + 'images/blank.gif'});
    $('html').addClass('js');
});
