
/**
 * Native Extensions
 */
String.prototype.rtrim = function() {
    return this.replace(/\s+$/, '');
};
String.prototype.ltrim = function() {
    return this.replace(/^\s+/, '');
};
String.prototype.trim = function() {
    return this.rtrim().ltrim();
};

/**
 * Tools
 */

var Utils = {
    log: function(msg) {
        try { console.log( msg );} catch(e) {}
    },

    logException: function(exception) {
        this.log('------------------------------------');
        this.log('Exception was: ' + exception);
        var stack = null;
        if(exception.stack) {
            stack = exception.stack;
        } else if(exception.message) {
            stack = exception.message;
        }
        if(stack != null) {
            stack = stack.split('\n');
            this.log('Begin of Exception Stack');
            for(i in stack) {
                this.log(stack[i]);
            }
            this.log('End of Exception Stack');
            this.log('------------------------------------');
        }
    },

    end:0
};
function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function sameOrigin(url) {
    // url could be relative or scheme relative or absolute
    var host = document.location.host; // host + port
    var protocol = document.location.protocol;
    var sr_origin = '//' + host;
    var origin = protocol + sr_origin;
    // Allow absolute or scheme relative URLs to same origin
    return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
        (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
        // or any other URL that isn't scheme relative or absolute i.e relative.
        !(/^(\/\/|http:|https:).*/.test(url));
}
function safeMethod(method) {
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
/**
 * Setups
 */
jQuery(document).ready(function() {
    jQuery.ajaxSetup({
        beforeSend: function(xhr, settings) {
            if(!safeMethod(settings.type) && sameOrigin(settings.url)) {
                xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
            }
        }
    });
});

/************************************************
 * Rosenthal Features for jQuery
 *
 ************************************************/

/**
 * jQuery.mainMenu
 */
(function($) {

    var properties = {
        main: null,
        slider: null
    };// end properties

    var methods = {
        init: function(options) {
            properties.main = this[0];
            properties.slider = this[1];
            $(properties.main).find('ul > li').hover(
                function(event) {
                    methods.slideTo(event, this);
                },
                function(event) {
                    if(false == $(event.relatedTarget).hasClass('preView')) {
                        methods.slideBack(event, this)
                        $('.preView:visible').fadeOut('');
                    }
                }
            );

            $('.preView').mouseleave(function(event) {
                if(event.relatedTarget.nodeName != 'A') {
                    methods.slideBack();
                    $(this).hide().fadeOut('');
                }
            });
            // Go to initial Pos
            methods.slideBack();
        },// end init

        slideTo: function(event, e) {
            var newWidth = $(e).width() + 14;
            var newPos = $(e).position().left;
            var animations = {'width': newWidth+'px', 'margin-left': newPos+'px'};
            if($(properties.slider).children('.slider').css('visibility') == 'hidden') {
                $(properties.slider).children('.slider').css('visibility', 'visible');
                //animations['visibility'] = 'visible';
            }
            $(properties.slider).children('.slider').stop().animate(animations, 100, 'linear', function() {
                methods._showPreview(event, e)
            });
        },// end slideTo

        slideBack: function(event, e) {
            if($(properties.main).find('ul > li.act').size()) {
                var newPos = $(properties.main).find('ul > li.act').position().left;
                var newWidth = $(properties.main).find('ul > li.act').width() + 14;
                $(properties.slider).children('.slider').stop().animate({'width': newWidth+'px', 'margin-left': newPos+'px'}, 100, 'linear');
            } else {
                $(properties.slider).children('.slider').css('visibility', 'hidden');
                //.animate({'visibility': 'hidden'}, 'fast', 'linear');

            }
        },// end slideBack

        _showPreview: function(event, element) {
            var previewClassPrefix = methods._getPreviewClassPrefix(element);
            if(previewClassPrefix != null && $('.'+previewClassPrefix+'Prev:hidden').size() == 1) {
                $('.preView:visible').fadeOut(100);
                $('.'+previewClassPrefix+'Prev').fadeIn(100, function() {

                });
            }
        },// end showPreview

        _getPreviewClassPrefix: function(element, postfix) {
            postfix = postfix !== undefined ? postfix : 'Nav';
            var previewClassPrefix = null;
            var navClass = element.className.replace(/\s*act\s*/, '').replace(/\s*preView\s*/, '').trim();
            if(navClass != '') {
                previewClassPrefix = navClass.split(postfix)[0];
            }
            return previewClassPrefix;
        },// end _getPreviewClassPrefix

        end : 0
    };// end methods
    $.fn.mainMenu = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.mainMenu');
        }
    };
})(jQuery);

/**
 * jQuery.styledDropDown
 */
(function($) {
    var methods = {
        dropContent: null,
        dropBottom: null,
        jScrollPaneContainer: null,
        toggler: null,
        hiddenField: null,
        defaultText: 'Bitte wählen',

        init : function(options) {
            options = options || {};
            methods.dropContent = this.find('.dropContent');
            methods.dropBottom = this.find('.dropBottom');
            methods.jScrollPaneContainer = this.find('.dropContent ul');
            methods.toggler = this.find('.dropContent > a');
            methods.hiddenField = jQuery('#categorysearch');

            methods.defaultText = this.find('.dropContent > a').text();


            // open / close handler
            // methods.toggler.live('click', methods.toggle);
            methods.toggler.click(methods.toggle);

            if($('#categorysearch').size() && $('#categorysearch').val() != '') {
                var selectedElement = this.find('.dropContent ul > li#cat_'+options.selectedValue + ' > a');
                if(selectedElement.size() == 1) {
                    $(selectedElement).parent().parent().children('.nonselected').show();
                    methods.toggler.text($(selectedElement).text());
                }
            }
            // click handler for selection
            this.find('.dropContent ul > li > a').click(function() {
                if($(this).parent().hasClass('nonselected')) {
                    $(this).parent().hide();
                    methods.hiddenField.val('');
                    methods.toggler.text($(this).text());
                } else {
                    $(this).parent().parent().children('.nonselected').show();
                    var selection = $(this).parent().attr('id').split('cat_')[1];
                    methods.hiddenField.val(selection);
                    methods.toggler.text($(this).text());
                }
                methods.close();
            });
        },// end init

        toggle: function() {
            if($(methods.toggler).hasClass('arrowDown')) {
                methods.open();
            } else if($(methods.toggler).hasClass('arrowUp')) {
                methods.close();
            }
        },// end toggle

        open: function() {
            this.jScrollPaneContainer.show();//css('position', 'relative').css('left', '0').slideDown(100);
            this.dropBottom.removeClass('dropClose');
            this.toggler.removeClass('arrowDown').addClass('arrowUp').attr('title', 'Schließen');
        },// end open

        close: function() {
            this.jScrollPaneContainer.hide();//.slideUp(100);
            this.dropBottom.addClass('dropClose');
            this.toggler.removeClass('arrowUp').addClass('arrowDown').attr('title', 'Öffnen');
        },// end close

        end : 0
    };// end methods
    $.fn.styledDropDown = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.styledDropDown');
        }
    };
})(jQuery);


/**
 * jQuery.headApplication
 */
(function($) {
    var designerInitialised = false;
    var methods = {
        init : function(options) {
            var self = methods;
            options = options !== undefined ? options : {};
            $('.headApplicationMainTab').click(function() {
                var name = this.id.split('headApplicationMainTab_')[1];
                if(name != 'search') {
                    if($('body.cms').size() == 1 && $('body.home').size() == 0) {
                        $.cookie('site_search', null, {path: '/'});
                    } else {
                        $.cookie('product_search', null, {path: '/'});
                    }
                }
                // Startseite ist etwas anders
                if($('body.home').size() == 1) {
                    if($(this).hasClass('open')) {
                        $('.topBox .iconClose').click();
                        $(this).removeClass('open');
                    } else {
                        $('#headApplicationContent_search').fadeIn();
                        $(this).addClass('open');
                        if($('.topBox').css('display') == 'none') {
                            if(options.onOpen !== undefined) {
                                $('.topBox').fadeIn('', options.onOpen);
                            } else {
                                $('.topBox').fadeIn('');
                            }
                        }
                    }
                } else {
                    $('.headApplicationContent').hide();
                    $('#headApplicationContent_'+name).fadeIn('', function() {
                        self.processTabContent( name );
                    });
                    $('.headApplicationMainTab').removeClass('open');
                    $(this).addClass('open');
                    if($('.topBox').css('display') == 'none') {
                        if(options.onOpen !== undefined) {
                            $('.topBox').fadeIn('', options.onOpen);
                        } else {
                            $('.topBox').fadeIn('');
                        }
                    }
                }


                // TabNav
                // Ersten wieder aktivieren
                if($('UL#tabNav_'+name).size()) {
                    $('UL#tabNav_'+name).children('li').removeClass('act').find('a > span').addClass('arrowOpen').removeClass('arrowDown');
                    $('UL#tabNav_'+name).children('li:first').addClass('act').find('a > span').removeClass('arrowOpen').addClass('arrowDown');
                }
                if($('.tabNav UL').not('UL#tabNav_'+name).size() && $('.tabNav UL').not('UL#tabNav_'+name).css('top') == '0px') {
                    $('.tabNav UL').not('UL#tabNav_'+name).animate({top: '29px'}, 300);
                    $('.cornerTL').removeClass('cornerInfo');
                }
                if($('UL#tabNav_'+name).size() && $('UL#tabNav_'+name).css('top') != '0px') {
                    $('UL#tabNav_'+name).animate({top: '0px'}, 300);
                    $('.cornerTL').addClass('cornerInfo');
                }

            });
            $('.topBox .iconClose').click(function() {
                $('.topBox').hide();
                $('.headApplicationContent').hide();
                $('.headApplicationMainTab').removeClass('open');
                if($('body.cms').size() == 1 && $('body.home').size() == 0) {
                    $.cookie('site_search', null, {path: '/'});
                } else {
                    $.cookie('product_search', null, {path: '/'});
                }
            });
            // Tab Navis wenn vorhanden
            $('div.tabNav > ul > li > a').click(function() {
                var name = this.id.split('tab_')[1];
                $(this).parent().parent().children('li').removeClass('act').find('a > span').addClass('arrowOpen').removeClass('arrowDown')
                $(this).children('span').addClass('arrowDown').removeClass('arrowOpen').parent().parent().addClass('act');
                if(name.length && $('#headApplicationContent_'+name).size()) {
                    $('#headApplicationContent_'+name).fadeIn('', function() {
                        self.processTabContent( name );
                    });
                    $('.headApplicationContent:not(#headApplicationContent_'+name+')').hide();
                }
            });

            if($('a.designerlink').size()) {
                $('a.designerlink').click(function() {
                    var id = this.id.split('designerlink_')[1];
                    if(id) {
                        methods.designer(id);
                    }
                    return false;
                });
            }

            /*
             * Search Form Cookie
             */
            $('form[name=searchform]').submit(function() {
                if($('body.cms').size() == 1 && $('body.home').size() == 0) {
                    $.cookie('site_search', 'opened', {path: '/'});
                } else {
                    $.cookie('product_search', 'opened', {path: '/'});
                }
            });

            // Initial state here
            if(/*$('body.home').size() == 1 ||*/ $.cookie('product_search') == 'opened') { // Temporary closed Search at startpage
                $('#headApplicationMainTab_search').click();
            } else if($('body.home').size() == 0 && $('body.cms').size() == 1 && $.cookie('site_search') == 'opened') {
                $('#headApplicationMainTab_search').click();
            } else if($('#headApplicationMainTab_info').size() == 1) {
                $('#headApplicationMainTab_info').click();
            }
            $('.headApplicationContent:visible').each(function() {
                var name = this.id.split('headApplicationContent_')[1];
                self.processTabContent( name );
            });
        },// end init

        processTabContent: function( name ) {
            // Clean from old more/less Anchors
            if(name != 'search') {
                $('#headApplicationContent_'+name).find('a.more,a.less').remove();
                $('#headApplicationContent_'+name).find('p.contentMore').removeClass('contentMore');
                // Scrollbar
                if( $('#headApplicationContent_'+name + ' > div.headApplicationInnerContent').size() == 0) {
                    var html = $('#headApplicationContent_'+name).html();
                    $('#headApplicationContent_'+name).html('<div class="headApplicationInnerContent">'+html+'</div>');
                }
                $('#headApplicationContent_'+name + ' > div.headApplicationInnerContent').scrollbar(Rosenthal.scrollbarOptions);
            }
        },

        designer: function(id) {
            var url = Rosenthal.designer.ajaxDetailUrl;
            jQuery.post(url, {'id': id}, function(data, textStatus, jqXHR) {
                $('#headApplicationContent_designer').html(data);
                $('html,body').animate({
                    scrollTop: 0
                }, 800, function() {
                    if(!$('#headApplicationMainTab_info').hasClass('open')) {
                        $('#headApplicationMainTab_info').click();
                    }
                    $('div.tabNav > ul > li > a#tab_designer').click();
                });
            });
        },// end designer
        end : 0
    };// end methods


    $.fn.headApplication = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.headApplication');
        }
    };
})(jQuery);


/**
 * jQuery.categoryWidget
 * To be called on $('.teaserBox').categoryWidget();
 */
(function($) {
    var methods = {

        init : function(options) {
            this.find('.teaserInner > .oneThird > h4').mouseover(function() {
                var height = $(this).next().children('ul').height()+33;
                $(this).addClass('open').next().addClass('open').css('min-height', height+'px').children('ul').first().animate({top: '0'}, 300);
            });
            this.find('.teaserInner > .oneThird').mouseleave(function() {
                $(this).children('h4').removeClass('open').next().first().children('ul').first().animate({top: '-301px'}, 600, function() {
                    $(this).parent().removeClass('open').css('min-height', '0');
                });
            });
        },// end init
        end : 0
    };// end methods


    $.fn.categoryWidget = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.categoryWidget');
        }
    };
})(jQuery);




/**
 * jQuery.i18n
 */
(function($) {
    var methods = {

        init : function(options) {
            var langselector = this.find('input[name=language]');
            var nextValue = this.find('input[name=next]');
            var form = this;
            this.find('ul >li > a').click(function(){
                var lang = this.rel.split('lang_')[1];
                langselector.val( lang );
                if(Rosenthal.i18n.lang_urls !==  undefined && Rosenthal.i18n.lang_urls[lang] !== undefined) {
                    nextValue.val(Rosenthal.i18n.lang_urls[lang]);
                }
                form.submit();
                return false;
            });
        },// end init
        end : 0
    };// end methods


    $.fn.i18n = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.i18n');
        }
    };
})(jQuery);


/**
 * jQuery.rosenthalCart
 * Call this Plugin on all valid add_to_cart forms
 * @requires jQuery.form plugin
 */

var RosenthalCart = {

    init : function(url) {
        // Basket Scroll View
        RosenthalCart.updateOrCreateScrollbar();
        // Ajax form handler
        if($('form.add_to_cart').size()) {
            $('form.add_to_cart').each(function(index, element) {
                $(element).ajaxForm({
                    url: 			Rosenthal.cart.addUrl,
                    beforeSubmit:  	RosenthalCart.validate,
                    success:       	RosenthalCart.upadteCart,
                    dataType:  		'json',
                    error: RosenthalCart.error
                });
            });
        }

        if($('a.basketIcon:not(.nonbasketIcon)').size()) {
            $('a.basketIcon:not(.nonbasketIcon)').click(function() {
                slug = this.id.split('addcart_')[1];
                RosenthalCart.buyNow( slug );
                return false;
            });
        }

        if($('a.buynow').size()) {
            $('a.buynow').click(function() {
                slug = this.id.split('buynow_')[1];
                RosenthalCart.buyNow( slug );
                return false;
            });
        }

        // open close handler
        $( '.basketDisplay' ).click( function() {
            $('.contentBasket').addClass('basketOpen');
            $('.basketBox').css({left: 0});
            RosenthalCart.updateOrCreateScrollbar();
//            $('.basketBox,.boxBottomSmall').fadeIn('', function() {
//
//            });
        });
        $( '.contentBasket a.btnSmallLev' ).click( function() {
            $('.contentBasket').removeClass('basketOpen');
//            $('.basketBox,.boxBottomSmall').fadeOut('');
            $('.basketBox').css({left: '-4400px'});
        });
    },// end init


    /**
     * One Click add To Cart via ajax
     * @param {string} slug
     */
    buyNow: function(slug) {
        jQuery.ajax(Rosenthal.cart.addUrl, {
            data: {slug: slug, quantity: 1},
            success: RosenthalCart.upadteCart,
            type: 'POST',
            dataType: 'json',
            error: RosenthalCart.error
        });
    },// end buyNow

    /**
     * Validate Form
     */
    validate: function(formData, jqForm, options) {
        for(index in formData) {
            if(formData[index].name == 'quantity') {
                if( parseInt( formData[index].value ) > 0) {
                    return true;
                } else {
                    $('.ttSmall').rstThickbox({content: '<p>' + Rosenthal.i18n.error_pls_set_valid_amount + '</p>', autoClose: 2000});
                    return false;
                }
            }
        }
        return true
    },// end validate

    upadteCart: function(data) {
        if(data.error !== undefined && data.error != "") {
            // TODO Fehlermeldungen
            $('.ttSmall').rstThickbox({content: '<p>' + data.error + '</p>', autoClose: 2000});
        } else if(data.results !== undefined && data.results == 'success') {
            var cartDisplay = $('.basketBox > div ul');
            if(cartDisplay.size()) {
                cartDisplay.empty();
                c = data.cart
                var lis = $('#cart_template').jqote(c);
                cartDisplay.html(lis).find('li:last').addClass('last');
                $('.basketDisplay > #number_entries').html(data.cart_count);
                $('.basketDisplay > #cart_total').html(data.cart_total);
            }

            // Update availability icon
            if($('#availability_' + data.added_slug).size()) {
                $('#availability_' + data.added_slug).attr('class', 'icon availability ' + data.added_availability_color + 'Icon');
            }
            $('form#product_detail_add_to_cart #quantity').val('1');
//             Block Add To Cart Buttons if availability changes to no available
            if( data.added_availability_color == 'red' || data.added_availability_color == 'grey') {
                if(data.new_availability_text !== undefined ) {
                    $('#availability_' + data.added_slug).attr('title', data.new_availability_text);
                }
                $('form#product_detail_add_to_cart #quantity').hide();
                if($('#addcart_' + data.added_slug).size()) {
                    $('#addcart_' + data.added_slug).attr('class', 'icon nonbasketIcon');
                    $('#addcart_' + data.added_slug).unbind('click');
                }
                if($('#buynow_' + data.added_slug).size()) {
                    $('#buynow_' + data.added_slug).addClass('unavailable');
                    $('#buynow_' + data.added_slug).unbind('click');
                }
                if($('form#product_detail_add_to_cart').size()) {
                    $('form#product_detail_add_to_cart').unbind('submit').submit(function() {
                        return false;
                    }).find('button').addClass('unavailable');;
                }
            }
            RosenthalCart.addedAnimation(data);
            $('.ttSmall').rstThickbox({content: '<p>' + Rosenthal.i18n.article_has_beed_added_to_cart + '</p>', autoClose: 2000});
            RosenthalCart.updateOrCreateScrollbar();
        }
    },// end upadteCart

    updateOrCreateScrollbar: function() {
        if($('#basketScroller .scrollbar-pane').size()) {
            $('#basketScroller').scrollbar('repaint');
        } else {
            $('#basketScroller').scrollbar(Rosenthal.scrollbarOptions);
        }
    },// end updateOrCreateScrollbar

    error: function(jqXHR, textStatus, errorThrown) {
        var data = eval('[' + jqXHR.responseText + ']');
        RosenthalCart.upadteCart(data[0]);
    },// end error

    addedAnimation: function(data) {
        if(data.added_slug != '' && $('#addcart_'+data.added_slug).size()) {
            $('#addcart_'+data.added_slug).addClass('fullIcon');
        }
        $('.iconBasket').addClass('full');
        $('.aniStars').fadeIn(200);
        window.setTimeout(function(){
            $('.aniStars').fadeOut(200);
        }, 500);
        window.setTimeout(function(){
            $('.ttArticle').fadeIn(200);
        }, 500);
        window.setTimeout(function(){
            $('.ttArticle').fadeOut(200);
        }, 1500);
    },// end addedAnimation
    end : 0
};// end methods
jQuery.extend({
    rosenthalCart: function(method) {
        if (RosenthalCart[method]) {
            return RosenthalCart[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return RosenthalCart.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.rosenthalCart');
        }
    }
});


var RosenthalWishlist = {
    init: function(options) {
        jQuery('.leafletIcon').click(function() {
            var slug = this.id.split('towishlist_')[1];
            jQuery.post(Rosenthal.wishlist.addUrl, {productname: slug}, function(data, textStatus, jqXHR) {
                if(data.error !== undefined && data.error != '') {
                    var tbOptions = {content: '<p>' + data.error + '</p>', autoClose: 2000}
                    if(data.error_type !== undefined && data.error_type == 'login') {
                        $('#loginform_next').val( Rosenthal.currentUrl );
                        tbOptions.onClose = function() {
                            $('html,body').animate({
                                scrollTop: 0
                            }, 800 , function (){
                                $( 'li.myRsth a' ).click();
                            });
                        };
                    }
                    $('.ttSmall').rstThickbox(tbOptions);
                } else if(data.success) {
                    $('#towishlist_' + slug ).addClass('noticedIcon');
                    $('.ttSmall').rstThickbox({content: '<p>' + data.success + '</p>', autoClose: 2000});
                }
                return false;
            }, 'json');
        });
    },// end init

    end: 0
};
jQuery.extend({
    rosenthalWishlist: function(method) {
        if (RosenthalWishlist[method]) {
            return RosenthalWishlist[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return RosenthalWishlist.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.rosenthalWishlist');
        }
    }
});


/**
 * jQuery.cleverReach
 */
(function($) {
    var CleverReach = {

        init: function(options) {
            this.find('button[type=submit]').click(function() {
                CleverReach.action( this.value );
                return false;
            });
        },// end init

        /**
         * Subscribe / Unsubscribe Action from HEADER REGISTRATION FORM
         */
        action: function(calltype) {
            var url = Rosenthal.newsletter.cleverreachUrl;
            var data = {
                calltype: calltype,
                email:  document.getElementById("nl-email").value,
                firstname: document.getElementById("nl-firstname").value,
                lastname: document.getElementById("nl-lastname").value
            };
            $.get(url, data, function(response) {
                var tbOptions = { content: '<p>' + response.message + '</p>', autoClose: 4000 };
                if(response.status == 'ok') { // TODO: only close the newsletterform if no error has occured...
                    tbOptions.onClose = function() {
                        $( '.metaBox .iconClose' ).click();
                    };
                }
                $('.ttSmall').rstThickbox( tbOptions );
            }, 'json');
        },// end call

        /**
         * Check if email is registered for shop registration process
         */
        isRegistered: function(emailAddress, callBack) {
            var isRegistered = false;
            var data = {'email': emailAddress, 'calltype': 'is_registered'};
            var url = Rosenthal.newsletter.cleverreachUrl;
            $.get(url, data, function(response) {
                if(response.result == 'NOT_REGISTERED') {
                    isRegistered = false;
                } else if(response.result == 'REGISTERED') {
                    isRegistered = true;
                }
                if(callBack !== undefined) {
                    callBack(isRegistered);
                }
            }, 'json');
        },// end isRegistered
        end : 0
    };// end methods


    $.fn.cleverReach = function(method) {
        if (CleverReach[method]) {
            return CleverReach[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return CleverReach.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.cleverReach');
        }
    };
})(jQuery);

/**
 * jQuery.rstThickbox
 * Call on one of the Thickbox Templates.
 * <usage>
 * var options = {content: 'Yeahhhh!', autoClose: 3000};
 * $('.ttSmall').rstThickbox(options);
 *
 * $('.ttSmall').rstThickbox({content: Rosenthal.i18n.article_has:_been_added});
 *
 * var options = {content: 'Some html by Ajax?', autoClose=false};
 * $('.ttMedium').rstThickbox(options);
 *
 * var options = {content: '<h1>Blah<h1/>', contentProcessor: function(ttContent, img) {
 * 		ttContent = ttContent.after(img);
 * 		return ttContent;
 * }};
 * $('.ttLarge').rstThickbox(options);
 *  </usage>
 *
 *  Options are
 * @param content (required) html/text content
 * @param autoClose (int, optional) Thickbox should close automatically after
 * \<autoClose\> ms
 * @param contentProcessor (Function, optional) a function which takes the content
 * with its ttContentWrapper in order to manipulate it, eg for putting that damn
 * Productimage outside the ttContent wrapper.
 *
 */
(function($) {
    var RstThickbox = {

        thickbox: null,
        options: {},
        timeOut: null,

        init : function(options) {
            // First,d estroy all opened TBs
            if(options !== undefined) {
                RstThickbox.options = options;
            }
            $('.toolTip:not(.template)').remove();
            var tb = this.clone();
            RstThickbox.thickbox = tb;
            RstThickbox.thickbox.removeClass('template');
            RstThickbox.thickbox.find('.ttContent').html(options.content);
            if(options.contentClass !== undefined) {
                RstThickbox.thickbox.find('.ttContent').addClass(options.contentClass);
            }
            if(options.content !== undefined) {
                if(options.contentProcessor !== undefined) {
                    options.contentProcessor.apply(RstThickbox.thickbox);
                }
            } else {
                $.error('The options must have a content element.');
            }
            var closeButton = RstThickbox.thickbox.find('.iconClose');
            RstThickbox.thickbox.appendTo('body');
            if(RstThickbox.options.fixedHeight !== undefined && RstThickbox.options.fixedHeight == true) {
                RstThickbox.thickbox.find('.ttInner').addClass('fixedHeight');
            }
            tb.css({display:'block', visibility: 'hidden'});
            RstThickbox.position(tb);
            tb.css({display:'none', visibility: 'visible'});
            var callback = function() {};
            if(RstThickbox.options.fixedHeight !== undefined && RstThickbox.options.fixedHeight == true) {
                callback = function() {
                    var funcy = function() {
                        RstThickbox.thickbox.find('.ttContent').scrollbar(Rosenthal.scrollbarOptions);
                    };
                    var to = window.setTimeout(funcy, 200);
                };
            }
            RstThickbox.thickbox.fadeIn('fast', callback);
            $('.ttOverlay').fadeIn('fast', function() {
                RstThickbox.thickbox.fadeIn('fast', callback);
            }).width($(window).width()).height($(window).height()).click(function() {
                RstThickbox.destroy();
            });

            if(closeButton.size()) {
                closeButton.click(function() {RstThickbox.destroy();});
            }
            if(options.autoClose !== undefined && options.autoClose > 0) {
                RstThickbox.timeOut = window.setTimeout(RstThickbox.destroy, options.autoClose);
            }
        },// end init

        position: function(e) {
            var pos = function(el) {
                var tbWidth = el.width();
                var tbHeight = el.height();
                var innerWidth = $(window).width();
                var innerHeight = $(window).height();
                var leftPos = parseInt((innerWidth - tbWidth) / 2);
                var topPos = parseInt((innerHeight - tbHeight) / 2);
                el.css({left: leftPos + "px", top: topPos + "px"});
            }
            pos(e);
        },// end position

        destroy: function() {
            if(RstThickbox.thickbox != null) {
                $('.ttOverlay').fadeOut('fast');
                RstThickbox.thickbox.fadeOut('fast', function()  {
                    RstThickbox.thickbox.remove();
                    if(RstThickbox.options.onClose !== undefined) {
                        RstThickbox.options.onClose();
                    }
                    RstThickbox.options = {};
                    if(RstThickbox.timeOut != null) {
                        window.clearTimeout( RstThickbox.timeOut );
                        RstThickbox.timeOut = null;
                    }
                })
            }
        },// end destroy
        end : 0
    };// end methods


    $.fn.rstThickbox = function(method) {
        if (RstThickbox[method]) {
            return RstThickbox[method].apply(this, Array.prototype.slice.call(
                    arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return RstThickbox.init.apply(this, arguments);
        } else {
            $.error('Method ' + method
                    + ' does not exist on jQuery.rstThickbox');
        }
    };
})(jQuery);

var RosenthalStudioStock = {
        init: function() {
            jQuery('.availability').click(function() {
                var slug = this.id.split('availability_')[1];
                jQuery.post(Rosenthal.productavailability.ajaxUrl, {slug: slug}, function(response) {
                    $('.ttBig').rstThickbox({content: response, autoClose: false, fixedHeight: true});
                });
                return false;
            });
        },// end init

        end:0
    };

/**
 * Allgemines, noch nicht in Plugins gezaubert
 */
jQuery(document).ready(function() {
    // Meta Navi oben
    $( '.metaMenu li a' ).click( function() {
        $('.metaBox').fadeIn(200);
        $('.contentBasket').removeClass('basketOpen');
        $('.basketBox').css('left', '-4400px');
//        $('.contentBasket .boxBottomSmall').fadeOut('');
    });
    $( 'li.myRsth a' ).click( function() {
        $('div.myRsth').show('');
        $('div.contact').hide('');
        $('div.newsletter').hide('');
        $('div.language').hide('');
    });
    $( 'li.contact a' ).click( function() {
        $('div.contact').show('');
        $('div.myRsth').hide('');
        $('div.myRsth').hide('');
        $('div.language').hide('');
    });
    $( '.news' ).click( function() {
        $('div.newsletter').fadeIn('');
        $('div.contact').hide('');
    });
    $( '.lang' ).click( function() {
        $('div.language').fadeIn('');
        $('div.contact').hide('');
        $('div.newsletter').hide('');
        $('div.myRsth').hide('');
    });
    $( 'a.closeBox' ).click( function() {
        $('.metaBox').fadeOut(200);
    });
    $( '.metaBox .iconClose' ).click( function() {
        $('.metaBox').fadeOut(200);
        $('div.newsletter').hide('');
    });
    // Error messages in forms
    $( '.errorBox' ).live('mouseover', function() {
        $(this).fadeOut('fast');
    });
    $( 'input,textarea' ).live('focus', function() {
        if($(this).next().hasClass('errorBox')) {
            $(this).next().fadeOut('fast');
        }
    });
    // _blank link replacement
    $('.new_window').live('click', function() {
        var win = window.open(this.href);
        return false;
    });

    /*
     * Thickboxen aller Art
     */
    // Shipping
    $('.tb_shipping').click(function() {
        var url = Rosenthal.isSecure ? '/ajax-cms-shipping-costs-ssl/' : '/ajax-cms-shipping-costs/';
        jQuery.get(url, {}, function(response) {
            $('.ttBig').rstThickbox({content: response, autoClose: false, fixedHeight:true});
        });
        return false;
    });
    // Termn and conditions
    $('.tb_terms').click(function() {
    	var url = Rosenthal.isSecure ? '/ajax-cms-terms-and-conditions-ssl/' : '/ajax-cms-terms-and-conditions/';
        jQuery.get(url, {}, function(response) {
            $('.ttBig').rstThickbox({content: response, autoClose: false, fixedHeight:true});
        });
        return false;
    });
    // Privacy policy
    $('.tb_privacy').click(function() {
    	var url = Rosenthal.isSecure ? '/ajax-cms-privacy-policy-ssl/' : '/ajax-cms-privacy-policy/';    		
        jQuery.get(url, {}, function(response) {
            $('.ttBig').rstThickbox({content: response, autoClose: false, fixedHeight:true});
        });
        return false;
    });
    // openNLRegisterForm: Newsletter Link in Footer, scrolls up and opens Layer
    $('.openNLRegisterForm').click(function() {
        $('html,body').animate({
            scrollTop: 0
        }, 800 , function (){
            $('.metaBox').show();
            $('.metaBox div.newsletter').show();
            $('.metaBox .myRsth').hide();
        });
        return false;
    });

    // Tell a friend / E-Mail recommendation
    if($('.email_recommendation').size()) {
        $('#tellafriendform').live('submit', function() {
            $('#tellafriendform').ajaxSubmit({
                target: $('.ttBig:not(.template) .ttContent'),
                success: function(response) {
                    if($('#recaptcha_widget').size()) {
                        Recaptcha.create(Rosenthal.captchaKey, '', { theme : 'custom', custom_theme_widget: 'recaptcha_widget', contentClass: 'recommendation'});
                    }
                }
            });
            return false;
        })
        $('.email_recommendation').click(function() {
            var slug = this.id.split('email_recommendation_')[1];
            var url = Rosenthal.tellafriend.ajaxUrl;
            jQuery.get(url, {slug: slug}, function(response) {
                $('.ttBig').rstThickbox({content: response, autoClose: false, fixedHeight:true, contentClass: 'recommendation'});
                Recaptcha.create(Rosenthal.captchaKey, '', { theme : 'custom', custom_theme_widget: 'recaptcha_widget'});
            });
            return false;
        });
    }

    // Raffle / Gewinnspiel AGB-Thickbox
    if( $('.tb_raffle-agb').size() && $('#hidden_raffle_terms_container').size()) {
        $('.tb_raffle-agb').click(function() {
            $('.ttBig').rstThickbox({content: $('#hidden_raffle_terms_container').html(), autoClose: false, fixedHeight:true});
            return false;
        });
    }

    // cycling teasers on start pages
    if( $('#sliding_category_images').size() ) {
        if($('#sliding_category_images [class^="btn"]').size()) {
            $('#sliding_category_images [class^="btn"]').hide();
        }
        $('#sliding_category_images').cycle( {fx: 'fade', speed: 800, timeout: 6000} );
        $('#sliding_category_images').hover(function() {
            $('#sliding_category_images').cycle('pause');
            $('#sliding_category_images [class^="btn"]').show();
        }, function() {
            $('#sliding_category_images').cycle('resume');
            $('#sliding_category_images [class^="btn"]').hide();
        });
    }
});


