mod_cart_timeout = 'undefined';
var bildArray = new Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
function bild(nummer) {
    var options = {
        zoomType: 'standard',
        zoomWidth: 319,
        zoomHeight: 319,
        xOffset: 10,
        yOffset: 20,
        position: "right",
        title: false
    };
    if (document.getElementById) for (a = 0; a < bildArray.length; a++) {
        if (bildArray[a] != nummer) {
            $("#bild" + bildArray[a]).hide();
                $('#zoom_it_' + bildArray[a]).unbind();
				$('.loaded_not_fired').remove();
        } else {
            $("#bild" + nummer).show();
                $('#zoom_it_' + nummer).jqzoom(options);
        }
    }
    return false;
}
$().ready(function() {
	if(($('#main_promo_text').length && $('#banner_start_cycle').length) || $('#start_mitarbeiter').length){
		//$('#main_promo_text').hide();
	}
    do_cart_quanty_init();
    $('.wish_tooly').tipsy({
        gravity: $.fn.tipsy.autoNS,
        title: function() {
            return $(this).next('.wish_tipsy_explain').html();
        },
        fade: true,
        html: true
    });
    $('.wish_tooly_alt').tipsy({
        gravity: $.fn.tipsy.autoNS,
        title: 'alt',
        fade: true,
        html: true
    });
    do_img_anim();
    $("#categories_container").accordion({
        header: '.title',
        active: false,
        alwaysOpen: true,
        autoheight: false
    });
    do_check_highlight();
    do_categories_ajax();
    do_ship_link();
    //do_animate_header();
    do_livechat_link();
	do_listing_change();
	do_setup_conf();
	do_check_cartAnim();
	setupSlider();
	$('ul.sf-menu').superfish({dropShadows:false,autoArrows:  false,delay:800,speed:500});
	$('.search_bg > input[type=text],#box_login > form > .mod_input').coolinput({source: 'title'});
	do_filters_buttons();
	do_schnellansicht();
});
function do_check_highlight() {
    highlight_it();
}
function highlight_it(data) {
    var config = {
        sensitivity: 3,
        interval: 300,
        over: function() {
            JT_show($(this));
        },
        timeout: 500,
        out: function() {}
    };
    $(".highlight").hoverIntent(config);
    $(".highlight").live('click',
    function() {
        JT_show($(this));
        return false;
    });
}
function check_ssl(mod_url) {
 					// SSL mod
					if(typeof mod_url != 'undefined'){
					var mod_href = '';
					if(typeof mod_ajax_request != 'undefined'){
					var mod_href = mod_url.replace(mod_ajax_normal_server,mod_ajax_ssl_server)
					}else{
							if(mod_url.search('https:') != -1){
							var mod_href = mod_url.replace('https:','http:')
							}else{
							var mod_href = mod_url;
							}
					}
					return mod_href;
					}
 }
function do_categories_ajax() {
    $('.subnav_ajax').bind('click',
    function() {
        var checked_basename = check_ssl($(this).attr('href'));
        $.ajax({
            url: checked_basename,
            data: {
                ajax: '1'
            },
            dataType: 'html',
            success: function(data) {
                $("html").animate({
                    scrollTop: 200
                },
                100);
                $('#putin_main').html(data);
            },
            beforeSend: function() {
                $('#box_whats_new').remove();
                $('#putin_main').html('<div class="ajax_loading"><img src="images/loading.gif" alt="loading..." title="loading..." /></div>');
                if ($('#countdown_product_1').length) {
                    $('#countdown_product_1').countdown('destroy')
                };
            }
        });
		if($('#box_bestsellers').length >0){
        $.ajax({
            url: checked_basename,
            data: {
                ajax: 'ajax_calls',
                what: 'get_bestsellers'
            },
            dataType: 'json',
            success: function(data) {
                put_it_in(data);
                $('#ajax_bestsellers').unblock();
            },
            beforeSend: function() {
                $('#ajax_bestsellers').block({
                    overlayCSS: {
                        backgroundColor: '#000',
                        opacity: 0.2
                    },
                    message: '<img src="images/loading.gif" alt="loading..." title="loading..." />',
                    css: {
                        width: '200px',
                        border: '1px solid #aaa',
						backgroundColor:'#fff',
						cursor:		'wait',
						height: '',
						margin:0
                    }
                });
            }
        });
		}
    });
    $('a.subnav_ajax_special').bind('click',
    function() {
        var checked_basename = check_ssl($(this).attr('href'));
        $.ajax({
            url: checked_basename,
            data: {
                ajax: '1'
            },
            dataType: 'html',
            success: function(data) {
                $('#putin_main').html(data);
            },
            beforeSend: function() {
                $("html").animate({
                    scrollTop: 200
                },
                100);
                $('#box_whats_new').remove();
                $('#putin_main').html('<div class="ajax_loading"><img src="images/loading.gif" alt="loading..." title="loading..." /></div>');
                if ($('#countdown_product_1').length) {
                    $('#countdown_product_1').countdown('destroy')
                };
            }
        });
        $.ajax({
            url: checked_basename,
            data: {
                ajax: 'ajax_calls',
                what: 'get_categories'
            },
            dataType: 'json',
            success: function(data) {
                put_it_in(data);
                $('#box_categories').unblock();
            },
            beforeSend: function() {
                $('#box_categories').block({
                    overlayCSS: {
                        backgroundColor: '#000',
                        opacity: 0.2
                    },
                    message: '<img src="images/loading.gif" alt="loading..." title="loading..." />',
                    css: {
                        width: '200px',
                        border: '1px solid #aaa',
						backgroundColor:'#fff',
						cursor:		'wait',
						height: '',
						margin:0
                    }
                });
            }
        });
        return false;
    });
}
function MOD_preloadImages() {
    var d = document;
    if (d.images) {
        if (!d.MOD_p) d.MOD_p = new Array();
        var i,
        j = d.MOD_p.length,
        a = MOD_preloadImages.arguments;
        for (i = 0; i < a.length; i++) if (a[i].indexOf("#") != 0) {
            d.MOD_p[j] = new Image;
            d.MOD_p[j++].src = a[i];
        }
    }
}
function MOD_swapImgRestore() {
    var i,
    x,
    a = document.MOD_sr;
    for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++) x.src = x.oSrc;
}
function MOD_findObj(n, d) {
    var p,
    i,
    x;
    if (!d) d = document;
    if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
        d = parent.frames[n.substring(p + 1)].document;
        n = n.substring(0, p);
    }
    if (! (x = d[n]) && d.all) x = d.all[n];
    for (i = 0; ! x && i < d.forms.length; i++) x = d.forms[i][n];
    for (i = 0; ! x && d.layers && i < d.layers.length; i++) x = MOD_findObj(n, d.layers[i].document);
    if (!x && d.getElementById) x = d.getElementById(n);
    return x;
}
function MOD_swapImage() {
    var i,
    j = 0,
    x,
    a = MOD_swapImage.arguments;
    document.MOD_sr = new Array;
    for (i = 0; i < (a.length - 2); i += 3) if ((x = MOD_findObj(a[i])) != null) {
        document.MOD_sr[j++] = x;
        if (!x.oSrc) x.oSrc = x.src;
        x.src = a[i + 2];
    }
}
function put_it_in(data) {
    if (typeof(data.error) != 'undefined') {
        mod_url_to_go = check_ssl(data.error);
        setTimeout(function() {
            window.location.href = mod_url_to_go
        },
        100);
    } else {
		if(typeof(data.message_to_show)!='undefined'){
			$.each(data.message_to_show, function(json_message_to_show_id,json_message_to_show_data){
			$.growlUI(json_message_to_show_data.title, json_message_to_show_data.text,0);
			});
		}
		// get the right main _content
		if(typeof(data.url_to_get)!='undefined'){
		$.ajax({url:check_ssl(data.url_to_get),data:{ajax:1},success:function(html_of_data){show_loader('hide');$('#putin_main').html(html_of_data);do_cart_quanty_init();do_check_highlight();},beforeSend:function(){show_loader('show');}});
		}
		
        if (typeof(data.items) != 'undefined') {
            $.each(data.items,
            function(json_id, json_data) {
                if (json_data.update_cat == '1') {
                    $(json_data.update_select).parent().children('.subnav_ajax_special').each(function() {
                        $(this).removeClass('aktive_ajax_special')
                    });
                    $(json_data.update_select).addClass('aktive_ajax_special');
                    if (typeof(lastupdated) != 'undefined') {
                        $(lastupdated).remove();
                    } else {
                        $('.zweiteebene,.zweiteebene_aktive,.dritteebene,.dritteebene_aktive').each(function() {
                            $(this).remove()
                        });
                    }
                    $(json_data.update_select).after(json_data.update_text);
                    lastupdated = json_data.update_select.replace('ajax_cat_putin_', 'ajax_cat_updated_');
                } else {
                    $(json_data.update_select).html(json_data.update_text);
                    do_img_anim();
                }
            });
        }
    }
}
function do_img_anim() {
    $('.one_new_img').each(function() {
        $(this).prev().bind('mouseenter',
        function() {
            $(this).next().queue([]);
        });
        $(this).prev().bind('mouseleave',
        function() {
            $(this).next().animate({
                height: 'show'
            },
            200);
        });
        $(this).children().children().attr('alt', '');
		var config = {
            sensitivity: 1,
            interval: 150,
            over: function() {
                $(this).animate({
                    height: 'hide'
                },
                200);
            },
            timeout: 150,
            out: function() {}
        };
        $(this).hoverIntent(config)
    });
}
function do_ship_link() {
    $(".ship_link").live('click',
    function() {
        window.open($(this).attr('href'), 'popup', 'toolbar=0, scrollbars=yes, resizable=yes, height=720, width=750');
        return false;
    });
	
	$(".print_popup_content").live('click',
    function() {
        window.open($(this).attr('href'), 'popup', 'toolbar=0, scrollbars=yes, resizable=yes, height=720, width=640');
        return false;
    });
}
function mysqlTimeStampToDate(timestamp) {
    var regex = /^([0-9]{2,4})-([0-1][0-9])-([0-3][0-9]) (?:([0-2][0-9]):([0-5][0-9]):([0-5][0-9]))?$/;
    var parts = timestamp.replace(regex, "$1 $2 $3 $4 $5 $6").split(' ');
    return new Date(parts[0], parts[1] - 1, parts[2], parts[3], parts[4], parts[5]);
}
function do_animate_header() {
    //$('#ekomi_top').hide();
    if ($('#box_live_shopping').length) {
        $('#box_live_shopping').animate({
            top: 104
        },
        500,
        function() {/*
            $('#ekomi_top').animate({
                left: 710
            },
            0,
            function() {
                $('#ekomi_top').fadeIn(300);
            });
        */});
    } else {
        /*$('#ekomi_top').animate({
            left: 710
        },
        1,
        function() {
            $('#ekomi_top').fadeIn(300);
        });*/
    }
    $('#countdown_wrapper').bind('mouseenter',
    function() {
        //$('#live_shopping_wrapper').css('z-index', '95');
        $('#box_live_shopping').animate({
            top: 0
        },
        500);
    });
    var config = {
        sensitivity: 1,
        interval: 0,
        over: function() {},
        timeout: 350,
        out: function() {
            $('#box_live_shopping').animate({
                top: 104
            },
            500,
            function() {
                //$('#live_shopping_wrapper').css('z-index', '80');
            });
        }
    };
    $('#box_live_shopping').hoverIntent(config);
}
function do_livechat_link() {
    $(".livechat_link").live('click',
    function() {
        window.open($(this).attr('href'), '', 'width=600,height=600,left=0,top=0,resizable=yes,menubar=no,location=yes,status=yes,scrollbars=yes');
        return false;
    });
}

function do_cart_quanty_init(wich_one) {
	if(wich_one == '' || typeof(wich_one)=='undefined'){
		wich_one = '#cart_quantity,form[id^=live_quantity],#multi_buy';
	}
    if ($(wich_one).length) {
		
		if ($('#multi_buy').length) {
			$('.products_form_submit').each(function(){
			$(this).unbind('click');																 
			$(this).bind('click',function(){
										  emosTargetEvent('multibuy','multibuy_click',0);
										  if($(this).prev('.products_input_qty').attr('value') == ''){
										  	$(this).prev('.products_input_qty').attr('value','1');
										  }else if($(this).next('.products_input_qty').attr('value') == ''){
										  	$(this).next('.products_input_qty').attr('value','1');
										  }
										  });
												 });
		}
		
        var checked_basename = check_ssl($(wich_one).attr('action'));
        var options = {
            url: checked_basename,
            dataType: 'json',
            data: {
                ajax: 'ajax_calls',
                what: 'cart'
            },
            beforeSubmit: function() {
                show_loader('show');
            },
            // pre-submit callback 
            success: function(data) {
                put_it_in(data);
                do_cart_quanty_init();
				do_check_cartAnim();
            } // post-submit callback 
        };
        $(wich_one).ajaxForm(options);
        $('select[name=attributes]').bind('change',
        function() {
            $(wich_one).ajaxSubmit(options);
        });
		// bind the keypress
var search_timeout = undefined;
$('input[name^=cart_quantity]').bind('keyup', function() {
        if(search_timeout != undefined) {
                clearTimeout(search_timeout);
        }
        var $this = this; // save reference to 'this' so we can use it in timeout function
        search_timeout = setTimeout(function() {
                search_timeout = undefined;
                $('#cart_quantity').ajaxSubmit(options);
        }, 750);
});
		
        $(wich_one).submit(function() {
            return false;
        });
    }
}

function show_loader(what) {
    if (what == 'show') {
        $.blockUI({
            message: '<img src="images/loading.gif" />',
            css: {
                width: '',
				height: '',
                margin: '0 0 0 -80px',
                left: '50%',
				top: '40%',
                border: '1px solid #211450',
				padding:	0,
				backgroundColor:'#fff',
				cursor:		'wait'
            },
            showOverlay: false,
            overlayCSS: {
                opacity: 0
            }
        });
    } else {
        $.unblockUI();
    }

}

  function do_listing_change(){
	function return_options(action_url){
		var checked_basename = check_ssl(action_url);
		var options = {
			url:checked_basename,
			target: '#putin_main',
			data:{ajax:'1'},
        	beforeSubmit:  function(){show_loader('show');},  // pre-submit callback 
        	success:       function(data){show_loader('hide');do_img_anim();do_listing_change();do_cart_quanty_init();do_check_highlight();do_setup_conf();}   // post-submit callback 
    	};
		return options;
	}
	$(".listing_template_form > form").each(function(){
	$(this).ajaxForm(return_options($(this).attr('action')));
					  });
	$('.max_result_dd').each(function(){
									  $(this).ajaxForm(return_options($(this).attr('action')));
									  	$(this).children('select[name=max_result],select[name=multisort]').bind('change',function(){ $(this).parent('.max_result_dd').ajaxSubmit(return_options($(this).parent('.max_result_dd').attr('action')));});
									  });
	
 }
 
 function do_setup_conf(){
	 	$('.mod_conf_in_cart').live('click',function(){
												 $('#multi_buy').submit();
												 return false;
												 });
		/*if (!$('div.conf_boy_now').length) {
		$('div.mod_conf_header').next().hide();
			$('div.mod_conf_header').click(function(){
					$(this).next().slideToggle('1000');								
													});	
		}*/
	 }
	 
function do_check_cartAnim(){
	if($('#cart_hidden').length){
		    var config = {
        sensitivity: 3,
        interval: 100,
        over: function() {
			$('#cart_hidden:hidden').slideDown(500);
			if(mod_cart_timeout != 'undefined'){
				clearTimeout(mod_cart_timeout);
			}
        },
        timeout: 500,
        out: function() {$('#cart_hidden:visible').slideUp(500);}
    };
	$('#cart_hidden').removeClass('no_js').addClass('yes_js');
	 $('#box_cart').live('mouseover', function()  
     {  
         if (!$(this).data('init') && $('#cart_hidden').length)  
         {  
             $(this).data('init', true);  
             $("#box_cart").hoverIntent(config);  
             $(this).trigger('mouseover');  
         }  
     });
 $('#mini_cart_close_button,#mini_cart_close_button2').live('click',function(){$('#cart_hidden:visible').slideUp(200);});   
	}
}

 function setupSlider(){
	    function g(l, k) {
            if (l.has(l.first, l.last)) {
                return
            }
			//if(k != 'init'){
           		l.lock();
					if(typeof(mod_current_cPath) !='undefined'){
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id'),mod_catPath:mod_current_cPath}
					}else{
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id')}
					}
				$.ajax({url:'',data:mod_data,type:'GET',dataType:'json',success:function(data){fadd(l, l.first, data)},beforeSend:function(){}});
            	l.unlock()
			//}
        }
		function fadd(l, m, k) {
			if(k.slider_qty > 30){
				l.size('30');
			}else{
				l.size(k.slider_qty);
			}
			$.each(k.slider_element, function(json_id,json_data){
				if(l.last == l.size()){
					m_add = (l.size() - k.slider_element.length + json_id+1);
					l.add(m_add, json_data);
				}else{
					l.add(m + json_id, json_data);
				}
			});
        }
		function iNt(l,k) {
            $(l.container.children('.jcarousel-clip').children('.jcarousel-list').children('li')).each(function() {
                if ($(this).html() == "") {
					if(k != 'init' && k != 'resize'){
                    $(this).html('<div class="jcarousel-loader"><div class="jcarousel-loader-img"></div></div>')
					}
                }
            })
        }
		
		function setSize(l, k) {
			if(l.size() == l.options.scroll){
			l.size(l.size()+l.options.scroll)
			}
		}
		
		function setSizeAlready(l, k) {
			    l.lock();
				if(typeof(l.last)=='undefined'){l.last = '1'}
					if(typeof(mod_current_cPath) !='undefined'){
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id'),mod_catPath:mod_current_cPath}
					}else{
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id')}
					}
				
				$.ajax({url:'',data:mod_data,type:'GET',dataType:'json',success:function(data){faddAlready(l, l.first, data)},beforeSend:function(){}});
            	l.unlock();
					// Pause autoscrolling if the user moves with the cursor over the clip.
    l.clip.hover(function() {
        l.stopAuto();
    }, function() {
        l.startAuto();
    });
		}
		function faddAlready(l, m, k) {
			l.size(k.slider_qty);
        }
		
		function setSizeAlreadyPromo(l, k) {
			    l.lock();
				if(typeof(l.last)=='undefined'){l.last = '1'}
					if(typeof(mod_current_cPath) !='undefined'){
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id'),mod_catPath:mod_current_cPath}
					}else{
					mod_data = {ajax_page: l.last,ajax:'ajax_calls',what:$(l.container.parent()[0]).attr('id')}
					}
				$.ajax({url:'',data:mod_data,type:'GET',dataType:'json',success:function(data){faddPromo(l, l.size(), data)},beforeSend:function(){}});
            	l.unlock();
					// Pause autoscrolling if the user moves with the cursor over the clip.
    l.clip.hover(function() {
        l.stopAuto();
    }, function() {
        l.startAuto();
    });
		}
		function faddPromo(l, m, k) {
			mod_last_size = l.size();
			if(k.slider_qty > 30){
				l.size(parseInt('30')+parseInt(l.size()));
			}else{
				l.size(parseInt(k.slider_qty)+parseInt(l.size()));
			}
						
			$.each(k.slider_element, function(json_id,json_data){
				
				if(l.last == l.size()){
					m_add = (parseInt(l.size()) - parseInt(k.slider_element.length) + parseInt(json_id)+1);
					l.add(m_add, json_data);
				}else{
					l.add(parseInt(m) + parseInt(json_id) + parseInt(mod_last_size) , json_data);
				}
				
			});
			//so now only add the texte
			if($('#main_promo_text').length){
				//l.add(parseInt(l.size())+1 , '<div id="moved_start"></div>');
				//l.size(parseInt(l.size())+1);
				//$('#main_promo_text').appendTo('#moved_start').show();
			}
			
        }
		
		
$('#news_load').jcarousel({itemLoadCallback:{onBeforeAnimation: iNt,onAfterAnimation: g},
						  scroll:1,
						  initCallback:setSizeAlready
								});
/*promo_call**/
if($('#banner_start_cycle').length){
	
setTimeout(function(){$('#promo_load').jcarousel({
						   auto:4,
						   animation:1000,
						   wrap:'both',
						   scroll:1,
						  initCallback:setSizeAlreadyPromo
								});},2000);
}

if($('#cycle_main_content').length){
$('#cycle_main_content').cycle({
		fx: 'fade',
		pager:  '#nav_main_content',
		slideExpr: '.main_inner_cycle',
		pause:true,
		pauseOnPagerHover:true,
		timeout:0,
		speed:0,
		delay:10000
	});	
}

if($('#load_marken').length){
	$('#load_marken').jcarousel({scroll:1});
}


 }
 
 

function do_filters_buttons(){
	if($('.stil_col_right').length){
		$('.mod_one_filter').button();
		
		/*$('.one_filter_whole,.two_filter_whole').each(function(){
			that = $(this).find('.one_filter_scroll');
			that.data('natural', that[0].scrollHeight);
			that.data('height', that.height());
			    var config = {sensitivity: 7,interval: 100,over: function() {$(this).clearQueue();$(this).animate({'maxHeight': $(this).data('natural')},500);},timeout: 1000,out: function() {$(this).clearQueue();$(this).animate({'maxHeight': $(this).data('height')},500);}};

			that.hoverIntent(config);
				
			
			
			});*/

			
		//do_price_filters()
	}
}


 function do_price_filters(){
					//here the init of the scrolls

	
	$('.one_filter_scroll_price > #pfrom,.one_filter_scroll_price > #pto').ForceNumericOnly();
	
	$("#price_filter").children().hide();
	$("#pfrom,#pto").css('border','0px solid #000000').attr('readonly','readonly');
			$("#price_filter").slider({
			range: true,
			step:4,
			values: [ 75, 300 ],
			slide: function(event, ui) {
				$("#pfrom").val(ui.values[0]);
				$("#pto").val(ui.values[1]);
			},
			stop: function(event, ui){
				$(this).parents('form').submit();
			}
		});

		var mod_low = 0;
		if($('#lowest_price').length){
			var mod_low = parseInt($('#lowest_price').html());
			$("#price_filter").slider( "option", "min" ,mod_low);
		}
		var mod_high = 100;
		if($('#high_price').length){
			var mod_high = parseInt($('#high_price').html());
			$("#price_filter").slider( "option", "max" ,mod_high);
		}
		if($("#pfrom").val() > 0){
			$("#price_filter").slider("values", 0,$("#pfrom").val());
		}else{
			$("#price_filter").slider("values", 0,0);
		}
		if($("#pto").val() > 0){
			$("#price_filter").slider("values", 1,$("#pto").val());
		}else{
			$("#price_filter").slider("values", 1,$( "#price_filter" ).slider( "option", "max" ));
		}

		
		$("#pfrom").val( $("#price_filter").slider("values", 0));
		$("#pto").val( $("#price_filter").slider("values", 1));
}
 // Numeric only control handler
$.fn.ForceNumericOnly =
function()
{
    return this.each(function()
    {
        $(this).keydown(function(e)
        {
            var key = e.charCode || e.keyCode || 0;
            // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
            return (
                key == 8 || 
                key == 9 ||
                key == 46 ||
                (key >= 37 && key <= 40) ||
                (key >= 48 && key <= 57) ||
                (key >= 96 && key <= 105));
        })
    })
};

function mod_move_cart(){
	$('#cart_hidden:hidden').slideDown(500);
	mod_cart_timeout = setTimeout(function() {
                mod_cart_timeout = 'undefined';
                $('#cart_hidden:visible').slideUp(500);
        }, 10000);
}







 
/* autocompleteField = jQuery("#flAutocompleteInputText");
jQuery(function() {
	function format(item) {
		return "<div class=\"autocompletecount\">~" + item.count + " Treffer</div>" + item.name;
	}
	autocompleteField.autocomplete('/scripts/autocomplete.php', {
		minChars: 2,
		dataType: "json",
		cacheLength: 1,
		matchSubset: false,
		autoFill: false,
		selectFirst: false,
		width:'266px',
		scrollHeight:250,
		max:100,
		parse: function(data) {
			return jQuery.map(data.suggestions, function(row) {
				row = row.split("|");
				return {
					data: {name: row[0], count: row[1]},
					value: row[0],
					result: row[0]
				}
			});
		},
		formatItem: function(item) {
			return format(item);
		},
		extraParams: {
			query: function() { return autocompleteField.val(); }
		}
	});
});*/




// $Revision: 125 $
// Maximale Bildbreite für die Thumbnail-Bilder in der Liste
maxWidthThumb = 40;
// Maximale Bildhöhe für die Thumbnail-Bilder in der Liste
maxHeightThumb = 40;
// Maximale Bildbreite für die Vorschau-Bilder bei Mouseover
maxWidthPreview = 250;
// Maximale Bildhöhe für die Vorschau-Bilder bei Mouseover
maxHeightPreview = 250;

// Benennung der Kategorien in der Liste
itemLabel = {
	'title':'Produktname',
	'cat':'Kategorie',
	'vendor':'Hersteller',
	'ordernumber':'Artikelnummer'
};
 autocompleteField = $("#flAutocompleteInputText");
$(function() {
	function format(item) {
		result = ''; 
		item.outputCat = itemLabel[item.cat];
		
		// Ausgabecode für die einzelnen Treffer
		if (item.image) {
			result += '<td class="ac_image" align="center" width="' + maxWidthThumb + 'px" height="' + maxHeightThumb + '"><img src="' + item.image + '" alt="Thumbnail" style="display:none;" /></td>';
		} else {
			result += '<td><span style="display:block;width:' + maxWidthThumb + 'px;height:' + maxHeightThumb + 'px;">&nbsp;</span></td>';
		}
		//result += '<td class="ac_name" valign="top">' + item.name + '</td><td class="ac_cat" valign="top">' + item.outputCat + '</td>';
		result += '<td class="ac_name" valign="top">' + item.name + '</td>';
		return result;
	}
	autocompleteField.autocomplete('scripts/structured_autocomplete.php', {
		max: 50,
		minChars: 2,
		dataType: "json",
		cacheLength: 1,
		matchSubset: false,
		autoFill: false,
		selectFirst: false,
		scrollHeight:400,
		scroll: true,
		width: false,
		parse: function(data) {
			suggestions = $.map(data.suggestions, function(row) {
				row = row.split("|");
				lastCat = "";
				/* sometimes the suggestion text contains the | symbol, so re-join it manually, leaving out the last two parts */
				text = row.slice(0, row.length - 2).join("|");
				return {
					data: {name: text, cat: row[row.length - 2], count: row[row.length - 1]},
					value: text,
					result: text
				}
			})
			for (i in suggestions) {
				suggestions[i].data.image = data.images[i];
				suggestions[i].data.parameters = data.parameters[i];
				/* remove the .result if there are parameters present, so the submitted query is empty */
				if (!$.isEmptyObject(data.parameters[i])) {
					suggestions[i].result = "";
				}
			}
			return suggestions;
		},
		formatItem: function(item) {
			return format(item);
		},
		extraParams: getFormValues(autocompleteField[0]),
	});
	autocompleteField.result(function(event, data, formatted) {
		addParameters(event.target.form, data.parameters, "", 0);
	});
});

// preloads images
function preloadImages (dom, maxW, maxH) {
	$(dom).preload({
		onComplete:completePL,
		treshhold:5
	});
	function completePL (data) {
		if(data.found) {
			resizeImage($(data.original), maxW, maxH);
		}
	}
}

// resizes image to given dimensions
function resizeImage (original, maxW, maxH) {
	if (original.width() > maxW || original.height() > maxH) {
                if (original.width() * maxH > original.height() * maxW) {
                        newW = new String(maxW) + "px";
                        newH = new String(maxW * original.height() / original.width()) + "px";
                } else {
                        newH = new String(maxH) + "px";
                        newW = new String(maxH * original.width() / original.height()) + "px";
                }
        } else {
                newW = new String(original.width()) + "px";
                newH = new String(original.height()) + "px";
        }
	original.css({width:newW,height:newH});
	original.show(); 
}

// starts preview on mouseover
function showPreview() {
	xOffset = -5;
	yOffset = 5;
	
	$('.ac_results table tr').live('hover', 
		function(e){
			src = $(this).children('td').children('img').attr('src'); 
			if (src && $(this).children('td').children('img').css('display') != 'none') {
				if (e.type == 'mouseenter') {
					$('body').append('<div id="preview"><img src="' + src + '" alt="Preview" style=display: none;" /></div>');
					preloadImages('#preview img', maxWidthPreview, maxHeightPreview);
					$("#preview").css("top",(e.pageY - xOffset) + "px").css("left",(e.pageX + yOffset) + "px").fadeIn("fast");
				} else {
					$('#preview').remove();
				}
			}
		}
	);
	$('.ac_results table tr').live('mousemove', 
		function(e){
			var bodyW = $('body').outerWidth();
			var bodyH = $('body').outerHeight();
			var imgW = (e.pageX + yOffset + $('#preview').width());
			var imgH = (e.pageY - xOffset + $('#preview').height());
			var imgL = (e.pageX + yOffset);
			var imgT = (e.pageY - xOffset);
			if (imgH > bodyH) {
				imgT = (e.pageY-$('#preview').height()+xOffset);
			}
			if (imgW > bodyW) {
				imgL = (e.pageX-$('#preview').width()-yOffset);
			}
			$("#preview").css("top",imgT + "px").css("left",imgL + "px");
		}
	);
	$(document).keydown(function(e) {
		if (e.keyCode == 27) {
			$("#preview").remove();
		}
	});
}

/* append filter parameters to the form before it is submitted */
function addParameters(form, data, name, depth) {
	for (i in data) {
		var encodedName = encodeURI(i);
		subname = (depth > 0 ? name + "[" + encodedName + "]" : encodedName);
		if (typeof data[i] != "object") {
			$(form).append($("<input/>").attr("type", "hidden").attr("name", subname).val(data[i]));
		} else {
			addParameters(form, data[i], subname, depth + 1);
		}
	}
}


/* collect all form values to be submitted with the autocomplete request */
function getFormValues(input) {
	inputs = {};
	$($(input.form).serializeArray()).each(function(i, j) {
		if(j.name!='keywords'){
			inputs[j.name] = j.value;
		}
	});
	//inputs.query = function() { return $(input).val(); };
	return inputs;
}

showPreview();

function do_schnellansicht(){
	if($('.ajax_listings').length){
		//make it live
		$('.ajax_listings').find('.one_listing_left,.one_listing_left2,.one_listing_left3').live('hover',function(e){
			if(e.type == 'mouseenter'){
				if(!$(this).find('.prod_buttons').length){
				//now we add the button
					var mod_add_button = '<div class="prod_buttons"><a class="ajax_prod" href="'+$(this).find('.listing_image').find('a').attr('href')+'">Schnellansicht</a><a href="'+$(this).find('.listing_image').find('a').attr('href')+'">Details</a></div>';
					$(this).find('.listing_image').append(mod_add_button);
				}
				$(this).find('.prod_buttons').fadeIn(250);
			}else{
				$(this).find('.prod_buttons').fadeOut(250);
			}
			
			
			});
		
		$('.ajax_prod').live('click',function(){
			var checked_basename = check_ssl($(this).attr('href'));
			$.ajax({
	            url: checked_basename,
	            data: {
	                ajax: '1'
	            },
	            dataType: 'html',
	            success: function(data) {
					show_loader('hide');
					$.blockUI({
						focusInput: false, 
						message: data,
				css: {
        	        width: $('.ajax_schnellansicht').width(),
					height: '',
	                margin: '0 0 0 -461px',
                	left: '50%',
					top: parseInt($(window).scrollTop())+parseInt(($(window).height()/100*16)),
        	        border: 'none',
					position: 'absolute',
					padding:	0,
					backgroundColor:'',
					cursor:		''
            	},
				 overlayCSS:  { 
      				  backgroundColor: '#000', 
				      opacity:         0.3 
    			}
						});
				do_cart_quanty_init('#cart_quantity');
				do_ship_link();
				do_check_highlight();
	            },
	            beforeSend: function() {
					show_loader('show');
					}
	        });
			$('.blockOverlay,.ajax_schnellansicht_close,.ajax_prod_back').live('click',function(){
				$.unblockUI({onUnblock: function(){$('.jqZoomWindow').remove();}});$('.blockOverlay').unbind();
				return false;
				});
			return false;
			});
	}
}
