
// reg exps
var rx_email=new RegExp("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*\.(([0-9]{1,3})|([a-z]{2,3})|(aero|coop|info|museum|name))$","gi");

// prototypes
String.prototype.trim = function() { return (this.replace(/\s+$/,"").replace(/^\s+/,"")); };

// Little helpers
var ie6 = typeof(ie6)!='undefined'?true:false;
var standorte_timer = 0;

function showStoreDetails(divid) {
    if (ie6) { $('select').hide(); }
    $('[id!='+divid+'].standortdetail').fadeOut('fast');
    var $div = $('#'+divid);
    $div.addClass('active').fadeIn('fast').mouseleave(function(){
        $(this).fadeOut('fast');
    });
}

function afterVoptnclickAnimation(voptn) {
    if (voptn=='list') {
        var $descrs = $('#productlist .items span.descr');
        $descrs.each(function(i) {
            var $measuring = $('.measuring', this);
            if ($measuring.height() > $(this).height()) {
               if ($('a', this).length < 1 ) {
                   var href=$(this).siblings('a').attr('href');
                   $(this).append('<a href="'+href+'">&raquo; <span>' + trans["weiterlesen"] + '&hellip;</span></a>');
                    $('a', this).hide().addClass('more').fadeIn('slow');
                }
            }
        });
    }
}

// plugin inlineLabel

;(function($) {
    $.inlineLabel = {
        defaults: {
            txt: 'label'
        }
    };

    $.fn.extend({
        inlineLabel: function(settings) {
            settings = $.extend({}, $.inlineLabel.defaults, settings);

            return this.each(function() {
                var j = jQuery;     // jQuery object.
                var $obj = j(this);    // input object (type text)
                $obj.focus(function(){
                    $obj.removeClass('err').attr('title', '');
                    $obj.val($obj.val().trim());
                    if ($obj.val() == settings.txt) { 
                        $obj.val('').css('font-style', 'normal');
                    }
                });
            
                $obj.blur(function(){
                    $obj.val($obj.val().trim());
                    if ($obj.val() == '' || $obj.val() == settings.txt) { 
                        $obj.css('font-style', 'italic').val(settings.txt);
                    } else {
                        if (typeof(settings.regexp)=='object') {
                           if (settings.regexp.test($obj.val())==false) {
                               $obj.addClass('err').attr('title', trans['plsCheckYourInput']);
                           }
                        }
                    }
                });

                $obj.blur();

            });
        }
    });
})(jQuery);

// plugin livequery

/*! Copyright (c) 2008 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) 
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 *
 * Version: 1.0.3
 * Requires jQuery 1.1.3+
 * Docs: http://docs.jquery.com/Plugins/livequery
 */

(function($) {
	
$.extend($.fn, {
	livequery: function(type, fn, fn2) {
		var self = this, q;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// See if Live Query already exists
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context &&
				type == query.type && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) )
					// Found the query, exit the each loop
					return (q = query) && false;
		});
		
		// Create new Live Query if it wasn't found
		q = q || new $.livequery(this.selector, this.context, type, fn, fn2);
		
		// Make sure it is running
		q.stopped = false;
		
		// Run it immediately for the first time
		q.run();
		
		// Contnue the chain
		return this;
	},
	
	expire: function(type, fn, fn2) {
		var self = this;
		
		// Handle different call patterns
		if ($.isFunction(type))
			fn2 = fn, fn = type, type = undefined;
			
		// Find the Live Query based on arguments and stop it
		$.each( $.livequery.queries, function(i, query) {
			if ( self.selector == query.selector && self.context == query.context && 
				(!type || type == query.type) && (!fn || fn.$lqguid == query.fn.$lqguid) && (!fn2 || fn2.$lqguid == query.fn2.$lqguid) && !this.stopped )
					$.livequery.stop(query.id);
		});
		
		// Continue the chain
		return this;
	}
});

$.livequery = function(selector, context, type, fn, fn2) {
	this.selector = selector;
	this.context  = context || document;
	this.type     = type;
	this.fn       = fn;
	this.fn2      = fn2;
	this.elements = [];
	this.stopped  = false;
	
	// The id is the index of the Live Query in $.livequery.queries
	this.id = $.livequery.queries.push(this)-1;
	
	// Mark the functions for matching later on
	fn.$lqguid = fn.$lqguid || $.livequery.guid++;
	if (fn2) fn2.$lqguid = fn2.$lqguid || $.livequery.guid++;
	
	// Return the Live Query
	return this;
};

$.livequery.prototype = {
	stop: function() {
		var query = this;
		
		if ( this.type )
			// Unbind all bound events
			this.elements.unbind(this.type, this.fn);
		else if (this.fn2)
			// Call the second function for all matched elements
			this.elements.each(function(i, el) {
				query.fn2.apply(el);
			});
			
		// Clear out matched elements
		this.elements = [];
		
		// Stop the Live Query from running until restarted
		this.stopped = true;
	},
	
	run: function() {
		// Short-circuit if stopped
		if ( this.stopped ) return;
		var query = this;
		
		var oEls = this.elements,
			els  = $(this.selector, this.context),
			nEls = els.not(oEls);
		
		// Set elements to the latest set of matched elements
		this.elements = els;
		
		if (this.type) {
			// Bind events to newly matched elements
			nEls.bind(this.type, this.fn);
			
			// Unbind events to elements no longer matched
			if (oEls.length > 0)
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						$.event.remove(el, query.type, query.fn);
				});
		}
		else {
			// Call the first function for newly matched elements
			nEls.each(function() {
				query.fn.apply(this);
			});
			
			// Call the second function for elements no longer matched
			if ( this.fn2 && oEls.length > 0 )
				$.each(oEls, function(i, el) {
					if ( $.inArray(el, els) < 0 )
						query.fn2.apply(el);
				});
		}
	}
};

$.extend($.livequery, {
	guid: 0,
	queries: [],
	queue: [],
	running: false,
	timeout: null,
	
	checkQueue: function() {
		if ( $.livequery.running && $.livequery.queue.length ) {
			var length = $.livequery.queue.length;
			// Run each Live Query currently in the queue
			while ( length-- )
				$.livequery.queries[ $.livequery.queue.shift() ].run();
		}
	},
	
	pause: function() {
		// Don't run anymore Live Queries until restarted
		$.livequery.running = false;
	},
	
	play: function() {
		// Restart Live Queries
		$.livequery.running = true;
		// Request a run of the Live Queries
		$.livequery.run();
	},
	
	registerPlugin: function() {
		$.each( arguments, function(i,n) {
			// Short-circuit if the method doesn't exist
			if (!$.fn[n]) return;
			
			// Save a reference to the original method
			var old = $.fn[n];
			
			// Create a new method
			$.fn[n] = function() {
				// Call the original method
				var r = old.apply(this, arguments);
				
				// Request a run of the Live Queries
				$.livequery.run();
				
				// Return the original methods result
				return r;
			}
		});
	},
	
	run: function(id) {
		if (id != undefined) {
			// Put the particular Live Query in the queue if it doesn't already exist
			if ( $.inArray(id, $.livequery.queue) < 0 )
				$.livequery.queue.push( id );
		}
		else
			// Put each Live Query in the queue if it doesn't already exist
			$.each( $.livequery.queries, function(id) {
				if ( $.inArray(id, $.livequery.queue) < 0 )
					$.livequery.queue.push( id );
			});
		
		// Clear timeout if it already exists
		if ($.livequery.timeout) clearTimeout($.livequery.timeout);
		// Create a timeout to check the queue and actually run the Live Queries
		$.livequery.timeout = setTimeout($.livequery.checkQueue, 20);
	},
	
	stop: function(id) {
		if (id != undefined)
			// Stop are particular Live Query
			$.livequery.queries[ id ].stop();
		else
			// Stop all Live Queries
			$.each( $.livequery.queries, function(id) {
				$.livequery.queries[ id ].stop();
			});
	}
});

// Register core DOM manipulation methods
$.livequery.registerPlugin('append', 'prepend', 'after', 'before', 'wrap', 'attr', 'removeAttr', 'addClass', 'removeClass', 'toggleClass', 'empty', 'remove');

// Run Live Queries when the Document is ready
$(function() { $.livequery.play(); });


// Save a reference to the original init method
var init = $.prototype.init;

// Create a new init method that exposes two new properties: selector and context
$.prototype.init = function(a,c) {
	// Call the original init and save the result
	var r = init.apply(this, arguments);
	
	// Copy over properties if they exist already
	if (a && a.selector)
		r.context = a.context, r.selector = a.selector;
		
	// Set properties
	if ( typeof a == 'string' )
		r.context = c || document, r.selector = a;
	
	// Return the result
	return r;
};

// Give the init function the jQuery prototype for later instantiation (needed after Rev 4091)
$.prototype.init.prototype = $.prototype;
	
})(jQuery);

// plugin autocomplete

jQuery.autocomplete = function(input, options) {
    // Create a link to self
    var me = this;

    // Create jQuery object for input element
    var $input = $(input).attr("autocomplete", "off");
    var $submit = $('input#searchformsubmit');

    // Apply inputClass if necessary
    if (options.inputClass) {
        $input.addClass(options.inputClass);
    }

    // Create results
    var results = document.createElement("div");

    // Create jQuery object for results
    // var $results = $(results);
    var $results = $(results).hide().addClass(options.resultsClass).css("position", "absolute");
    if( options.width > 0 ) {
        $results.css("width", options.width);
    }

    // Add to body element
    $("body").append(results);

    input.autocompleter = me;

    var timeout = null;
    var prev = "";
    var active = -1;
    var cache = {};
    var keyb = false;
    var hasFocus = false;
    var lastKeyPressCode = null;
    var mouseDownOnSelect = false;
    var hidingResults = false;

    // flush cache
    function flushCache(){
        cache = {};
        cache.data = {};
        cache.length = 0;
    };

    // flush cache
    flushCache();

    // if there is a data array supplied
    if( options.data != null ){
        var sFirstChar = "", stMatchSets = {}, row = [];

        // no url was specified, we need to adjust the cache length to make sure it fits the local data store
        if( typeof options.url != "string" ) {
            options.cacheLength = 1;
        }

        // loop through the array and create a lookup structure
        for( var i=0; i < options.data.length; i++ ){
            // if row is a string, make an array otherwise just reference the array
            row = ((typeof options.data[i] == "string") ? [options.data[i]] : options.data[i]);

            // if the length is zero, don't add to list
            if( row[0].length > 0 ){
                // get the first character
                sFirstChar = row[0].substring(0, 1).toLowerCase();
                // if no lookup array for this character exists, look it up now
                if( !stMatchSets[sFirstChar] ) stMatchSets[sFirstChar] = [];
                // if the match is a string
                stMatchSets[sFirstChar].push(row);
            }
        }

        // add the data items to the cache
        for( var k in stMatchSets ) {
            // increase the cache size
            options.cacheLength++;
            // add to the cache
            addToCache(k, stMatchSets[k]);
        }
    }

    $input
    .keydown(function(e) {
        // track last key pressed
        lastKeyPressCode = e.keyCode;
        switch(e.keyCode) {
            case 38: // up
                e.preventDefault();
                moveSelect(-1);
                break;
            case 40: // down
                e.preventDefault();
                moveSelect(1);
                break;
            case 9:  // tab
            case 13: // return
                if( selectCurrent() ){
                    // make sure to blur off the current field
                    $input.get(0).blur();
                    e.preventDefault();
                }
//                if ($input.val()) $submit.focus();
                break;
            default:
                active = -1;
                if (timeout) clearTimeout(timeout);
                timeout = setTimeout(function(){onChange();}, options.delay);
                break;
        }
    })
    .focus(function(){
        // track whether the field has focus, we shouldn't process any results if the field no longer has focus
        hasFocus = true;
    })
    .blur(function() {
        // track whether the field has focus
        hasFocus = false;
        if (!mouseDownOnSelect) {
            hideResults();
        }
    });

    hideResultsNow();

    function onChange() {
        // ignore if the following keys are pressed: [del] [shift] [capslock]
        if( lastKeyPressCode == 46 || (lastKeyPressCode > 8 && lastKeyPressCode < 32) ) return $results.hide();
        var v = $input.val();
        if (v == prev) return;
        prev = v;
        if (v.length >= options.minChars) {
            $input.addClass(options.loadingClass);
            requestData(v);
        } else {
            $input.removeClass(options.loadingClass);
            $results.hide();
        }
    };

    function moveSelect(step) {

        var lis = $("li", results);
        if (!lis) return;

        active += step;

        if (active < 0) {
            active = 0;
        } else if (active >= lis.size()) {
            active = lis.size() - 1;
        }

        lis.removeClass("ac_over");

        $(lis[active]).addClass("ac_over");

        // Weird behaviour in IE
        // if (lis[active] && lis[active].scrollIntoView) {
        //     lis[active].scrollIntoView(false);
        // }

    };

    function selectCurrent() {
        var li = $("li.ac_over", results)[0];
        if (!li) {
            var $li = $("li", results);
            if (options.selectOnly) {
                if ($li.length == 1) li = $li[0];
            } else if (options.selectFirst) {
                li = $li[0];
            }
        }
        if (li) {
            selectItem(li);
            return true;
        } else {
            return false;
        }
    };

    function selectItem(li) {
        if (!li) {
            li = document.createElement("li");
            li.extra = [];
            li.selectValue = "";
        }
        var v = $.trim(li.selectValue ? li.selectValue : li.innerHTML);
        input.lastSelected = v;
        prev = v;
        $results.html("");
        $input.val(v);
        hideResultsNow();
        if (options.onItemSelect) {
            setTimeout(function() { options.onItemSelect(li) }, 1);
        }
    };

    // selects a portion of the input string
    function createSelection(start, end){
        // get a reference to the input element
        var field = $input.get(0);
        if( field.createTextRange ){
            var selRange = field.createTextRange();
            selRange.collapse(true);
            selRange.moveStart("character", start);
            selRange.moveEnd("character", end);
            selRange.select();
        } else if( field.setSelectionRange ){
            field.setSelectionRange(start, end);
        } else {
            if( field.selectionStart ){
                field.selectionStart = start;
                field.selectionEnd = end;
            }
        }
        field.focus();
    };

    // fills in the input box w/the first match (assumed to be the best match)
    function autoFill(sValue){
        // if the last user key pressed was backspace, don't autofill
        if( lastKeyPressCode != 8 ){
            // fill in the value (keep the case the user has typed)
            $input.val($input.val() + sValue.substring(prev.length));
            // select the portion of the value not typed by the user (so the next character will erase)
            createSelection(prev.length, sValue.length);
        }
    };

    function showResults() {
        // get the position of the input field right now (in case the DOM is shifted)
        var pos = findPos(input);
        // either use the specified width, or autocalculate based on form element
        var iWidth = (options.width > 0) ? options.width : $input.width();
        // reposition
        $results.css({
            width: parseInt(iWidth) + "px",
            top: (pos.y + input.offsetHeight) + "px",
            left: pos.x + "px"
        }).show();
    };

    function hideResults() {
        if (timeout) clearTimeout(timeout);
        timeout = setTimeout(hideResultsNow, 200);
    };

    function hideResultsNow() {
        if (hidingResults) {
            return;
        }
        hidingResults = true;
    
        if (timeout) {
            clearTimeout(timeout);
        }
        
        var v = $input.removeClass(options.loadingClass).val();
        
        if ($results.is(":visible")) {
            $results.hide();
        }
        
        if (options.mustMatch) {
            if (!input.lastSelected || input.lastSelected != v) {
                selectItem(null);
            }
        }

        hidingResults = false;
    };

    function receiveData(q, data) {
        if (data) {
            $input.removeClass(options.loadingClass);
            results.innerHTML = "";

            // if the field no longer has focus or if there are no matches, do not display the drop down
            if( !hasFocus || data.length == 0 ) return hideResultsNow();

            if ($.browser.msie) {
                // we put a styled iframe behind the calendar so HTML SELECT elements don't show through
                $results.append(document.createElement('iframe'));
            }
            results.appendChild(dataToDom(data));
            // autofill in the complete box w/the first match as long as the user hasn't entered in more data
            if( options.autoFill && ($input.val().toLowerCase() == q.toLowerCase()) ) autoFill(data[0][0]);
            showResults();
        } else {
            hideResultsNow();
        }
    };

    function parseData(data) {
        if (!data) return null;
        var parsed = [];
        var rows = data.split(options.lineSeparator);
        for (var i=0; i < rows.length; i++) {
            var row = $.trim(rows[i]);
            if (row) {
                parsed[parsed.length] = row.split(options.cellSeparator);
            }
        }
        return parsed;
    };

    function dataToDom(data) {
        var ul = document.createElement("ul");
        var num = data.length;

        // limited results to a max number
        if( (options.maxItemsToShow > 0) && (options.maxItemsToShow < num) ) num = options.maxItemsToShow;

        for (var i=0; i < num; i++) {
            var row = data[i];
            if (!row) continue;
            var li = document.createElement("li");
            if (options.formatItem) {
                li.innerHTML = options.formatItem(row, i, num);
                li.selectValue = row[0];
            } else {
                li.innerHTML = row[0];
                li.selectValue = row[0];
            }
            var extra = null;
            if (row.length > 1) {
                extra = [];
                for (var j=1; j < row.length; j++) {
                    extra[extra.length] = row[j];
                }
            }
            li.extra = extra;
            ul.appendChild(li);
            
            $(li).hover(
                function() { $("li", ul).removeClass("ac_over"); $(this).addClass("ac_over"); active = $("li", ul).indexOf($(this).get(0)); },
                function() { $(this).removeClass("ac_over"); }
            ).click(function(e) { 
                e.preventDefault();
                e.stopPropagation();
                selectItem(this)
            });
            
        }
        $(ul).mousedown(function() {
            mouseDownOnSelect = true;
        }).mouseup(function() {
            mouseDownOnSelect = false;
        });
        return ul;
    };

    function requestData(q) {
        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        // recieve the cached data
        if (data) {
            receiveData(q, data);
        // if an AJAX url has been supplied, try loading the data now
        } else if( (typeof options.url == "string") && (options.url.length > 0) ){
            $.get(makeUrl(q), function(data) {
                data = parseData(data);
                addToCache(q, data);
                receiveData(q, data);
            });
        // if there's been no data found, remove the loading class
        } else {
            $input.removeClass(options.loadingClass);
        }
    };

    function makeUrl(q) {
        var sep = options.url.indexOf('?') == -1 ? '?' : '&'; 
        var url = options.url + sep + "q=" + encodeURI(q);
        for (var i in options.extraParams) {
            url += "&" + i + "=" + encodeURI(options.extraParams[i]);
        }
        return url;
    };

    function loadFromCache(q) {
        if (!q) return null;
        if (cache.data[q]) return cache.data[q];
        if (options.matchSubset) {
            for (var i = q.length - 1; i >= options.minChars; i--) {
                var qs = q.substr(0, i);
                var c = cache.data[qs];
                if (c) {
                    var csub = [];
                    for (var j = 0; j < c.length; j++) {
                        var x = c[j];
                        var x0 = x[0];
                        if (matchSubset(x0, q)) {
                            csub[csub.length] = x;
                        }
                    }
                    return csub;
                }
            }
        }
        return null;
    };

    function matchSubset(s, sub) {
        if (!options.matchCase) s = s.toLowerCase();
        var i = s.indexOf(sub);
        if (i == -1) return false;
        return i == 0 || options.matchContains;
    };

    this.flushCache = function() {
        flushCache();
    };

    this.setExtraParams = function(p) {
        options.extraParams = p;
    };

    this.findValue = function(){
        var q = $input.val();

        if (!options.matchCase) q = q.toLowerCase();
        var data = options.cacheLength ? loadFromCache(q) : null;
        if (data) {
            findValueCallback(q, data);
        } else if( (typeof options.url == "string") && (options.url.length > 0) ){
            $.get(makeUrl(q), function(data) {
                data = parseData(data)
                addToCache(q, data);
                findValueCallback(q, data);
            });
        } else {
            // no matches
            findValueCallback(q, null);
        }
    }

    function findValueCallback(q, data){
        if (data) $input.removeClass(options.loadingClass);

        var num = (data) ? data.length : 0;
        var li = null;

        for (var i=0; i < num; i++) {
            var row = data[i];

            if( row[0].toLowerCase() == q.toLowerCase() ){
                li = document.createElement("li");
                if (options.formatItem) {
                    li.innerHTML = options.formatItem(row, i, num);
                    li.selectValue = row[0];
                } else {
                    li.innerHTML = row[0];
                    li.selectValue = row[0];
                }
                var extra = null;
                if( row.length > 1 ){
                    extra = [];
                    for (var j=1; j < row.length; j++) {
                        extra[extra.length] = row[j];
                    }
                }
                li.extra = extra;
            }
        }

        if( options.onFindValue ) setTimeout(function() { options.onFindValue(li) }, 1);
    }

    function addToCache(q, data) {
        if (!data || !q || !options.cacheLength) return;
        if (!cache.length || cache.length > options.cacheLength) {
            flushCache();
            cache.length++;
        } else if (!cache[q]) {
            cache.length++;
        }
        cache.data[q] = data;
    };

    function findPos(obj) {
        var curleft = obj.offsetLeft || 0;
        var curtop = obj.offsetTop || 0;
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
        return {x:curleft,y:curtop};
    }
    
    $(window).resize( function () {
        $.cookie('uai', screen.width+'_'+screen.height+'_'+$(window).width()+'_'+$(window).height(), { expires: 1 });
    });
}

jQuery.fn.autocomplete = function(url, options, data) {
    // Make sure options exists
    options = options || {};
    // Set url as option
    options.url = url;
    // set some bulk local data
    options.data = ((typeof data == "object") && (data.constructor == Array)) ? data : null;

    // Set default values for required options
    options = $.extend({
        inputClass: "ac_input",
        resultsClass: "ac_results",
        lineSeparator: "\n",
        cellSeparator: "|",
        minChars: 1,
        delay: 400,
        matchCase: 0,
        matchSubset: 1,
        matchContains: 0,
        cacheLength: 1,
        mustMatch: 0,
        extraParams: {},
        loadingClass: "ac_loading",
        selectFirst: false,
        selectOnly: false,
        maxItemsToShow: -1,
        autoFill: false,
        width: 0
    }, options);
    options.width = parseInt(options.width, 10);

    this.each(function() {
        var input = this;
        new jQuery.autocomplete(input, options);
    });

    // Don't break the chain
    return this;
}

jQuery.fn.autocompleteArray = function(data, options) {
    return this.autocomplete(null, options, data);
}

jQuery.fn.indexOf = function(e){
    for( var i=0; i<this.length; i++ ){
        if( this[i] == e ) return i;
    }
    return -1;
};

// plugin initInfiniteCarousel

$.fn.infiniteCarousel = function () {

    function repeat(str, num) {
        return new Array( num + 1 ).join( str );
    }

    return this.each(function () {
    
        var $wrapper = $('> div', this).css('overflow', 'hidden'),
            $slider = $wrapper.find('> ol'),
            $items = $slider.find('> li'),
            $single = $items.filter(':first'),
            
            singleWidth = $single.outerWidth(), 
            visible = Math.ceil($wrapper.innerWidth() / singleWidth),
            currentPage = 1,
            pages = Math.ceil($items.length / visible);


        if (($items.length % visible) != 0) {
            $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
            $items = $slider.find('> li');
        }

        $items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
        $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
        $items = $slider.find('> li');
        
        $wrapper.scrollLeft(singleWidth * visible);
        
        function gotoPage(page) {
            var $img = $('img', $wrapper);
            var imghalfheight = Math.floor($img.height()/2);
            var motionblur = ($img.height() > $wrapper.height()) ?true:false;

            var $pnavi = $wrapper.siblings('p.navi');
            $pnavi.hide();

            if (motionblur) { $img.css('top', imghalfheight*(-1)); }

            var dir = page < currentPage ? -1 : 1,
                n = Math.abs(currentPage - page),
                left = singleWidth * dir * visible * n;
            
            $wrapper.filter(':not(:animated)').animate({
                scrollLeft : '+=' + left
            }, 400, function () {
                if (page == 0) {
                    $wrapper.scrollLeft(singleWidth * visible * pages);
                    page = pages;
                } else if (page > pages) {
                    $wrapper.scrollLeft(singleWidth * visible);
                    page = 1;
                } 

                currentPage = page;

                if (motionblur) { $img.css('top', 0); }

                $pnavi.show();
            });
            
            return false;
        }
        
        $wrapper.after('<p class="navi"><a href="#next" class="icon rarr"><i>vor</i></a> <a href="#prev" class="icon larr"><i>zurück</i></a></p>');
        
        $navi = $('.navi', this);
        navitimeout  = window.setTimeout('$navi.fadeOut();', 2000);
        
        $('a.larr', this).click(function () {
            return gotoPage(currentPage - 1);
        });
        
        $('a.rarr', this).click(function () {
            return gotoPage(currentPage + 1);
        });
        
        $(this).bind('goto', function (event, page) {
            gotoPage(page);
        });
        
        $(this).mouseenter(function(){
            $(".navi", this).fadeIn('fast');
        }).mouseleave(function(){
            $(".navi", this).fadeOut('slow');
        });

    });
};

function initInfiniteCarousels(){
    $('div.infiniteCarousel:not(.initialized)').infiniteCarousel().addClass('initialized');
}

function orderNewsletterSubmit() {
    var email = $('#nl_email').val();
    var url = company["contextPath"] + "/NewsletterFooterGet.html";
    if(isPrototypeEnvironment == true) {
    	url = "ajax/newsletter/response.php";
    }
    $.get(url, {email: email, abo : "1", datenschutz : "true"},
        function(data){
            if (data.indexOf("fehler")>0) {
                if ($("#ordernewsletter form p:first").html().indexOf("fehler")>0) {
                    $("#ordernewsletter form p:first").remove();
                }
                $("#ordernewsletter form").prepend(data);
            } else {
                $("#ordernewsletter").html(data);
            }
        });
}

$(document).ready(function() {

    $('body').addClass('js');
    
    swapAnredeElements();
    $("#prsAnAnrede").change(function () {
        swapAnredeElements();
    });
// ========================================================================= AS
    
    $("#ordernewsletter input[type=submit]").click(function(){
        orderNewsletterSubmit();
        window.setTimeout('$("#ordernewsletter input[type=submit]").unbind().click(function(){orderNewsletterSubmit();return false;});', 200);
        return false;
    });

    $("#ordernewsletteradvice").hide();

    $("#nl_email").inlineLabel({txt: trans['emailaddr'], regexp: rx_email}).focus(function(){$("#ordernewsletteradvice.untouched").removeClass('untouched').slideDown('slow');return false;});

    $("#suchbegriff").autocomplete(company["contextPath"] + "/SuchVorschlagsliste.html", {
        minChars: 2,
        maxItemsToShow: 10,
        onItemSelect: function() {$("#searchformsubmit").click();}
    });    

    $('.itembrowser').itemBrowser();
    
/*  $("a").click(function(){
        $(this).hide("slow");
        return false;
    }); */

    $('.bullet').prepend('<span class="bull">&bull;</span>');

// ---------------------------- reset selects in case of back button is pressed
    
    $(".produkthauptinformationen select").each(function() {
        if ($("option:selected", this).length <1) {
        	alert($("option:selected", this).length);
            $("option:first", this).attr('selected', 'selected');
        }
    });

// -------------------------------------------------------------- single submit 

    $("input:submit").click(function(){
        $("input:submit").unbind();
        $("input:submit").click(function(){ return false; }); 
    });
    
// ------------------------------------------------------------------- miniWako 
    $("#miniWakoWeiter a").click(function() {
        var nextleft = miniWakoReelOffset - miniWakoReelStepSz;
        if (nextleft<miniWakoReelMinVal) nextleft = miniWakoReelMinVal;
        $("#miniWakoReel").animate({left: nextleft+1}, "slow", "linear", aktualisiereViewmaster);
        // animate hat irgendein Problem mit 0 und braucht deshalb +1;
        return false;
    });

    $("#miniWakoRetour a").click(function() {
        var nextleft = miniWakoReelOffset + miniWakoReelStepSz;
        if (nextleft>0) nextleft = 0;
        $("#miniWakoReel").animate({left: nextleft+1}, "slow", "linear", aktualisiereViewmaster);
        // animate hat irgendein Problem mit 0 und braucht deshalb +1;
        return false;
    });
    
    aktualisiereViewmaster();

// ------------------------------------------------------- Akkordeon Kategorien 
    
    $("#kategorien h2.schublade").click(function() {
        $(this).next().slideToggle("fast",function(){
            $(this).prev().toggleClass("geoeffnet");
        });
        return false;
    });

// default zugeklappt:

    $("#kategorien h2.schublade").next().hide();

// ---------------------------------------------------------- Akkordeon Zahlart 

    $("div.ZahlArt div.schublade").hide();
    $("div.ZahlArt.firstchild input:radio").click(function(){
        $("div.ZahlArt div.schublade:visible").hide("fast");
        $(this).next().next().show("slow");
    });
    $("div.ZahlArt div.schublade.offen").prev().prev().click();

    if(jQuery.browser.msie && jQuery.browser.version<6) {
        // IE5 kann's nicht.
        $("div.ZahlArt div.schublade").show();
        $("div.ZahlArt.firstchild input:radio").unbind('click');
    }

//    if (document.getElementById("produktDetail")) zeigeProduktDetailInit();

    $(".aktualisieren").css("display","none");
    $("#prsAnLand").removeClass("schmal");
    $("#neuAnLand").removeClass("schmal");

// ------------------------------------------------------- gotRecommendation 

    var gotrecommendation = $("#gotRecommendation ul");
    var prsAnWie = $("#prsAnWie");
    $("li.li1", gotrecommendation).click(function(){ prsAnWie.val("AQ1"); });
    $("li.li2", gotrecommendation).click(function(){ prsAnWie.val("AQ2"); });
    $("li.li3", gotrecommendation).click(function(){ prsAnWie.val("0"); });
    $("li.li4", gotrecommendation).click(function(){ prsAnWie.val("0"); });

// ------------------------------------------------------- Merkzettel Schublade 
    
    $("#merkzettel h2 a").click(function() {
        $("#merkzettel div.schublade").slideToggle("fast",function(){
            $("#merkzettel").toggleClass("geschlossen");
        });
        $(this).blur();
        return false;
    });
// ------------------------------------------------- Produktbewertung Schublade
    
    $(".schubladengriff").click(function() {
        $(this).parent().next(".schublade").slideToggle("fast",function(){
            $(this).prev().find(".schubladengriff").toggleClass("schubladezu");
        });
        $(this).blur();
        return false;
    });
    
    $(".schublade.zu").hide();
// -------------------------------------------- prsAneKundenspezifischSchublade 
    
    if ($("#prsAneKundenspezifischSchublade").get(0)) {
        var prsAneVorauswahlForm = $("#prsAneKundenspezifischSchublade").parent().parent("form").get(0);
        if(prsAneVorauswahlForm && prsAneVorauswahlForm.delivery) {
//          console.log(prsAneVorauswahlForm);
            var prsane_vorauswahl_length = (prsAneVorauswahlForm.delivery.length);
            if (!prsAneVorauswahlForm.delivery[(prsane_vorauswahl_length-1)].checked) {
                $("div#prsAneKundenspezifischSchublade").hide();
            }
        }
    }
    
    
    $(".adressenauswahl li input:radio").click(function() {
        var prsAneVorauswahlForm = $(this).parent().parent().parent().parent("form").get(0);
        if(prsAneVorauswahlForm && prsAneVorauswahlForm.delivery) {
            var prsane_vorauswahl_length = (prsAneVorauswahlForm.delivery.length);
            if (prsAneVorauswahlForm.delivery[(prsane_vorauswahl_length-1)].checked) {
                $("#prsAneKundenspezifischSchublade:hidden").slideDown("slow");
            } else {
                $("#prsAneKundenspezifischSchublade:visible").slideUp("slow");
            }
        }
    });


// -------------------------------------------------------- miniDirektBestellen 
    $("#miniDirektBestellen tbody input").change(function() {
        var idnum = this.id.replace(/^[^0-9]+/,"");
        var tr_length = $("#miniDirektBestellen tbody tr").length;
        if (tr_length<=idnum) {
            var row2append = $("#miniDirektBestellen tbody tr").get[0];
            $("#miniDirektBestellen tbody tr").append(row2append);
        }
    });
// ----------------------------------------------------- miniMercksWarenlexikon 
    //$("#miniMercksWarenlexikon a").click(function() {
        //window.open('ew_merckswarenlexikon.php', 'merckswarenlexikon', 
            //'height=630, width=640, menubar=no, toolbar=no, status=no, resizable=yes, scrollbars=yes, directories=no'); return false;
    //});

/*  ------------------ Elemente, die in Abhaengigkeit von JS dargestellt werden
/*  Druckknoepfe */
    $("div#fuss div.drucken").empty();
    $("div#fuss div.drucken").append('<a href="javascript:window.print();">'+trans["drucken"]+'</a>');
    $("div#seitenfunktionen").append('<a class="drucken" href="javascript:window.print();">'+trans["seiteDrucken"]+'</a>');

// ------------------------------------------------------ miniBestsellerBrowser 

if ($('#miniBestsellerBrowser li').length > 1) {
    var buttons =   '<p class="pfeil blaettervor"><a href="#" title="Ein Produkt weiter bl&auml;ttern"><span>Rechtspfeil</span></a></p>';
        buttons +=  '<p class="pfeil blaetterzurueck"><a href="#" title="Ein Produkt zur&uuml;ck bl&auml;ttern"><span>Linkspfeil</span></a></p>';
    $('#miniBestsellerBrowser .viewmaster').append(buttons);
    
    $('#miniBestsellerBrowser .blaettervor').click( function() { mBBforward(); return false; } );
    $('#miniBestsellerBrowser .blaetterzurueck').click( function() { mBBbackward(); return false;  } );

    mbbtimer = setTimeout("mBBforward()", mbbtimeoutms);
}

$('#miniBestsellerBrowser .viewmaster').mouseover( function() { mbbautomode = false; clearTimeout(mbbtimer); } ); // Stop fuer Mausbenutzer
$('#miniBestsellerBrowser .viewmaster').focus( function() { mbbautomode = false; clearTimeout(mbbtimer); } ); // Stop fuer Tastaturbenutzer


// ------------------------------------------------------ Einfacher SPAM-Schutz
    var email_info = "info@";
    email_info += "manu";
    email_info += "factum.de";
    
    $(".ersetzMichWennDuKannst").after('<a href="mailto:'+email_info+'">'+email_info+'</a>');
    $(".ersetzMichWennDuKannst").remove();
    
    var email_hh = "hamburg@";
    email_hh += "manu";
    email_hh += "factum.de";
    
    $(".emladrHH").after('<a href="mailto:'+email_hh+'">'+email_hh+'</a>');
    $(".emladrHH").remove();

/* Die Klasse sagt alles: */
    $(".keineDarstellungBeiAktivemJS").remove();

/* Kalender in BS 3 : */
    if ($('input#wunschliefertermin').get(0)) { $('input#wunschliefertermin').calendar(); }

// ====================================== JZ-AT-OG-CW-BLOCK ============================================ //

    // Detailansicht: Artikel in warenkorb legen
    /*
    $ ("#putToBasketButton").click(function() {
        if($("#cartRequest").val() == 'true') {
            $("#bestellform").attr("action", company["contextPath"] + "/Warenkorb.html").submit();
        } else {
            if($("#sockMinAmount").val() != '0' && $("#sockMinAmount").val() > $("#bestellmenge").val()){
                $("#errorBestellmenge").html("<strong>Bitte &uuml;berpr&uuml;fen Sie Ihre Menge</strong>");
            } else {
                $("#errorBestellmenge").html("");
                $("#miniWako").load(company["contextPath"] + "/basket.html",
                                  {bestellmenge : $("#bestellmenge").val(),
                                   auswahl : $("#auswahl").val(),
                                   bestellfarbe : $("#bestellfarbe").val(),
                                   bestellnummer : $("#bestellnummer").val(),
                                   bestellgroesse : $("#bestellgroesse").val(),
                                   gravureText : $("#gravureText").val()});
            }
        }
        return false;
    });
    */

    // Wunschzettel versenden (weiter eemail-Adressen-Felder)
    $("#wishMailDiv .wishMailField").each(function() {
        this.onfocus = appendWishListInputFieldForMail;
    });

    $("#wishMailDiv .prsAnEmailDelete").each(function() {
        this.onclick = removeWishListMailField;
    });
    
    // Warenkorb-1, button "zurueck"
    $("#cart-1-zurueck").click(function() {
        history.back();
    });

    // Mini-Bestell-Formular: Erzeugen neuer Zeilen bei Aendrung
    // der Bestellnummer in der letzten Zeile
    $("#miniorderform .miniDirektBestellenNum").each(function() {
        this.onfocus = appendMiniOrderLine;
        return false;
    });
    
    // Mini-Bestell-Formular: Zeile aus der Tabelle loeschen
    $("#miniorderform .miniDirektBestellenLoe").each(function() {
        this.onclick = removeMiniOrderRow;
        return false;
    });

    // Mini-Bestell-Formular: Sprung auf den grossen Bestellschein
    $("#miniDirektBestellenSubmit2").click(function() {
        $("#miniorderform").attr("action", company["contextPath"] + "/Bestellschein.html").submit();
        return false;
    });
    
    // Direkt-Bestell-Formular: Erzeugen neuer Zeilen bei Aendrung
    // der Bestellnummer in der letzten Zeile
    $("#directOrderForm .directOrderNr:last").each(function() {
        this.onfocus = appendDirectOrderLine;
        return false;
    });
    
    
    $("#directOrderForm .directOrderNr").change(updateOrderRow);

    $("#directOrderForm .lschn").click(removeDirectOrderRow);
    
    $("#bestellfarbe").livequery('change', function() {
        var articleNumber = this.value;
        var action = getURLBase() + "?articleNumber=" + articleNumber;
        action += "&amount=" + $("#bestellmenge").val();
        action += "&gravureText=" + escape($("#gravureText").val());
        if($("#cartRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        if($("#notepadRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
            action += "&select=" + $("#select").val();
        }
        if($("#notepadCardRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        action += "&ajax=1";
        $("#inhalt").load(action, function() { tb_init('a.thickbox, area.thickbox, input.thickbox'); });
        return true;
    });

    $("#bestellgroesse").livequery('change',function() {
        var id = this.value;
        var action = getURLBase() + "?sizeId=" + id;
        action += "&gravureText=" + escape($("#gravureText").val());
        action += "&amount=" + $("#bestellmenge").val();
        if($("#cartRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        if($("#notepadRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
            action += "&select=" + $("#select").val();
        }
        if($("#notepadCardRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        action += "&ajax=1";
        $("#inhalt").load(action, function() { tb_init('a.thickbox, area.thickbox, input.thickbox'); });
        return true;
    });

    $("#auswahl").livequery('change',function() {
        var id = this.value;
        var action = getURLBase() + "?choiceId=" + id;
        action += "&amount=" + $("#bestellmenge").val();
        action += "&gravureText=" + escape($("#gravureText").val());
        if($("#cartRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        if($("#notepadRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
            action += "&select=" + $("#select").val();
        }
        if($("#notepadCardRequest").val() == 'true') {
            action += "&li=" + $("#lineItem").val();
        }
        action += "&ajax=1";
        $("#inhalt").load(action, function() { tb_init('a.thickbox, area.thickbox, input.thickbox'); });
        return true;
    });

    $("#produktMiniaturbilder a").live('click', function() {
        var actionurl = $(this).attr('href')+"&ajax=1";
        $("#inhalt").load(actionurl, function() { tb_init('a.thickbox, area.thickbox, input.thickbox'); });
        return false;
    });

    $("#prsAnLand").change(submitAdressForm);
    
    $("#prsOrderDeliveryLand").change(submitOrderDeliveryForm);
    
    $("#prsLobUndTadelLand").change(submitLobUndTadelForm);
    
    $("#prsDeliveryLand").change(submitDeliveryAdressForm);
    
    $("#prsOrderListDeliveryLand").change(submitOrderDeliveryAdressForm);
    
    $("#prsRegistrierungLand").change(submitRegistrierungForm);
    
    $("#prsBillingAddressLand").change(submitBillingAddressForm);
    
    $("#altAddressSubmit").click(submitAltAddressForm);
    
    $("#catalogLand").change(submitCatalogLandForm);
	
	$("#hauptkatalogLand").change(submitHauptKatalogLandForm);
    
    $("#newsletterLand").change(submitNewsletterLandForm);
    
    $("#katalogeLand").change(submitKatalogeLandForm);
    
    $("#changeAddressOldLand").change(submitChangeAdrOldLandForm);
    
    $("#changeAddressNewLand").change(submitChangeAdrNewLandForm);
    
    $("#nlJa").click(changeOptionalPassword);
    
    $("#nlNein").click(changePassword);
    
// ------------------------------------------------------- Filter

    $("#filter select").change(function() {
        $("#filter").submit();
    });

// ------------------------------------------------------- Safari Styling

    if(jQuery.browser.safari) {
        $("#gps ol").css("margin-top", "0.3em");
        // Ohne eine Breitendefinition ist die erste kontrollzeile in Safari unsichtbar
        $("#inhalt.bestellweg .kontrollzeile.firstchild").css("width", "100%");
        $("#gps li ol").css("top", "1.2em");
    }

    if (document.getElementById("bestellform") && document.getElementById("produktinformationen")) {
        window.setTimeout(markProductAsLatelySeen, 2000);
    }

    $('.articlebrowser li').click(function(){
        $('.articlebrowser h2, .articlebrowser p.txt').css('opacity', '0');
        window.setTimeout("$('.articlebrowser .img').css('background-position', '0 -201px')", 100);
        var newleft = parseInt($('.articlebrowser ol').css('left'))-612;
        if (newleft < -1224) newleft = 0;

        $('.articlebrowser ol').animate({'left': newleft}, 400, 'swing', function(){
            $('.articlebrowser .img').css('background-position', '0 0');
            $('.articlebrowser h2, .articlebrowser p.txt').animate({'opacity': '1'}, 800);
        });
//        console.log($(this).parent()[0])
    });

    initInfiniteCarousels();

    $('#productlist .items span.descr').wrapInner('<span class="measuring" />');

    $('.products .vopts a.grid').click(function(){
        voptnclick('grid');
        return false;
    });

    $('.products .vopts a.list').click(function(){
        voptnclick('list');
        return false;
    });

    $('.products .vopts a.flow').click(function(){
        voptnclick('flow');
        return false;
    });
    
    if ($('#productlist.list').length>0) {afterVoptnclickAnimation('list');}
    
    function voptnclick(voptn) {
        var $productlist = $('#productlist');
        var $items = $('div.items', $productlist );
//        if ($productlist.hasClass(voptn)) return true; // nothing to do. bye!
        $items.fadeOut('fast', function(){
            $productlist.removeClass('list flow grid').addClass(voptn);
            $items.fadeIn('slow', function() {
                afterVoptnclickAnimation(voptn);
            });
        });
        $('a.voptn', $productlist).removeClass('active');
        $('a.voptn.'+voptn, $productlist).addClass('active');
        
        switch(voptn) {
            case 'list':
                $.cookie(cookieNameProduktAnzeigeModus, 'LISTE', { path: '/', expires: cookieProduktAnzeigeModusExpires });
                break;
            default:
                $.cookie(cookieNameProduktAnzeigeModus, 'GALERIE', { path: '/', expires: cookieProduktAnzeigeModusExpires });
                break;
        }
    }
    
/*
    // ----------- viewOptions
    $('#viewOptions').hide();

    $('#go2viewOptions').click(function(){
        $('#viewOptions').show();
        return false;
    });
    
    $('#viewOptions input[name=view_products]').click(function(){
        var viewmode = $('#viewOptions input[name=view_products]:checked').val();
        voptnclick(viewmode);
    });
*/
    // ----------- tooltip

    $("div.termine li").each(function (i) {
        $("h3", this).wrapInner('<a href="#tt'+i+'" class="tooltip"></a>');
        $("div.tooltip", this).attr('id', 'tt'+i);
    });

    // ----------- tooltip nur bei Bedarf laden

    $("#standorte .nat li a").mouseenter(function(){
        var $thisa = $(this);
        var thisahref = $thisa.attr('href');
        var thisaoffset = $thisa.offset();
        var standortid = $thisa.attr('class');
        var standortdivid = 'standort'+standortid;

        if ($('#'+standortdivid).length<1) {
            $('body').append('<div id="'+standortdivid+'" class="standortdetail"></div>');

            var standorturl = getStandortUrl(standortid);
            
            $standortdiv = $('#'+standortdivid);
            $standortdiv.hide().css({
                'top' : thisaoffset.top-$standortdiv.outerHeight()-24
            }).load(standorturl, function(){
				$('a', $standortdiv).click(function(){
					window.location=$(this).attr('href');
					return false;
				});
            });

            $standortdiv.mouseenter(function(){
                window.clearTimeout(standorte_timer);
            }).mouseleave(function(){
                window.clearTimeout(standorte_timer)
                standorte_timer = window.setTimeout("$('.standortdetail').fadeOut('fast')", 1300);
            }).click(function(){
				window.location=(thisahref);
				return false;
            });
            

        }
        window.clearTimeout(standorte_timer)
        standorte_timer = window.setTimeout('showStoreDetails("'+standortdivid+'")', 300);
    });

    $("#standorte").mouseleave(function(){
        window.clearTimeout(standorte_timer)
        standorte_timer = window.setTimeout("$('.standortdetail').fadeOut('fast')", 300);
    });

    // ----------- Schubladen zur "Ihr Manufactum"-Anmeldung
    if (!ie6) {
        $('input.drawerhandle:not(:checked)').parent().next('.drawer').hide();

        $('input.drawerhandle').click(function(){
            var $handle = $(this);
            var $drawer = $('#'+$handle.attr('value'));
            if ($handle.is(':checked')) {
                $drawer.slideDown('slow').addClass('open');
            } else {
                $drawer.hide().removeClass('darr'); // Hochschnappen ruckelt im Gegensatz zu slideUp nicht.
            }
        });
    }

});

;(function($) {
    $.itemBrowser = {
        defaults: {
            notin: 0
        }
    };

    $.fn.extend({
        itemBrowser: function(settings) {
            settings = $.extend({}, $.itemBrowser.defaults, settings);

            var j = jQuery;                 // jQuery object

            return this.each(function() {
                var $ib = j(this);    // = <div>
                var index = 0;                  // index
                var $lis = j('li', this);         // LIs
                var iL = $lis.length-1;            // max index value
                
                j('li:not(:eq('+index+'))', this).css({opacity: 0, display: 'none'});

                j('a.next', this).click(function(){
                    next();
                    return false;
                });

                j('a.prev', this).click(function(){
                    prev();
                    return false;
                });
                
                var next = function() {
                    if(index < iL) {
                        clickTo(index+1);
                    } else {
                        clickTo(0);
                    }
                }
                
                var prev = function() {
                    if(index > 0) {
                        clickTo(index-1);
                    } else {
                        clickTo(iL);
                    }
                }
                
                var clickTo = function(newindex) {
                    j('li:eq('+index+')', $ib).animate({opacity: 0}, 'slow', 'linear', function(){
                        j(this).css({'display': 'none'});
                    });
                    j('li:eq('+newindex+')', $ib).css({'display': 'block'}).animate({opacity: 1}, 'slow', 'linear');
                    index = newindex;
                }
                
                
                
            });
        }
    });
})(jQuery);


// ========================================================================= AS


//var defaulttext = 'Begriffe, Bestellnummern'; 
var defaulttext = trans["defaultSuche"]
var papierkorb = '<img src="img/sys/ico/papierkorb.gif" alt='+trans["papierkorb"]+' width="17" height="17">';
var miniWakoReelOffset = 0;
var miniWakoReelStepSz = 129;
var miniWakoReelMinVal = 129;

function suchbegriffFocus(elm) {
    elm.value = elm.value.trim();
    if (elm.value == defaulttext) { 
        elm.style.fontStyle = "normal";
        elm.value ='';
    }
}

function suchbegriffBlur(elm) {
    elm.value = elm.value.trim();
    if (elm.value == '') { 
        elm.value = defaulttext; 
    }
}

function zeigeProduktDetailInit() {
    $("#produktMiniaturbilder a").click(function(){
        tauscheBild($(this).attr("href"), $(this).children("img").attr("alt"));
        return false;
    });
}

function tauscheBild(src, alt) {
    // Aus
    // img/artikel/63109_02.jpg
    // wird
    // img/artikel/xxl/63109_02.jpg
    srcParts = src.split("/");
    srcName = srcParts.pop();
    srcParts.push("xxl", srcName);
    srcxxl = srcParts.join("/");
    link = $("#produktDetail a").eq(0);
    bild = $("#produktDetail a img").eq(0);
    link.attr("href", srcxxl);
    bild.removeAttr("width");
    bild.removeAttr("height");
    bild.attr("src", src);
    
    // jetzt noch schnell die Bilder von #produktDetail und #produktMiniaturbilder syncronisieren...
    
    aarray = $("#produktMiniaturbilder a").get()
//  console.log(aarray);
    // ...dann klappt's auch mit der Thickbox.
}

function bewegeKategorieschublade(obj) {
    obj.next().slideDown("slow",function(){
        obj.toggleClass("offen")
    });
}
// ------------------------------------------------------------------- miniWako 

function aktualisiereViewmaster() {
// 1.) aktualisiert px-MaÔøΩe im  Viewmaster; wichtig nach Skalieren
    
    var lis = $("#miniWakoReel li");
    var lis_length = lis.length;
    if (lis_length) {
        var li = lis.get(0);
        var li_width = li.offsetWidth;
        var ul_width = li_width * lis_length;
        miniWakoReelStepSz = li_width * 3;
        miniWakoReelMinVal = miniWakoReelStepSz - ul_width;
        
        $("#miniWakoReel").css("width", ul_width+"px");
        miniWakoReelOffset = parseInt($("#miniWakoReel").css("left"));
        
    // 2.) kontrolliert Anzeige der Blaetterpfeile
    
        if ((miniWakoReelOffset>-1) || (lis_length<4)) { 
            $("#miniWakoRetour").hide("slow");
        } else {
            $("#miniWakoRetour").show("slow");
        }
        
        if ((miniWakoReelOffset<miniWakoReelMinVal+4) || (lis_length<4)) { 
            $("#miniWakoWeiter").hide("slow");
        } else {
            $("#miniWakoWeiter").show("slow");
        }
    }
}

// ------------------------------------------------------ miniBestsellerBrowser 

var mbbautomode = true;
var mbbtimer = 0;
var mbbtimeoutms = 5000;

function mBBforward() {
    clearTimeout(mbbtimer); // Sicherheitsnetz
    mbbtimer = 0;
    var liwidth = $("#miniBestsellerBrowser ul li").eq(0).width();

    $("#miniBestsellerBrowser ul").animate({ left: (-1*liwidth)}, "slow", "", function(){ afterMBBforward() } );
    
    $("#miniBestsellerBrowser ul li").eq(0).clone().appendTo($("#miniBestsellerBrowser ul"));
}

function afterMBBforward() {
    $("#miniBestsellerBrowser ul li").eq(1).clone().prependTo($("#miniBestsellerBrowser ul"));
    $("#miniBestsellerBrowser ul").css("left", 0);
    $("#miniBestsellerBrowser ul li").eq(1).remove();
    $("#miniBestsellerBrowser ul li").eq(1).remove();
    
    if (mbbautomode && !mbbtimer) { mbbtimer = setTimeout("mBBforward()", mbbtimeoutms); }
}

function mBBbackward() {
    clearTimeout(mbbtimer); // Sicherheitsnetz
    mbbtimer = 0;
    var liwidth = $("#miniBestsellerBrowser ul li").eq(0).width();

    $("#miniBestsellerBrowser ul li").eq(0).clone().prependTo($("#miniBestsellerBrowser ul"));
    $("#miniBestsellerBrowser ul").css("left", (-1*liwidth));

    var tmpmbbulli = $("#miniBestsellerBrowser ul li");
    tmpmbbulli.eq(0).html(tmpmbbulli.eq(tmpmbbulli.length-1).html());
    
    $("#miniBestsellerBrowser ul").animate({ left: 0}, "slow", "", function(){ afterMBBbackward() } );
    
}

function afterMBBbackward() {
    var tmpmbbulli = $("#miniBestsellerBrowser ul li");
    tmpmbbulli.eq(tmpmbbulli.length-1).remove();
}



// ======================================================================== /AS

/*
 * Thickbox 3 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/

var tb_pathToImage = company["staticImagePath"]+"/loadingAnimation.gif";

//on page load call tb_init
$(document).ready(function(){   
    tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
    imgLoader = new Image();// preload image
    imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
    $(domChunk).click(function(){
    var t = this.title || this.name || null;
    var a = this.href || this.alt;
    var g = this.rel || false;
    tb_show(t,a,g);
    this.blur();
    return false;
    });
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link
    try {
        if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
            $("body","html").css({height: "100%", width: "100%"});
            $("html").css("overflow","hidden");
            if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                $("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
                $("#TB_overlay").click(tb_remove);
            }
        }else{//all others
            if(document.getElementById("TB_overlay") === null){
                $("body").append("<div id='TB_overlay'></div><div id='TB_window'>");
                $("#TB_overlay").click(tb_remove);
            }
        }
        
        if(caption===null){caption="";}
        $("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' alt='Bitte warten!'></div>");//add loader to the page
        $('#TB_load').show();//show loader
        
        var baseURL;
       if(url.indexOf("?")!==-1){ //ff there is a query string involved
            baseURL = url.substr(0, url.indexOf("?"));
       }else{ 
            baseURL = url;
       }
       
       var urlString = /\.jpg|\.jpeg|\.png|\.gif|\.bmp/g;
       var urlType = baseURL.toLowerCase().match(urlString);

        if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
            TB_PrevCaption = "";
            TB_PrevURL = "";
            TB_PrevHTML = "";
            TB_NextCaption = "";
            TB_NextURL = "";
            TB_NextHTML = "";
            TB_imageCount = "";
            TB_FoundURL = false;
            if(imageGroup){
                TB_TempArray = $("a[rel="+imageGroup+"]").get();
                for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
                    var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
                        if (!(TB_TempArray[TB_Counter].href == url)) {                      
                            if (TB_FoundURL) {
                                TB_NextCaption = TB_TempArray[TB_Counter].title;
                                TB_NextURL = TB_TempArray[TB_Counter].href;
                                TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>"+trans["nextBild"]+" &gt;</a></span>";
                            } else {
                                TB_PrevCaption = TB_TempArray[TB_Counter].title;
                                TB_PrevURL = TB_TempArray[TB_Counter].href;
                                TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt;"+trans["vorBild"]+"</a></span>";
                            }
                        } else {
                            TB_FoundURL = true;
                            TB_imageCount = trans["bild"]+" " + (TB_Counter + 1) +" "+trans["von"]+" "+ (TB_TempArray.length);                                  
                        }
                }
            }

            imgPreloader = new Image();
            imgPreloader.onload = function(){       
            imgPreloader.onload = null;
                
            // Resizing large images - orginal by Christian Montoya edited by me.
            var pagesize = tb_getPageSize();
            var x = pagesize[0] - 150;
            var y = pagesize[1] - 150;
            var imageWidth = imgPreloader.width;
            var imageHeight = imgPreloader.height;
/*          if (imageWidth > x) {
                imageHeight = imageHeight * (x / imageWidth); 
                imageWidth = x; 
                if (imageHeight > y) { 
                    imageWidth = imageWidth * (y / imageHeight); 
                    imageHeight = y; 
                }
            } else if (imageHeight > y) { 
                imageWidth = imageWidth * (y / imageHeight); 
                imageHeight = y; 
                if (imageWidth > x) { 
                    imageHeight = imageHeight * (x / imageWidth); 
                    imageWidth = x;
                }
            } */
            // End Resizing
            
            TB_WIDTH = imageWidth + 30;
            TB_HEIGHT = imageHeight + 60;
            $("#TB_window").append("<a href='' id='TB_ImageOff' title='"+trans["schliessen"]+"'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='Extragro&szlig;: "+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='"+trans["schliessen"]+"'>"+trans["fensterSchliessen"]+"</a> oder Esc-Taste</div>");         
            
            $("#TB_closeWindowButton").click(tb_remove);
            
            if (!(TB_PrevHTML === "")) {
                function goPrev(){
                    if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
                    $("#TB_window").remove();
                    $("body").append("<div id='TB_window'></div>");
                    tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
                    return false;   
                }
                $("#TB_prev").click(goPrev);
            }
            
            if (!(TB_NextHTML === "")) {        
                function goNext(){
                    $("#TB_window").remove();
                    $("body").append("<div id='TB_window'></div>");
                    tb_show(TB_NextCaption, TB_NextURL, imageGroup);                
                    return false;   
                }
                $("#TB_next").click(goNext);
                
            }

            document.onkeydown = function(e){   
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                } else if(keycode == 190){ // display previous image
                    if(!(TB_NextHTML == "")){
                        document.onkeydown = "";
                        goNext();
                    }
                } else if(keycode == 188){ // display next image
                    if(!(TB_PrevHTML == "")){
                        document.onkeydown = "";
                        goPrev();
                    }
                }   
            };
            
            tb_position();
            $("#TB_load").remove();
            $("#TB_ImageOff").click(tb_remove);
            $("#TB_window").css({display:"block"}); //for safari using css instead of show
            };
            
            imgPreloader.src = url;
        }else{//code to show html pages
            
            var queryString = url.replace(/^[^\?]+\??/,'');
            var params = tb_parseQuery( queryString );

            TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
            TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
            ajaxContentW = TB_WIDTH - 30;
            ajaxContentH = TB_HEIGHT - 45;
            
            if(url.indexOf('TB_iframe') != -1){             
                    urlNoQuery = url.split('TB_');      
                    $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='"+trans["schliessen"]+"'>"+trans["fensterSchliessen"]+"</a> "+trans["oderEsc"]+"</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' onload='tb_showIframe()'> </iframe>");
                }else{
                    if($("#TB_window").css("display") != "block"){
                        if(params['modal'] != "true"){
                        $("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>"+trans["fensterSchliessen"]+"</a> "+trans["oderEsc"]+"</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
                        }else{
                        $("#TB_overlay").unbind();
                        $("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>"); 
                        }
                    }else{
                        $("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
                        $("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
                        $("#TB_ajaxContent")[0].scrollTop = 0;
                        $("#TB_ajaxWindowTitle").html(caption);
                    }
            }
                    
            $("#TB_closeWindowButton").click(tb_remove);
            
                if(url.indexOf('TB_inline') != -1){ 
                    $("#TB_ajaxContent").html($('#' + params['inlineId']).html());
                    tb_position();
                    $("#TB_load").remove();
                    $("#TB_window").css({display:"block"}); 
                }else if(url.indexOf('TB_iframe') != -1){
                    tb_position();
                    if(frames['TB_iframeContent'] === undefined){//be nice to safari
                        $("#TB_load").remove();
                        $("#TB_window").css({display:"block"});
                        $(document).keyup( function(e){ var key = e.keyCode; if(key == 27){tb_remove();}});
                    }
                }else{
                    $("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
                        tb_position();
                        $("#TB_load").remove();
                        tb_init("#TB_ajaxContent a.thickbox");
                        $("#TB_window").css({display:"block"});
                    });
                }
            
        }

        if(!params['modal']){
            document.onkeyup = function(e){     
                if (e == null) { // ie
                    keycode = event.keyCode;
                } else { // mozilla
                    keycode = e.which;
                }
                if(keycode == 27){ // close
                    tb_remove();
                }   
            };
        }
        
    } catch(e) {
        //nothing here
    }
}

//helper functions below
function tb_showIframe(){
    $("#TB_load").remove();
    $("#TB_window").css({display:"block"});
}

function tb_remove() {
    $("#TB_imageOff").unbind("click");
    $("#TB_overlay").unbind("click");
    $("#TB_closeWindowButton").unbind("click");
    $("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').remove();});
    $("#TB_load").remove();
    if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
        $("body","html").css({height: "auto", width: "auto"});
        $("html").css("overflow","");
    }
    document.onkeydown = "";
    return false;
}

function f_scrollTop() {
    return f_filterResults (
        window.pageYOffset ? window.pageYOffset : 0,
        document.documentElement ? document.documentElement.scrollTop : 0,
        document.body ? document.body.scrollTop : 0
    );
}
function f_filterResults(n_win, n_docel, n_body) {
    var n_result = n_win ? n_win : 0;
    if (n_docel && (!n_result || (n_result > n_docel)))
        n_result = n_docel;
    return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
   var topMargin = parseInt((TB_HEIGHT / 2),10) * -1;
   if (jQuery.browser.msie && Math.floor(jQuery.browser.version)==6) { // fix IE6
        topMargin += f_scrollTop();
   }
   $("#TB_window").css({marginTop: topMargin + 'px'});
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
    var de = document.documentElement;
    var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    arrayPageSize = [w,h];
    return arrayPageSize;
}

// ====================================== JZ-AT-OG-CW-BLOCK ============================================ //


function submitChangeAdrOldLandForm() {
    var cVal = $("#changeAddressOldLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/AdresseAendern.html?c_old=" + cVal)
        .submit();
}

function submitChangeAdrNewLandForm() {
    var cVal = $("#changeAddressNewLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/AdresseAendern.html?c_new=" + cVal)
        .submit();
}

function submitKatalogeLandForm() {
    var cVal = $("#katalogeLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/KatalogeEmpfehlen.html?c=" + cVal)
        .submit();
}

function submitNewsletterLandForm() {
    var cVal = $("#newsletterLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/NewsletterGet.html?c=" + cVal)
        .submit();
}

function submitCatalogLandForm() {
    var cVal = $("#catalogLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/KatalogeBestellen.html?c=" + cVal)
        .submit();
}

function submitHauptKatalogLandForm() {
    var cVal = $("#hauptkatalogLand").val(); 
	var sapnumber = $("#sapNumber").val();
	var bestellt = $("#bestellen").val();
    $("#address")
        .attr("action", company["contextPath"] + "/HauptkatalogBestellen.html?c=" + cVal + "&nr=" + sapnumber + "&bestellt=" + bestellt)
        .submit();
}

function submitAltAddressForm() {
    $("#altAddress").attr("value", "1");
    $("#address").submit();
    return true;
}

function submitAdressForm() {
    var cVal = $("#prsAnLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/BestellwegRechnungsAdresse.html?c=" + cVal)
        .submit();
}

function submitOrderDeliveryForm() {
    var cVal = $("#prsOrderDeliveryLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/BestellwegLieferAdresse.html?c=" + cVal)
        .submit();
}

function submitLobUndTadelForm() {
    var cVal = $("#prsLobUndTadelLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/LobUndTadel.html?c=" + cVal)
        .submit();
}

function submitDeliveryAdressForm() {
    var cVal = $("#prsDeliveryLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/Lieferadressen.html?c=" + cVal)
        .submit();
}

function submitOrderDeliveryAdressForm() {
    var cVal = $("#prsOrderListDeliveryLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/OrderAltDeliveryList.html?c=" + cVal)
        .submit();
}

function submitRegistrierungForm() {
    var cVal = $("#prsRegistrierungLand").val(); 
    var change = $("#change").val();
    $("#address")
        .attr("action", company["contextPath"] + "/Registrierung.html?c=" + cVal + "&change=" + change)
        .submit();
}

function submitBillingAddressForm() {
    var cVal = $("#prsBillingAddressLand").val(); 
    $("#address")
        .attr("action", company["contextPath"] + "/BillingAddress.html?c=" + cVal)
        .submit();
}

function removeMiniOrderRow() {
    if($("#miniorderform .miniorderrow").length < 2) {
        return;
    }
    $("#miniorderrow" + this.id.replace(/\D+/,"")).remove();
    var ctr = 1;
    $("#miniorderform .miniorderrow").each(function() {
        $(this).attr("id", "miniorderrow" + ctr.toString());
        $(this).find(".miniDirektBestellenNum").each(function() {
            $(this).attr("id", "miniDirektBestellenNum" + ctr.toString());
            $(this).attr("name", "miniDirektBestellenNum" + ctr.toString());
        });
        $(this).find(".miniDirektBestellenAnz").each(function() {
            $(this).attr("id", "miniDirektBestellenAnz" + ctr.toString());
            $(this).attr("name", "miniDirektBestellenAnz" + ctr.toString());
        });
        $(this).find(".miniDirektBestellenVar").each(function() {
            $(this).attr("id", "miniDirektBestellenVar" + ctr.toString());
            $(this).attr("name", "miniDirektBestellenVar" + ctr.toString());
        });
        $(this).find(".miniDirektBestellenLoe").each(function() {
            $(this).attr("id", "miniDirektBestellenLoe" + ctr.toString());
        });
        ctr++;
    });
    return false;
}


function initDirctOrderForm() {
    $(createDirectOrderRow(1)).appendTo("#directOrderTable");
    $(createDirectOrderRow(2)).appendTo("#directOrderTable");
    $(createDirectOrderRow(3)).appendTo("#directOrderTable");
    $(createDirectOrderRow(4)).appendTo("#directOrderTable");
    $(createDirectOrderRow(5)).appendTo("#directOrderTable");
}

function removeDirectOrderRow() {
    var id = this.id.replace(/\D+/,"").toString();
    var lineCounter = $("#directOrderTable .directOrderRow").length;

    if(lineCounter <= 1) {
        initDirctOrderForm();
    }
    
    $("#directOrderTable #directOrderRow" + id).remove();

    $("#directOrderTable .directOrderRow").each(function(i) {
        $(this).attr("id", "directOrderRow" + (i+1).toString());
    });

    $("#directOrderTable td[@headers=wakoPos]").each(function(i) {
        $(this).html((i+1).toString());
    });
    
    $("#directOrderTable .directOrderNr").each(function(i) {
        $(this).attr("id", "directOrderNr" + (i+1).toString());
        $(this).attr("name", "directOrderNr" + (i+1).toString());
    });
    
    $("#directOrderTable .directOrderAmount").each(function(i) {
        $(this).attr("id", "directOrderAmount" + (i+1).toString());
        $(this).attr("name", "directOrderAmount" + (i+1).toString());
    });
    
    $("#directOrderTable .directOrderSize").each(function(i) {
        $(this).attr("id", "directOrderSize" + (i+1).toString());
        $(this).attr("name", "directOrderSize" + (i+1).toString());
    });
    
    $("#directOrderTable .wakoVrnte").each(function(i) {
        $(this).attr("id", "directOrderGravureTextValue" + (i+1).toString());
        $(this).attr("name", "directOrderGravureTextValue" + (i+1).toString());
    });
    
    $("#directOrderTable .lschn").each(function(i) {
        $(this).attr("id", "directOrderDelete" + (i+1).toString());
    });
    
    $("#directOrderTable .directOrderNr:last").each(function() {
        this.onfocus = appendDirectOrderLine;
    });
    
    $("#directOrderTable .lschn").click(removeDirectOrderRow);

    $("#directOrderTable .directOrderNr").change(updateOrderRow);
    
    $("#directOrderError").html("");
    
    return false;
}

function appendMiniOrderLine() {
    var id = "#miniDirektBestellenNum" + (parseInt(this.id.replace(/\D+/,"")) + 1); 
    var prevId = "#miniDirektBestellenNum" + (parseInt(this.id.replace(/\D+/,"")) - 1);
    if( $(id).size() < 1 && (prevId == "#miniDirektBestellenNum0" || prevId != "#miniDirektBestellenNum0" && $(prevId).val().length > 0)) {
        var newid = $("#miniorderform .miniorderrow").length;
        if(newid < parseInt(company["maxOrderFormTableRows"])) {
            var newRow = createMiniOrderRow(newid + 1);
            $(newRow).appendTo("#miniordertable");
        }
    }
}


function createInputCell(headers, name, id, size, maxlength) {
    return createTableCell(headers).append(createInputField(name, id, size, maxlength));
}


function td(headers) {
    return $("<td></td>").attr("headers", headers);
}


function createInputField(name, id, size, maxlength) {
    return $("<input/>")
        .attr("type", "text")
        .attr("name", name)
        .attr("id", id)
        .attr("size", size)
        .attr("maxlength", maxlength);
}


function createMiniOrderRow(id) {
    var idStrValue = id.toString();
    var trId = "miniorderrow" + idStrValue;
    row = $("<tr></tr>").attr("id", trId).addClass("miniorderrow")
    
    row.append(td("miniDirektBestellenNum")
        .append(createInputField( "miniDirektBestellenNum" + idStrValue,
                                  "miniDirektBestellenNum" + idStrValue,
                                  "10", "32").addClass("miniDirektBestellenNum").focus(appendMiniOrderLine))
    );
    
    row.append(td("miniDirektBestellenAnz")
        .append(createInputField( "miniDirektBestellenAnz" + idStrValue,
                                  "miniDirektBestellenAnz" + idStrValue,
                                  "4", "5").addClass("miniDirektBestellenAnz"))
    );
    
    row.append(td("miniDirektBestellenVar")
        .append(createInputField( "miniDirektBestellenVar" + idStrValue,
                                  "miniDirektBestellenVar" + idStrValue,
                                  "4", "3").addClass("miniDirektBestellenVar"))
    );
    
    var deleteButtonUrl = $("<a></a>")
                            .attr("id", "miniDirektBestellenLoe" + idStrValue)
                            .attr("href", "#")
                            .attr("title", trans["zeileDelete"])
                            .click(removeMiniOrderRow);
    var deleteIcon = $("<img src=\"" + company["staticImagePath"] + "/ico/papierkorb.gif\" alt="+trans["papierkorb"]+" width=\"17\" height=\"17\">");               
    row.append(td("miniDirektBestellenLoe")
                .append(deleteButtonUrl.addClass("miniDirektBestellenLoe")
                    .append(deleteIcon)));
    return row;
}


function appendDirectOrderLine() {
    var lastLineNr = parseInt(this.id.replace(/\D+/,""));
    if(lastLineNr > 19) {
        return;
    }
    var id = "#directOrderNr" + (parseInt(this.id.replace(/\D+/,"")) + 1); 
    var prevId = "#directOrderNr" + (parseInt(this.id.replace(/\D+/,"")) - 1);
    if( $(id).size() < 1 && (prevId == "#directOrderNr0" || prevId != "#directOrderNr0" && $(prevId).val().length > 0)) {
        var newid = $("#directOrderForm .directOrderRow").length + 1;
        var newRow = createDirectOrderRow(newid);
        $(newRow).appendTo("#directOrderTable");
    }
}


function createDirectOrderRow(id) {
    var idStrValue = id.toString();
    var trId = "directOrderRow" + idStrValue;
    row = $("<tr></tr>").attr("id", trId).addClass("directOrderRow")
    
    row.append(td("wakoPos")
        .addClass("inpt")
        .html(idStrValue)
    );
    
    row.append(td("wakoBstNr")
        .addClass("directOrderNrText")
        .append(createInputField( "directOrderNr" + idStrValue,
                                  "directOrderNr" + idStrValue,
                                  "6", "5").addClass("directOrderNr").focus(appendDirectOrderLine))
    );
    
    row.append(td("wakoBstNr")
        .addClass("text")
        .append(createInputField( "directOrderAmount" + idStrValue,
                                  "directOrderAmount" + idStrValue,
                                  "4", "5").addClass("directOrderAmount"))
    );

    row.append(td("wakoVrnte")
        .attr("id", "directOrderSize" + idStrValue)
        .append(createInputField( "directOrderSize" + idStrValue,
                                  "directOrderSize" + idStrValue,
                                  "6", "5").addClass("directOrderSize"))
    );

    row.append(td("wakoBez")
        .attr("id", "directOrderDesc" + idStrValue)
        .append("&nbsp;")
    );

    row.append(td("wakoAnpss")
        .append($("<ul></ul>")
        .addClass("prdktFun")
        .append($("<li></li>")
            .append($("<a></a>")
                .click(removeDirectOrderRow)
                .addClass("lschn")
                .attr("id", "directOrderDelete" + idStrValue)
                .attr("href", "#")
                .append(trans["loeschen"]))))
    );
    
    return row;
}


function updateOrderRow() {
    if($(this).val().length > 0) {
        var id = $(this).parent().parent().attr("id");
        var articleNr = $(this).val();
        var id = parseInt(this.id.replace(/\D+/,""));
        $(this).parent().parent().load(company["contextPath"] + "/orderRowUpdate.html",
                                       {id : id, articleNumber : articleNr}, 
                                       function(a, status, c) {
                                          $(this).find("td>*").animate({opacity: 'show'}); 
                                          $("#directOrderTable .lschn").click(removeDirectOrderRow);
                                          $("#directOrderTable .directOrderNr").change(updateOrderRow);
                                          elem = $("#directOrderAmount"+id);
                                          ac = $(elem).attr("autocomplete");
                                          $(elem).attr("autocomplete", "off");
                                          elem.focus();
                                          $(elem).attr("autocomplete", ac);
                                       });
    }
}


function updateAllRowsInOrderForm() {
    $("#directOrderForm .directOrderNr").each(
    updateOrderRow);
}


function getStandortUrl(standortid) {
	if(isPrototypeEnvironment == true) {
	    return 'ajax/standorte/' + standortid + '.html';
	} else {
	    if(document.location.href.indexOf("https",0) == 0) {
	        return '/Standorte.html?standort=' + standortid + '&https';
	    } else {
	        return '/Standorte.html?standort=' + standortid;
	    }
	}
}


function getURLBase() {
    var currentUrl = window.location.href;
    if(currentUrl.indexOf("?") != -1) {
        stringArray = currentUrl.split("?");
        return stringArray[0];        
    }        
    else {
        return currentUrl;
    }    
}

// ----------------------------------------------------MerksWarenlexikon aus Produktdetailseite
    
    function mercksWarenlexikon(url){
        window.open(url, 'merckswarenlexikon', 
            'height=630, width=640, menubar=no, toolbar=no, status=no, resizable=yes, scrollbars=yes, directories=no'); return false;
    }
    
// ----------------------------------------------------Wunschzettel Email-felder 

function appendWishListInputFieldForMail() {
    var l = $(".wishMailField").length;
    if($(this).attr("id") == "prsAnEmail" + (l-1)) {
        var small = $("<small></small>").html(trans["optional"]);
        var label = $("<label></label>").attr("for", "prsAnEmail").html(trans["weiterer"]).append(small);
        var input = $("<input value=\"\" />")
            .attr("id", "prsAnEmail" + l)
            .attr("name", "emails")
            .attr("maxlength", "132")
            .attr("type", "text")
            .addClass("wishMailField")
            .focus(appendWishListInputFieldForMail);
        var delLink = $("<a></a>")
            .attr("href", "#")
            .attr("style", "margin-left:5px;")
            .attr("id", "prsAnEmailDelete" + l)
            .addClass("prsAnEmailDelete")
            .html(trans["loeschen"]);
        delLink.click(removeWishListMailField);
        var p = $("<p></p>").attr("id", "wishMailP" + l).append(label).append(input).append(delLink);
        $("#wishMailDiv").append(p);
    }
}

function removeWishListMailField() {
    var id = parseInt(this.id.replace(/\D+/,""));
    $("#wishMailP" + id).remove();
    updateWishListEmailFields();
}

function updateWishListEmailFields() {
    var n = 0;
    $("#wishMailDiv .wishMailField").each(function() {
        this.id = "prsAnEmail" + n;
        n++;
    });
}

function changeOptionalPassword(){
    $("#labelPw").html(trans["pw"]);
}

function changePassword(){
    $("#labelPw").html(trans["pwOptional"]);
}

//---------------------------------------------------- Firma als Anrede 

function swapAnredeElements() {
    if($("#prsAnAnrede")) {
        if($("#prsAnAnrede").val() == '0004' && $("#prsAnvornameLabel").html() == trans["firstName"]) {
            $("label:contains(trans['firstName'])").text(trans["company1"]);
            $("label:contains(trans['lastName'])").text(trans["company2"]);
            $("#adrAppendixId").html(trans["firstAndLastName"]);
            $("#prsAnvorname").attr("name", "lastName");
            $("#prsAnNachname").attr("name", "firstName");
            var firstName = $("#prsAnvorname").val();
            $("#prsAnvorname").val($("#prsAnNachname").val());
            $("#prsAnNachname").val(firstName);
        } else if($("#prsAnAnrede").val() != '0004' && $("#prsAnvornameLabel").html() == trans["company1"]){
            $("label:contains(trans['company1'])").text(trans["firstName"]);
            $("label:contains(trans['company2'])").text(trans["lastName"]);
            $("#adrAppendixId").html(trans["addressAppendix"]);
            $("#prsAnvorname").attr("name", "firstName");
            $("#prsAnNachname").attr("name", "lastName");
            var firstName = $("#prsAnvorname").val();
            $("#prsAnvorname").val($("#prsAnNachname").val());
            $("#prsAnNachname").val(firstName);
        }
    }
}

function markProductAsLatelySeen() {
    var bstNr = $("#bestellnummer").val();
    $.ajax({
        type: "POST",
        url: company['contextPath'] + "/ZuletztAngesehen.html",
        data: "articleNumber=" + bstNr,
        success: function(msg) {}
    });
}

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else {
        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]);
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
