function alertTh(i, dragThumb) {
    //Дозакрытие блоков которые по маус ауту не закрылись
    var n = 0;
    resolutions = new Array('1024x768', '1152x864', '1280x960', '1280x1024', '1400x1050', '1600x1200', '1920x1440', '2560x1920', '1280x800', '1440x900', '1680x1050', '1920x1200', '2560x1600', '720p', '1080p', 'iPhone', 'iPad', '800x480', '1024x600', '1366x768', '2560x1024', '2880x900', '3200x1200', '3360x1050', '3840x1200', '5120x1600', '5120x1920');
    while ((block = $('#reflections').children()[n++])) {
        var tempId = '#' + $(block).attr('id');
        $(tempId).remove();
    }
    
    //Создание HTML зеркала
    var id = 'ref' + i.attr('id');
    var needResolution = currentResolution(i);
    var html = '<div id="' + id + '" class="refTh">\n\
<img src="/i/p.png" class="refImg"/>\n\
<div class="resLink hidden">\n\
<div class="link">\n\
<a onClick="return apiHref(this);" resolution="' + needResolution + '" href="/open/' + i.attr('translit') + '-' + i.attr('id').replace('th', '') + '.html">' + needResolution.replace('x', '&nbsp;&times;&nbsp;') + '</a>\n\
</div>\n\
<div class="img">\n\
<div class="container">\n\
<a href="/open/' + i.attr('translit') + '-' + i.attr('id').replace('th', '') + '.html" title="\u041cаксимальное разрешение"></a>\n\
</div>\n\
</div>\n\
<div class="clearfloat"></div>\n\
</div>\n\
<div class="clearfloat"></div>\n\
</div>';
//alert(html);
    $('#reflections').append(html);
    
    //Расчёт переменных
    id = '#' + id;
    var srcWidth = parseInt(i.width());    //ширина и высота маленькой иконки которая отображается 120 х 120
    var srcHeight = parseInt(i.height());  //120
    var tWidth  = 288; //оригинальные размеры тумбы
    var tHeight = 180;
    var offsetLeft = parseInt(i.offset().left); //Расстояние слева, сверу верхнего левого угла картинки 120 х 120
    var offsetTop = parseInt(i.offset().top);
    var endOffsetTop = offsetTop - tHeight/2 + srcHeight/2; //Итоговое расстояние сверху, слева тумбы исходного размера
    var endOffsetLeft = offsetLeft - tWidth/2 + srcWidth/2 - ($.browser.msie ? 0 : 0);
    
    var resLinkWidth = parseInt($('.refTh .resLink').width()); //Ширина блока с сылками на опен

    //Проверка выхода за границы документа
    endOffsetLeft = endOffsetLeft < 10 ? 10 : endOffsetLeft;
    endOffsetLeft = endOffsetLeft + tWidth > $(document).width() - 10 ? $(document).width() - 10 - tWidth : endOffsetLeft;
    endOffsetTop  = endOffsetTop < 10 ? 10 : endOffsetTop;
    endOffsetTop  = endOffsetTop + tHeight > $(document).height() - 10 ? $(document).height() - 10 - tHeight : endOffsetTop;
    
    
    //Создание клона поверх иконки 120 на 120, которая будет преобразовываться
    $(id + '.refTh .refImg').attr('src', i.attr('src'));
    $(id + '.refTh .refImg').css('width', srcWidth);
    $(id + '.refTh .refImg').css('height', srcHeight);

    $(id).css('width', srcWidth);
    $(id).css('height', srcHeight);

    $(id).css('top', offsetTop);
    $(id).css('left', offsetLeft);

    $(id).css('display', 'block');
    $(id + '.refTh .resLink').css('left', tWidth / 2 - resLinkWidth / 2 - 18);
    
    $(id + '.refTh').css({'background-image' : 'url(' + $(id + '.refTh .refImg').attr('src') + ')'})
    
    //Увеличение картинки
    $(id + '.refTh').animate({
        width: tWidth,
        height: tHeight,
        top: endOffsetTop,
        left: endOffsetLeft
    }, {
        duration: 100
    });
    $(id + '.refTh .refImg').animate({
        width: tWidth,
        height: tHeight,
        top: endOffsetTop,
        left: endOffsetLeft
    }, {
        duration: 100,
        complete: function() {
            $(id + '.refTh .resLink').removeClass('hidden');
            $(id + '.refTh .refImg').remove();
        }
    });
    
    
     //Включение перетаскивания//
    if ($('.prp .pics .thumb').length < 10) 
        dragThumb = false;
    
    if (dragThumb == true) {
        //Переменная определяющая необходимость свертывания картинки если мышка ушла во время перетаскивания
        var needHide = false;
        var innerPicOffset = getInnerPicOffset(i);

        stopLeft = innerPicOffset - width + $('.content2').offset().left + 960 - 160;

        //Останавливать справа только если вначале
        stopRight = endOffsetLeft - $('.prp .relativePictures .pics').position().left;

        //Включение перетаскивания для картинки
        $(id).draggable({ 
                axis: 'x',
                start: function () {
                    $('.thumb').unbind('mouseover');
                    $(id).unbind('mouseleave');
                    $(id).bind('mouseleave', function () {
                        needHide = true;
                    });
                    startLeft = $('.prp .relativePictures .pics').position().left;
                    imgStartLeft = $(id).position().left;
                },
                drag: function () {
                    //Прокрутка блока с картинками
                    var idPositionLeft = $(id).position().left;
                    var left = startLeft - imgStartLeft + idPositionLeft;
                    var overflowLeft  = $('.content2').position().left - idPositionLeft;
                    var overflowRight = -$('.content2').position().left - 960 + tWidth + idPositionLeft;
                    var opacity;

                    //Исчезновение по краям
                    switch (true) {
                        case overflowLeft > 0 && overflowRight < 0:
                        case overflowLeft < 0 && overflowRight > 0:
                            opacity = 1 - Math.max(overflowLeft, overflowRight)/100;
                            break;
                        default:
                            opacity = 1;

                    }
                    $(id).fadeTo(0, opacity);
                    $('.scroll .bar .dott').css('left', -1 * left / speed);
                    $('.prp .relativePictures .pics').css('left', left);
                },
                stop: function () {
                    $('.prp .relativePictures .pics').width();
                    $('.content2 .thumb').bind('mouseover',
                        function () {
                            alertTh($(this), true);
                        });
                    $('.content2 .selected .thumb').unbind('mouseover');
                    if (needHide == true) $(id).remove();
                    $(id).unbind('mouseleave').bind('mouseleave', function () {
                        $(id).remove();
                    });
                },
                containment: [stopLeft, 0, stopRight, 1000],
                scroll: false

            });
        ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    }
    
    //Добавление события на удаление
    $(id).bind('mouseleave', function () {
        $(this).remove();
    });

}

function hideTh(id) {
    i = $(id.replace('ref', ''));
    $(id + '.refTh .resLink').css('display', 'none');
    try {
        var srcWidth  = i.width();   
        var srcHeight = i.height();   
        var offsetLeft = i.offset().left + (srcWidth - srcHeight)/2 ;
        var offsetTop = i.offset().top;
    } 
    catch (err) {
        $(id).remove();
    }
    $(id).animate({
            width: srcHeight,
            height: srcHeight,
            top: offsetTop,
            left: offsetLeft
        }, {
            duration: 100,
            complete: function() {
                $(this).remove();
        }
    });
    $(id + '.refTh .refImg').animate({
            width: srcWidth,
            height: 120,
            top: offsetTop,
            left: offsetLeft
        }, {
            duration: 100,
            complete: function() {
        }
    });
}

function getThumbSizes(i, p) {
    var sizes = new Object ();
    var delta = new Object ();
    var n, x, min = 1000, key;
    sizes = {
        125 : {width : 240, height : 192},
        134 : {width : 240, height : 180},
        158 : {width : 259, height : 162},
        250 : {width : 300, height : 120},
        300 : {width : 360, height : 120}
    }
    for (x in sizes) {
        if (Math.abs(x - i) < min) { 
            min = Math.abs(x - i);
            key = x;
        } else continue;
    }
    return sizes[key][p];
}

//Подсчёт растояния от левого края для картинки 80х80 внутри блока/////
getInnerPicOffset = function (i) {
    var n = 0;
    while ((pic = $('.pics .thumb')[n++])) {
        if (i.attr('id') == $(pic).attr('id'))
            return (n) * 95;
        else continue;
    }
}

function selectCurrentPicture(id) {
    
    //Выбор текущей картинки
    $(id).unbind('mouseover');
    if ($('.prp .pics .thumb').length > 10) {
        var innerPicOffset = getInnerPicOffset($(id));
        var left = 531 - innerPicOffset;
        if (left > 0) left = 0;
        if (width - innerPicOffset < 510)
            left = 974 - width;
        $('.content2 .pics').css('left', left);
        $('.scroll .bar .dott').css('left', -1 * left / speed);
    } else {
        $('.scroll').remove();
    }
    
}

function getScreenResolution(w, h, l) 
{
    var ret = '';
    switch (true) {
        case w == 1920 && h == 1080:
            ret = '1080p';
            break;
        case w == 1280 && h == 720:
            ret = '720p';
            break;
        case w == 640 && h == 960:
            ret = 'iPhone';
            break;
        case w == 1024 && h == 1024:
            ret = 'iPad';
            break;
    }
    if (ret == '')
        if (l == true)
            ret = w + '&nbsp;&times;&nbsp;' + h;
        else 
            ret = w + 'x' + h;
    else {
        ret += l == true ? ret + ', ' + w + '&nbsp;&times;&nbsp;' + h + '' : '';
        
    }
    return ret;
}

function getResolutionParams(n) {
    var ar = new Array();
    switch (n) {
        case '720p':
            ar[0] = 1280;
            ar[1] = 720;
            break;
        case '1080p':
            ar[0] = 1920;
            ar[1] = 1080;
            break;
        case 'iPhone':
            ar[0] = 640;
            ar[1] = 960;
            break;
        case 'iPad':
            ar[0] = 1024;
            ar[1] = 1024;
            break;
        default:
            ar = n.split('x');
            ar[0] = parseInt(ar[0]);
            ar[1] = parseInt(ar[1]);
            break;
    }
    return ar;
}

function apiHref(link) {
    //очистка временной хуйни
    $('#reflections').html('');
    url = $(link).attr('href');
    if (true /*navigator.appName == 'Microsoft Internet Explorer'*/) {
        var form = '<form method="POST" id="openform" action="' + url + '"><input type="hidden" name="resolution" value="' + $(link).attr('resolution') + '" /></form>';
        $('body').append(form);
        $('#openform').submit();
        return false;
    }
    else updateLiveInternetCounter(url);
    
    $('.top .td2').fadeTo('slow', 0.5, function() {});
    scrollTop();
    $.post(
        //Отправление запроса
        '/api' + url, 
        {
            resolution : $(link).attr('resolution')
        }, function (data) {
            var res = $.parseJSON(data);
            switch (res.params.api) {
                case 'wallpapers':
                    responseWallpapers(res);
                    break;
                case 'open':
                    responseOpen(res);
                    break;
            }
            showBanners();
            $('.top .td2').fadeTo('fast', 1, function() {});

    });
    return false;
}

//Определяем какое разрешение показать пользователю
function currentResolution(i) {
    var res, p, delta = -99999, max = 0, cur, w, h, sum, _sum, maxR;
    var needResolution = 'all';
    try {
        if ($('#userRes').attr('value') == 'all' || $('#userRes').attr('value') == undefined) {
            res = i.attr('res').split(',');
            w = screen.width;
            h = screen.height;
            cur = getScreenResolution(w, h);
            for (var n in res) 
            {
                if (res[n] == cur) 
                {
                    needResolution = res[n];
                    break;
                }
                else
                {
                    p = getResolutionParams(res[n]);
                    _sum = p[0] + p[1];
                    sum = w + h - _sum;
                    if (w <= p[0] && h <= p[1])
                    {
                        if (sum > delta)
                        {
                            delta = sum;
                            needResolution = res[n];
                        }
                    } 
                    if (_sum > max)
                    {
                        max = _sum;
                        maxR = res[n];
                    }
                }
            }
            
                /*
            if (p[0] >= screen.width && p[1] >= screen.height) {
                needResolution = getScreenResolution(screen.width, screen.height, false);
                if ($.inArray(needResolution, resolutions) < 0) {
                    needResolution = i.attr('res');
                }
            }
            else 
                needResolution = i.attr('res');
                */
        } else {
            needResolution = $('#userRes').attr('value');
        }
    } catch (err) {
        
    }
    return needResolution == 'all' ? maxR : needResolution;
}
