$(document).ready(function(){

    var windowWidth,
    
    tId,
    cache = [];
    
    var showMiniInfo = function() {
        clearTimeout(tId);
        var this_ = this;
        tId=setTimeout(function(){  
               
            var showBox = function(data) {
                
                $(this_).append('<div class="productMiniInfoWindow"><div class="productMiniInfoContent"></div><div class="clear"></div><div class="arr"></div></div>');

                $('.productMiniInfoContent').html(data);
                windowWidth = $('.productMiniInfoWindow').width();
                var position = $(this_).offset();
                
                //obsluga listy
                if($(this_).parent('.showMiniInfo').width() > 500){
                    //strzalka z lewej
                    $('.productMiniInfoWindow').css({
                        'left': '100px'
                    });
                    
                    $('.productMiniInfoWindow .arr').addClass('left');
                }
                //kafelki
                else{
                    if( parseInt( $('html').width() / 2) > position.left){
                    
                        //strzalka z lewej
                        $('.productMiniInfoWindow').css({
                            'right':'-' + windowWidth + 'px' 
                        });
                        $('.productMiniInfoWindow .arr').addClass('left');
                    }else{
                        //strzalka z prawej
                        $('.productMiniInfoWindow').css({
                            'left':'-' + windowWidth + 'px'
                        });
                        $('.productMiniInfoWindow .arr').addClass('right');
                    }
                }

                $( $(this_).parents('.showMiniInfo') ).css('z-index','150');
                $('.productMiniInfoWindow').css('top','-' + (parseInt($('.productMiniInfoWindow').height())) / 2 + 'px');
               
                $('#productBoxMini .prodImgContainerMini').css('height',$('.productMiniInfoWindow').height() + 'px');
                $('.productMiniInfoWindow').fadeIn('slow');
            }

            var regex = /\/([0-9]+)\//g,
            productId = regex.exec($(this_).find('a').attr('href'))[1];
            
            if (productId in cache) {
                showBox(cache[productId]);
            }
            else {
                $.get($(this_).find('a').attr('href').replace('show', 'show-mini'), function(data) {
                    cache[productId] = data;
                    showBox(data);
                });
            }
        },650);
    };
    
    
    $(".showMiniInfo .productImg").live("mouseenter", showMiniInfo).live("mouseleave", function() { 
        clearTimeout(tId);
        $( $(this).parents('.showMiniInfo')).css('z-index','5');
        $('.productMiniInfoWindow').remove();
    }
    );
});
