/**
 *
 * translator
 * todo!!
 */
var fp = fp || {};

if( !fp.translation ){
    fp.translation = {
        data : [],
        init: function(){},
        set : function(key,value){
            if(this.data[key]){
                return false;
            }
            this.data[key] = value;
            return true;
        },
        get : function(key){
            if(this.data[key]){
                return this.data[key]
            }
            return '['+key+']';
        }
    }

    fp.translation.constructor = fp.translation.init();
}

//load by ready
fp.event = fp.event || {};
fp.event.loaded = {
    list : [],
    init : function(){
        var _this = this;
        document.observe("dom:loaded", function(){  _this.loaded(); });
    },
    loaded : function() {
        for(var i = 0; i < this.list.length; i++){
            this.list[i]();
        }
    },
    regist : function(func){
        if(typeof func == 'function'){
            this.list.push(func);
        }else{
            console.log(func);
        }
    }
};
fp.event.loaded.constructor = fp.event.loaded.init();

fp.utils = fp.utils || {};

fp.utils.Times =  {
    convertSecToMSec : function(value) {
        return parseNumber(value) * 1000;
    }
};

fp.utils.redirect = {
    url : '',
    handler : null,
    init : function() {

    },
    gotoUrl : function(url) {
        window.location.href = url;
    },
    gotoUrlByTime : function(seconds, url) {
        window.setTimeout("fp.utils.redirect.gotoUrl('"+url+"')", fp.utils.Times.convertSecToMSec(seconds));
    }
};
fp.utils.redirect.constructor = fp.utils.redirect.init();



/* content of footer.phtml */

/*
 old position on footer
 */

//function subscribeFooterNewsletter(formname) {
//
//    $('newsletter-validate-detail-footer').setStyle({
//        display:'none'
//    });
//    
//    $('footerMPNewslettersubscriptionWelcomeText').innerHTML = '<ul class="messages"><li class="notice-msg" style="display:block;"><ul><li style="display:block;">'+fp.translation.get("Your request will be sent...") +'<br/>'+fp.translation.get("Please wait a moment.") + '</li></ul></li></ul>';
//    
//    new Ajax.Request(baseURL+"newsletter/subscriber/new/", {
//        method:'post',
//        parameters: $(formname).serialize(true),
//        onSuccess: function(transport) {
//            if(transport.status == 200) {
//                var newsletterFormReply = eval('(' + transport.responseText + ')');
//                $('footerMPNewslettersubscriptionWelcomeText').innerHTML = newsletterFormReply.antwort;
//            }
//        }
//    });
//}
//
//document.observe("dom:loaded", function() {
//    var totalPageHeight;
//    $$('body').each(function(e) {
//        $(e).getDimensions();
//        totalPageHeight = Element.getHeight(e);
//    });
//    if($('footerNLsubscribeButton')) {
//        $('footerNLsubscribeButton').observe('click', function(){
//            subscribeFooterNewsletter('newsletter-validate-detail-footer');
//        });
//    }
//
//    if ($('catLeftNavigation')) {
//        var dimensions = $('catLeftNavigation').getDimensions();
//        var browser_size = getSize();
//        var fullPageHeight = "fullpageheight";
//        totalPageHeight = totalPageHeight - 1400;
//        Event.observe(window,'scroll', function(){
//            var arr1 = getScrollXY();
//
//            if(arr1[1] > dimensions.height && arr1[1] < totalPageHeight){
//                $('toTopButton').setStyle({
//                    display: 'block'
//                });
//            }else if(arr1[1] < dimensions.height || arr1[1] > totalPageHeight){
//                $('toTopButton').setStyle({
//                    display: 'none'
//                });
//            }
//        })
//    }
//});

/*
 * function returns absolute postitions of the current browser view
 */
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;

    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}

/*
 * function returns current browser dimensions
 */
function getSize() {
    var myWidth = 0, myHeight = 0;

    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [ myWidth, myHeight ];
}

document.observe("dom:loaded", function() {

    if($('NewsletterSubscriptionFooter_email')) {
        var  $newsletter_mail = $('NewsletterSubscriptionFooter_email'),
            NewsletterSubscriptionFooter_email_value = fp.translation.get('Ihre E-Mail Adresse'),
            newsletterSubscriberFormDetail = new VarienForm('newsletter-validate-detail-footer');


        $newsletter_mail.setValue(NewsletterSubscriptionFooter_email_value);

        $newsletter_mail.observe('focus', function(){

            if(this.value==NewsletterSubscriptionFooter_email_value){
                this.value='';
            }
        });

        $newsletter_mail.observe('blur', function(){
            if(this.value==''){
                this.value=NewsletterSubscriptionFooter_email_value;
            }
        });
    }
});

/* pop up */
function openFaqPopup(){
    var popW = 990, popH = 500;
    var leftPos = 600, topPos = 300;
    var popunder = window.open(baseURL+'faq_popup','FAQ','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
}

function open_glossar(arg){
    var popW = 585, popH = 640;
    var leftPos = 600, topPos = 300;
    var popup = window.open(baseURL+'glossar/index/show/id/' + arg,'FAQ','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
    popup.focus();
}

function openNLPopup(){
    var popW = 600, popH = 530;
    var leftPos = 600, topPos = 300;
    var popunder = window.open(baseURL+'mynewsletter/popunder','Newsletter','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=no,resizeable=no');
    if(popunder){
        popunder.focus();
    }
    setCookie('popunder', true, 3600 * 24 * 30, '/', serverName);
}


/*
 * function returns absolute postitions of the current browser view
 */
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;

    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [ scrOfX, scrOfY ];
}

/*
 * function returns current browser dimensions
 */
function getSize() {
    var myWidth = 0, myHeight = 0;

    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [ myWidth, myHeight ];
}

/*
 * function positions the notice div centered in the browser
 */
function positionNoticeDiv() {
    var arr1 = getScrollXY();
    var arr2 = getSize();

    var elt = $('addToWatchlistOverlay');

    // retrieve required dimensions
    var eltDims = elt.getDimensions();

    // calculate the center of the page using the browser and element dimensions
    var x = ((arr2[0] - eltDims.width) / 2) / 2;
    var y  = arr1[1] + ((arr2[1] - eltDims.height) / 2) / 2;

    // set the style of the element so it is centered
    var styles = {
        position : 'absolute',
        top      : y + 'px',
        left     : x + 'px'
    };

    elt.setStyle(styles);

    return false;
}

/*
 * main function that triggers the notice div, eff
 */
function addToWatchList(productID) {

    //$('watchlist-addTo-' + productID).update('Bitte warten...');

    // Overlay configuration
    var overlayCss = "-webkit-border-radius: 100px; -moz-border-radius: 100px; opacity:0; position:absolute; background:#FFFFFF; border:1px solid #000; padding:15px;"; // exclude to CSS
    var overlayContent = "<center>"+fp.translation.get('Please wait.. Product added to your reminder list.')+"</center>";

    // Insert stylish notice div
    $('watchlist-addTo-' + productID + '_2').insert('<div style="' + overlayCss + '" id="addToWatchlistOverlay">' + overlayContent +'</div>');

    // position watchlistoverlay
    positionNoticeDiv();
    // make notice div visible to the user
    addWatchlistOverlay(productID);
}

function ajaxWatchlistAdd(productID) {
    new Ajax.Request("/watchlist/index/add/product/" + productID, {

        onSuccess: function(transport) {
            if(transport.status == 200) {
                // Success
                //$('watchlist-addTo-' + productID).update('Produkt vorgemerkt');
                removeWatchlistOverlay('watchlist-addTo-' + productID, '');
                $('watchlist-addTo-' + productID).addClassName('addToWishlist_gemerkt');
            }
        },
        onFailure: function(transport) {
            if(transport.status == 302) {
                // Already on list
                // $('watchlist-addTo-' + productID).update('Produkt bereits vorgemerkt');
                removeWatchlistOverlay('watchlist-addTo-' + productID, '');
            }
            else {
                // Failure
                //alert('Beim Verarbeiten Ihrer Anfrage trat leider ein Fehler auf. Kontaktieren Sie uns doch bitte, falls das Problem weiterhin auftritt.');
                //removeWatchlistOverlay('watchlist-addTo-' + productID, 'Fehler ... nochmal <a onclick="addToWatchList('+ productID +'); openWatchlistPopUnder(); return false;" href="#">Merken</a>?');
            }
        }
    });
    openWatchlistPopUnder();
}

function addWatchlistOverlay(productID){
    new Effect.Opacity('addToWatchlistOverlay', {
        from: 0.0,
        to: 1.0,
        duration: 0.5,
        afterFinish: function(){
            ajaxWatchlistAdd(productID);
        }
    } );
}

function removeWatchlistOverlay(el, content){
    new Effect.Opacity('addToWatchlistOverlay', {
        from: 1.0,
        to: 0.0,
        duration: 0.5,
        afterFinish: function(){
            setTimeout( function(){
                $(el).update(content);
            }, 1000);
        }
    });
}

function openWatchlistPopUnder() {
    window.name = 'mainWindow';
    var popW = 475, popH = 600;
    var leftPos = 600, topPos = 300;
    var popunder = window.open(baseURL + 'watchlist/reminder','Merkliste','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
    if(popunder){
        popunder.blur();
    }
    window.focus();
}

/* footer */
function sendRequest() {
    
    var email       = document.getElementById('email').value,
        firstname   = document.getElementById('firstname').value,
        lastname    = document.getElementById('lastname').value;

    //alert('email='+ email+'&name=' +firstname+' ' +lastname);
    if(email !== ""){

        new Ajax.Request(baseURL+"newsletter/subscriber/new",
        {
            method: 'post',
            parameters: $('newsletterSignup').serialize(true),
            onComplete: closeAndGotoThankyou,
            asynchronous: false
        });
    }else {
        document.getElementById('email').focus();
    }
}
         
function sendRequestNlShort() {
    var email       = document.getElementById('NewsletterSubscriptionFooter_email').value;

    //alert('email='+ email+'&name=' +firstname+' ' +lastname);
    if(email !== "" && email !== fp.translation.get('Ihre E-Mail Adresse')){
        new Ajax.Request(baseURL+"newsletter/subscriber/new",
        {
            method: 'post',
            parameters: $('newsletter-validate-detail-footer').serialize(true),
            onComplete: closeAndGotoThankyouNLShort,
            asynchronous: false
        });
    }else {
        //document.getElementById('NewsletterSubscriptionFooter_email').focus();
        $("NewsletterErrMsgInline").addClassName('err');
        document.getElementById('NewsletterErrMsgInline').innerHTML = "<span style=\"margin-left:10px;\">"+fp.translation.get('E-mail field cannot be empty.')+"</span>";
    }
}


function closeAndGotoThankyou(data) {
    if(data.status == 200) {
        document.getElementById('newsletterSignup').innerHTML = data.responseText;
        //close by time
        fp.ui.newsletter.hideByTime(3000);
    }
    
    window.location.href = baseURL+"newsletter-anmeldung";
}

function closeAndGotoThankyouNLShort(data) {
    if(data.responseText == fp.translation.get('Confirmation request has been sent')) {
        $("NewsletterErrMsgInline").removeClassName('err');
        $("NewsletterErrMsgInline").addClassName('success');        
        document.getElementById('NewsletterErrMsgInline').innerHTML = "<span style=\"margin-left:10px;\">"+data.responseText+"</span>";
        //close by time
        fp.ui.newsletter.hideByTime(1000);
        window.location.href = baseURL+"newsletter-anmeldung";
    } else {
        $("NewsletterErrMsgInline").removeClassName('success');
        $("NewsletterErrMsgInline").addClassName('err');
        document.getElementById('NewsletterErrMsgInline').innerHTML = "<span style=\"margin-left:10px;\">"+data.responseText+"</span>";
    }
    
}


/* content of footer.phtml */
function openFaqPopup(){
    var popW = 990, popH = 500;
    var leftPos = 600, topPos = 300;
    var popunder = window.open(baseURL + 'faq_popup','FAQ','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
}

function open_glossar(arg){
    var popW = 585, popH = 640;
    var leftPos = 600, topPos = 300;
    var popup = window.open(baseURL + 'glossar/index/show/id/' + arg,'FAQ','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
    popup.focus();
}


/* content of catalog product detail.phtml */

// @todo: use hasClass/addClass/... here
function tab_over(t){
    return function() {
        var cl = t.className || "";
        if(~cl.indexOf('inactive')) {
            cl = cl.replace(/inactive/, 'active');
        }
        t.className = cl;
    }
}
function tab_out(t){
    return function() {
        var cl = t.className;
        if(~cl.indexOf('clicked')){
            return;
        }
        if(~cl.indexOf('active') && !~cl.indexOf('inactive')) {
            cl = cl.replace(/active/, 'inactive');
        }
        t.className = cl;
    }
}
fp.event.loaded.regist(function(){

    $$('.product_details_tab').each(function(tab){
        Event.observe(tab, 'mouseover', tab_over(tab));
        Event.observe(tab, 'mouseout', tab_out(tab));
    });
    $$('.product_details_tab.active').each(function(tab){
        tab.className += ' clicked';
    });

});


/* content of catalog product view.pthml */

if(!fp.product){
    fp.product = {
        productId : 0,
        isBundle : false,
        init : function(){
            fp.event.loaded.regist( this.initDomReady );
        },
        initDomReady : function()
        {
            if(!fp.product.isProduct()) return;

            // Apply toggleCount function to onchange event for bundle select(s)
            $$('.bundle-option-select').each(function(element) {
                element.observe('change', toggleCountHandler);
            });


            var productAddToCartForm = new VarienForm('product_addtocart_form');
            productAddToCartForm.submit = function(){
                if (this.validator.validate()) {
                    this.form.submit();
                }
            }.bind(productAddToCartForm);

            fp.product.initDetailTabs();
        },

        setProductId : function(id)
        {
            this.productId = parseInt(id);
        },

        isProduct : function(){
            return this.productId > 0;
        },
        initDetailTabs : function() {
            $$('div.product-details_tab').each(function(s){
                s.observe('click', function() {

                    $$('div.product-details_tab').each(function(e){
                        $(e).removeClassName('product-details_tab_active');
                        $(e).addClassName('product-details_tab_inactive')
                    });

                    $(s).addClassName('product-details_tab_active');
                    $$('div.product_details_contents').each(function(k){
                        $(k).setStyle({display: 'none'});
                    });
                    $(s.identify() + "_content").setStyle({display: 'block'});
                });
            });
            $$('div.product_details_tab').each(function(s){
                s.observe('click', function() {
                    if(!s) return;
                    $$('div.product_details_tab').each(function(e){
                        $(e).removeClassName('active');
                        $(e).addClassName('inactive');
                        $(e).removeClassName('clicked');
                    });
                    $(s).removeClassName('inactive');
                    $(s).addClassName('active');
                    $(s).addClassName('clicked');
                    $$('div.product_details_contents').each(function(k){
                        $(k).setStyle({display: 'none'});
                    });
                    if($(s.identify() + "_content")){
                        $(s.identify() + "_content").setStyle({display: 'block'});
                    }
                });
            });
        }
    }
    fp.product.constructor = fp.product.init();
}


function getSelectedOption(select)
{
    var selectedOptions = $(select).getElementsBySelector('option');
    var selection  = null;

    for (var i = 0; i < selectedOptions.length; i++)
    {
        if (selectedOptions[i].selected)
        {
            selection = selectedOptions[i];
            break;
        }
    }
    return selection;
}

function toggleCountHandler(event) {
    toggleCount($('product-qty-select'));
}

// Actions on item count changings
function toggleCount(select) {

    var active = getSelectedOption(select);

    if(active.value == "11") {
        // Move to the active select input
        $('qtyInfo').style.left = select.positionedOffset()[0] + 'px';
        $('qtyInfo').style.top = select.positionedOffset()[1] + 25 + 'px';
        $('qtyInfo').show();
    } else {
        $('qtyInfo').hide();
    }

    // Reload stock status with service module
    // 1) Product ID
    productId = fp.product.productId;

    // 2) Check for bundle option
    bundleSelect = $$('.bundle-option-select');
    if(bundleSelect && bundleSelect.length > 0) {
        bundleSelect = bundleSelect[0];
        option = getSelectedOption(bundleSelect);
        optionId = option.value;
    } else {
        bundleInput = $$('.bundle-option-hidden-input');
        if(bundleInput && bundleInput.length > 0)
            optionId = bundleInput[0].value;
        else
            optionId = 0;
    }

    Service.add('stockInfo', 'customer', 'stockInfo', [productId, active.value, optionId]);
}

function showDomObject(caller, id, hideCaller) {
    var obj = $(id);
    if(!obj) return;

    if(obj.hasClassName('hidden')) {
        obj.removeClassName('hidden');
    }

    if(caller && hideCaller){
        $(caller).hide();
    }
}



/* WATCHLIST */

/*
 * main function that triggers the notice div, eff
 */
function addToWatchList(productID) {

    //$('watchlist-addTo-' + productID).update('Bitte warten...');

    // Overlay configuration
    var overlayCss = "-webkit-border-radius: 100px; -moz-border-radius: 100px; opacity:0; position:absolute; background:#FFFFFF; border:1px solid #000; padding:15px;"; // exclude to CSS
    var overlayContent = "<center>Bitte warten... Produkt wird der Merkliste hinzugef&uuml;gt.</center>";

    // Insert stylish notice div
    $('watchlist-addTo-' + productID + '_2').insert('<div style="' + overlayCss + '" id="addToWatchlistOverlay">' + overlayContent +'</div>');

    // position watchlistoverlay
    positionNoticeDiv();
    // make notice div visible to the user
    addWatchlistOverlay(productID);
}

function ajaxWatchlistAdd(productID) {
    new Ajax.Request("/watchlist/index/add/product/" + productID, {

        onSuccess: function(transport) {
            if(transport.status == 200) {
                // Success
                //$('watchlist-addTo-' + productID).update('Produkt vorgemerkt');
                removeWatchlistOverlay('watchlist-addTo-' + productID, '');
                $('watchlist-addTo-' + productID).addClassName('addToWishlist_gemerkt');
            }
        },
        onFailure: function(transport) {
            if(transport.status == 302) {
                // Already on list
                // $('watchlist-addTo-' + productID).update('Produkt bereits vorgemerkt');
                removeWatchlistOverlay('watchlist-addTo-' + productID, '');
            }
            else {
                // Failure
                //alert('Beim Verarbeiten Ihrer Anfrage trat leider ein Fehler auf. Kontaktieren Sie uns doch bitte, falls das Problem weiterhin auftritt.');
                //removeWatchlistOverlay('watchlist-addTo-' + productID, 'Fehler ... nochmal <a onclick="addToWatchList('+ productID +'); openWatchlistPopUnder(); return false;" href="#">Merken</a>?');
            }
        }
    });
    openWatchlistPopUnder();
}

function addWatchlistOverlay(productID){
    new Effect.Opacity('addToWatchlistOverlay', {
        from: 0.0,
        to: 1.0,
        duration: 0.5,
        afterFinish: function(){
            ajaxWatchlistAdd(productID);
        }
    } );
}

function removeWatchlistOverlay(el, content){
    new Effect.Opacity('addToWatchlistOverlay', {
        from: 1.0,
        to: 0.0,
        duration: 0.5,
        afterFinish: function(){
            setTimeout( function(){$(el).update(content);}, 1000);
        }
    });
}

function openWatchlistPopUnder() {
    window.name = 'mainWindow';
    var popW = 475, popH = 600;
    var leftPos = 600, topPos = 300;
    var popunder = window.open('<?php echo $this->getBaseUrl(); ?>watchlist/reminder','Merkliste','width=' + popW +  ',height=' + popH + ',left=' + leftPos + ',top=' + topPos + ',dependent=no,menubar=no,scrollbars=yes,resizeable=no');
    if(popunder){popunder.blur();}
    window.focus();
}

function showMiniInfo(id){
    $('produktinformationen_content').hide();
    $('miniinfo_price-info').hide();
    $('miniinfo_add-to-cart').innerHTML = '<a id="addRelatedToCart" href="javascript:void(0);" class="button-gradient righter" style="display:inline-block; float:right; "><div class="button-blue-left button-left">&nbsp;</div><div class="button-blue-middle button-middle">In den Warenkorb</div><div class="button-blue-right button-right">&nbsp;</div></a>';
    $('article_miniinfo_loader').show();
    Effect.Appear('ajaxAddToCartOverlay', {duration: 0.4,  to: 0.4});
    elmIdentifier = 'article_miniinfo';
    var elm = $(elmIdentifier);

    $('ajaxAddToCartOverlay').observe('click', function(event) {
        hidepop(elmIdentifier);
    });
    $('article_miniinfo_close').observe('click', function(event) {
        hidepop(elmIdentifier);
    });

    var s = elm.style, sc;
    if(window.innerWidth) {
        sc = window.innerWidth;
    } else {
        sc = document.body.clientWidth;
    }
    sc = sc-848;
    elm.left = (sc < 0 ? 0 : sc)/ 2 + "px";
    $("article_miniinfo").setStyle({'left':elm.left});

    Effect.Appear("article_miniinfo", {duration: 0.4,  to: 1});

    new Ajax.Request('<?php echo $this->getBaseUrl() ?>catalog/ajax/sliderpopup/id/' + id + '/isAjax/1/', {
        method: 'get',
        onFailure: function() {
            $('miniinfo_add-to-cart').innerHTML = 'Ein Fehler ist aufgetreten ...';
        },
        onSuccess: function(response) {
            var miniinfo = eval('(' + response.responseText + ')');
            $('miniinfo_options').innerHTML = '';
            $('article_miniinfo_loader').hide();
            $('produktinformationen_content').show();
            $('miniinfo_price-info').show();
            $('miniinfo_productName').innerHTML = miniinfo.name;
            $('miniinfo_mediaGalleryImages').innerHTML = miniinfo.mediagallery;
            $('miniinfo_brandtext').innerHTML = miniinfo.brand_text;
            $('miniinfo_description').innerHTML = miniinfo.description;
            $('miniinfo_bulletpoints').innerHTML = miniinfo.bulletpoints;
            $('miniinfo_attributes').innerHTML = miniinfo.attributes;
            $('miniinfo_toProductLink').href = miniinfo.url_path;
            $('miniinfo-discount-price').innerHTML = miniinfo.discountprice;
            $('miniinfo-price').innerHTML = miniinfo.price;
            $('miniinfo_brandlogo').innerHTML = miniinfo.brandlogo;
            $('addRelatedToCart').observe('click', function(event) {
                var options = '';
                $$('#article_miniinfo .miniinfo_select_options').each(function(option){
                    id = option.id;
                    id = id.replace(/miniinfo-/, '');
                    options = options + '&bundle_option[' + id + ']=' + option.value + '';
                });
                addRelatedToCart(miniinfo.entity_id, 1, options);
            });
            if (miniinfo.productType == 'bundle') {
                var arrValues = miniinfo.optionGroupNames;
                var bundleSkonto;
                $H(miniinfo.optionGroupNames).each(function(pair){
                    var miniinfoSelectElement = new Element('select', {'id': 'miniinfo-' + pair.key, 'class': 'miniinfo_select_options'});
                    $("miniinfo_options").insert('<span style="font-weight:bold;">' + pair.value + '</span><br/>');
                    $("miniinfo_options").insert(miniinfoSelectElement);
                    $("miniinfo_options").insert('<br/>');
                    $H(miniinfo.optionGroup[pair.key]).each(function(valuepair){
                        var opt = document.createElement('option');
                        opt.text = valuepair.value;
                        opt.value = valuepair.key;
                        $('miniinfo-' + pair.key).options.add(opt);
                    });

                    gesamtpreis = 0;
                    $$('#article_miniinfo .miniinfo_select_options').each(function(narf){
                        gesamtpreis = gesamtpreis + miniinfo.selectionPureCosts[narf.value];
                    });
                    bundleSkonto = renderPrice(Math.round((gesamtpreis - ((gesamtpreis / 100) * miniinfo.storeSkonto))*100)/100);
                    gesamtpreis = renderPrice(gesamtpreis);
                    $('miniinfo-discount-price').innerHTML = bundleSkonto;
                    $('miniinfo-price').innerHTML = gesamtpreis;

                    $('miniinfo-' + pair.key).observe('change', function(event) {
                        gesamtpreis = 0;
                        $$('#article_miniinfo .miniinfo_select_options').each(function(narf){
                            gesamtpreis = gesamtpreis + miniinfo.selectionPureCosts[narf.value];
                        });
                        bundleSkonto = renderPrice(Math.round((gesamtpreis - ((gesamtpreis / 100) * miniinfo.storeSkonto))*100)/100);
                        gesamtpreis = renderPrice(gesamtpreis);
                        $('miniinfo-discount-price').innerHTML = bundleSkonto;
                        $('miniinfo-price').innerHTML = gesamtpreis;
                    });
                });


                //$('miniinfo_add-to-cart').innerHTML = '<button onclick="document.location.href=\'' + miniinfo.url_path + '\'; return false;" style="width: 385px; float: left;" class="button-gradient righter"><div class="button-yellow-left button-arrow-left" style="width: 5px;">&nbsp;</div><div class="button-yellow-middle button-middle">Bitte klicken Sie hier um zum Produkt zu gelangen</div><div class="button-yellow-right button-right">&nbsp;</div></button>';
            }
        }
    });
}

function renderPrice(preis){
    preis = "" + preis;
    if (preis.indexOf('.') == -1) {
        preis = preis + ',00 â‚¬';
    }else{
        preis = preis.replace( /\./ , "," ) + ' â‚¬';
    }
    return preis;
}

function format( number )
{
    var n = ""+number;
    var s;
    if( n.indexOf("-") > -1 ) s=1;
    else
        s=0;
    for( i = n.length-3; i > s; i-=3 ){n = n.substring( 0, i ) + "." + n.substring( i );}
    return n;
}

function addRelatedToCart(relatedId, quantity, options){
    $('miniinfo_add-to-cart').innerHTML = '<img src="'+baseURL+'/skin/frontend/fpc/default/images/ajax-loader2.gif" alt="loader"/>';
    new Ajax.Request(baseURL+'checkout/cart/add?product='+ relatedId + '&qty=' + quantity + '&isAjax=1' + options, {
        onSuccess: function(response) {
            $('miniinfo_add-to-cart').innerHTML = 'Produkt wurde in den Warenkorb gelegt. <a href="javascript:void(0);" onclick="hidepop(\'article_miniinfo\');" style="text-decoration:underline;">Popup schlie&szlig;en</a>';
        }
    });
}

function changePopupImage(productId, imageId)
{
    $$('#additional_product_images_' + productId + ' img.prodImg').each(function(e){
        $(e).removeClassName('inactiveBigPopupImage').setStyle({display: 'none'});;
    });

    $('image_big_' + imageId).addClassName('activeBigPopupImage').setStyle({display: 'block'});

}


function hidepop(hideId){
    if (document.getElementById(hideId)) {$(hideId).hide()};
    $('ajaxAddToCartOverlay').hide();
    $('article_miniinfo').hide();
}

/*
 * function positions the AGB div centered in the browser
 */
function positionAgbDiv() {
    var arr1 = getScrollXY();
    var arr2 = getSize();

    var elt = $('MP2_AGBWDR_holder');
    // retrieve required dimensions
    var eltDims = elt.getDimensions();

    // calculate the center of the page using the browser and element dimensions
    var x = ((arr2[0] - eltDims.width) / 2) / 2;
    var y  = arr1[1] + ((arr2[1] - eltDims.height) / 2) / 2;

    // set the style of the element so it is centered
    var styles = {position : 'absolute',
        top      : y + 'px',
        left     : x + 'px'};

    //elt.setStyle(styles);

    return false;
}

function showReviewForm(openOnly) {
    if(openOnly) {
        if($('review-form').getStyle('display') == 'none') {
            Effect.toggle('review-form', 'slide');
        }
    }
    else {
        Effect.toggle('review-form', 'slide');
        Effect.toggle('writeFirstReview', 'slide');
    }
}

/* content from review/form.phtml */

function submitReviewForm(caller, hideCaller) {
    var $form = $('review-form');
    var $status = $('reviewSubmitStatus');

    if(caller && hideCaller){
        $(caller).addClassName('hidden');
    }

    var _caller = caller;

    $status.innerHTML = fp.translation.get('Your request will be sent...')+'<br/>'+fp.translation.get('Please wait a moment.');
    //$('form_key_review').value = $('reviewFormKey').innerHTML;

    new Ajax.Request($form.readAttribute('action'), {
        method:'post',
        parameters: $form.serialize(true),
        onSuccess: function(transport) {
            if(transport.status == 200) {

                var reviewSubmitStatus = eval('(' + transport.responseText + ')');

                $form.addClassName(reviewSubmitStatus.state);

                if (reviewSubmitStatus.state == 'ok') {
                    $form.innerHTML = reviewSubmitStatus.antwort;
                }else{
                    $status.innerHTML = reviewSubmitStatus.antwort;
                    if(_caller){
                        $(_caller).removeClassName('hidden');
                    }
                };
            }
        }
    });
}

/* content from checkout billing.phtml */
//alert('debug');

Event.observe(document, 'dom:loaded', function() {
    $$(".create_account").each( function(el) {
        Event.observe(el, "click", function(evt) {
            toggleCreateAccount(this);
        });
    });
});

fp.checkout = {
    init : function() {},
    getPrefixValue : function() {
        var value = 'Herr';
        var childs = document.getElementsByName('billing[prefix]');
        var i = childs.length;
        while(i--) {
            var child = childs[i];
            if(child.checked) {
                value = child.value;
            }
        }
        return value;
    },
    setBillpayCompanySalutation : function(value){
        value = value == 'Frau' ? 'Frau' : 'Herr';
        document.getElementById('billpay_rec_salutation').value = value;
        return document.getElementById('billpay_rec_salutation').value;
    },
    nextStep : function(caller, stepid) {
        useThisAddressBilling('new');
        billing.newAddress(!caller.value);
        if(checkout.setMethod() === false) {
            return false;
        }
        billing.save();
        emptyFields('shipping', false);
    }
}
fp.checkout.constructor = fp.checkout.init();

function openPopUp(url) {
    var myleft=20;
    var mytop=20;
    var settings="width=1000,height=600,top=" + mytop + ",left=" + myleft + ",scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=no,dependent=no";
    var win=window.open(url,"mypopup",settings);
    win.focus();
    return false;
}

function toggleCreateAccount(radio_button) {
    var value = $(radio_button).getValue();
    if (value == 'register') {
        $('register-customer-password').show();
        $('confirm-customer-password').show();
        $('secure-customer-password').show();
    } else {
        $('register-customer-password').hide();
        $('confirm-customer-password').hide();
        $('secure-customer-password').hide();
    }
}



function useThisAddressBilling(AddrId){

    var options = $$('select#billing-address-select option');
    var len = options.length;
    if (len >= 1) {
        for (var i = 0; i < len; i++) {
            if(options[i].value == AddrId){
                options[i].selected = true;
                $('billing:save_in_address_book').checked = false;
                removeAdressHighlights('use_billing_address');
                $('use_billing_address_' + AddrId).addClassName('active');
                $$('#billing-new-address-form .required-entry').each(function(s, index) {
                    s.addClassName('skip-input');
                    s.removeClassName('validation-failed');
                });
            }else if(AddrId == 'new'){
                if(options[i].value == ''){
                    options[i].selected = true;
                    $('billing:save_in_address_book').checked = true;
                    removeAdressHighlights('use_billing_address');
                    $('use_billing_address_' + AddrId).addClassName('active');
                    $$('#billing-new-address-form .required-entry').each(function(s, index) {
                        s.removeClassName('skip-input');
                    });
                }
            }
        }
    }else if(AddrId == 'new' && $('use_billing_address_new')){
        $('use_billing_address_' + AddrId).addClassName('active');
    }
}

function useThisAddressShipping(AddrId){
    var options = $$('select#shipping-address-select option');
    var len = options.length;
    if(len == 0) { $('shipping-new-address-form').addClassName('active');}
    if (len >= 1) {
        $('shipping:same_as_billing').checked = false;
        $('billing:use_for_shipping_yes').checked = false;
        $('shipping:save_in_address_book').checked = true;
        for (var i = 0; i < len; i++) {
            if(options[i].value == AddrId){
                options[i].selected = true;
                $('shipping:save_in_address_book').checked = false;
                removeAdressHighlights('use_shipping_address');
                $('use_shipping_address_' + AddrId).addClassName('active');
                $$('#shipping-new-address-form .required-entry').each(function(s, index) {
                    s.addClassName('skip-input');
                    s.removeClassName('validation-failed');
                });
            }else if(AddrId == 'new'){
                if(options[i].value == ''){
                    options[i].selected = true;
                    $('shipping:save_in_address_book').checked = true;
                    removeAdressHighlights('use_shipping_address');
                    $('shipping-new-address-form').addClassName('active');
                    $$('#shipping-new-address-form .required-entry').each(function(s, index) {
                        s.removeClassName('skip-input');
                    });
                }
            }
        }
    } else if(AddrId == 'unregisteredBillingAdress'){
        removeAdressHighlights('use_shipping_address');
        $('unregisteredBillingAdress_holder').addClassName('active');
        $('shipping-new-address-form').removeClassName('active');
    }
}


function removeAdressHighlights(ele){
    $$('.' + ele).each( function (s) { s.removeClassName('active'); });
    if (ele == 'use_shipping_address') {
        $('shipping-new-address-form').removeClassName('active');
    } else if (ele == 'use_billing_address') {
        $('use_billing_address_new').removeClassName('active');
    }
}


fp.utils.abCheck = {
    isAbActive : false,
    check: function(){        
        var x = document.getElementById('ad1');

        if (x == null) {return true}

        var xstyle = false;
        var attrToCheck = new Array('MozBinding','display','position','top','left');
        var attrCond = new Array('none','inline','static','auto','auto');
        var _aba = false;

        if (x.currentStyle) //IE
            xstyle = x.currentStyle
        else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox & Crome
            xstyle = document.defaultView.getComputedStyle(x, "")

        var i=0;
        while (i<attrToCheck.length) {                  
            //console.log(attrToCheck[i]+" val: "+xstyle[attrToCheck[i]]+" cond: "+attrCond[i]);
            if (xstyle[attrToCheck[i]] != attrCond[i]) {
                if (undefined != xstyle[attrToCheck[i]]) {
                    _aba = true;break;
                }
            }                    
            i++;
        }

        this.isAbActive = _aba; 
        
    },
    fallbackSwitch : function(id,idFallback){
        this.check();
        if (this.isAbActive == true) {
            $(id).setStyle({display: 'none'});
            $(idFallback).setStyle({display: 'block'});
        }
    }

}
