$(function() {
    $('.photo_thumb a').live('click', function() {
        $(this).blur();
        showImg($(this).attr('num'), $(this).attr('href'), $(this).attr('width'), $(this).attr('height'));
        return false;
    });
    
    $('#gallery_image .img, #gallery_image .next').live('click', function() {
        var next = gallery[current_img] ? gallery[current_img] : gallery[0];
        showImg(next[0], next[1], next[2], next[3]);
    });
    
    $('#gallery_image .prev').live('click', function() {
        var next = gallery[current_img - 2] ? gallery[current_img - 2] : gallery[total - 1];
        showImg(next[0], next[1], next[2], next[3]);
    });

    $(window).keypress(function(e) {
        if ($('#gallery_image:visible').length) {
            if (e.keyCode == 39) { $('#gallery_image .next').click(); }
            if (e.keyCode == 37) { $('#gallery_image .prev').click(); }
        }
    });
    
    $(window).resize(function() { setImageSize(); });
    
    $('.gallery_block .paginator a').live('click', function() {
        $(this).blur();
        var href = location.href;
        href = href.replace(/\?.+|\#.+/gi, '');
        $.address.value('/'+$(this).attr('href'));
        return false;
    });
    
    $.address.change(function(e) {
        var hash = e.value;
        var page = getVariable('page', hash);
        var image = getVariable('image', hash);

        if (page) {
            var href = location.href;
            href = href.replace(/\?.+|\#.+/gi, '');
            $.get(href, {
                ajax: true,
                page: page
            }, function(response){
                $('#gallery_' + gallery_id).html(response);
            });
        }
        
        if (image) {
            var next = gallery[image - 1] ? gallery[image - 1] : gallery[0];
            showImg(next[0], next[1], next[2], next[3]);
        }
    });
});

var current_img = 1;

function showImg(num, img, width, height) {
    current_img = num;

    var win_top = $(window).scrollTop();

    var page = getVariable('page', location.hash);    
    if (!page) page = 1;

    $.address.value('/?page='+page+'&image='+num);
    
    $('#num').text(current_img);

    if ($("#gallery_image:visible").length) {
        var tbl_height = $('#gallery_image table').height();
        
        $('#gallery_image .img').attr('src', img).width(width).height(height).attr('or_width', width).attr('or_height', height).hide();
        
        $('#gallery_image table').height(tbl_height);
        
        $('#gallery_image .img').load(function() {
            setImageSize();
            $('#gallery_image table').height('auto');
            $('#gallery_image .img').stop().show();
        });
    }
    else {
        $("#gallery_image").modal({
            focus: true,
            opacity: 50,
            close: true,
            overlayClose: true,
            modal: true,
            escClose: true,
            autoPosition: false,
	    overlayId: "simplemodal-overlay-gallery",
	    containerId: "simplemodal-container-gallery",
	    dataId: "simplemodal-data-gallery",
            onShow: function(dialog){
                $('.simplemodal-wrap').css({
                    overflow: 'hidden'
                });

                $(window).scrollTop(win_top);

                var top = $(window).scrollTop() + 50;
                $('#simplemodal-container-gallery').css('top', top);

                $('#gallery_image .img').attr('src', img).attr('width', width).attr('height', height).attr('or_width', width).attr('or_height', height);
                
                setImageSize();
            },
            onClose: function(dialog) {
                var hash = location.hash.replace(/\#/gi, '');
		hash = hash.replace(/\&image=\d+/gi, '');
                $.address.value(hash);
                $.modal.close();
            }
        });
    }
}

function setImageSize() {
    var or_width = parseInt($('#gallery_image .img').attr('or_width'));
    var or_height = parseInt($('#gallery_image .img').attr('or_height'));
    
    // текущая ширина картинки
    var cur_img_width = $('#gallery_image .img').width();
    
    // разница между шириной контейнера и картинкой
    var razn_width = 102;
    
    // максимальная ширина картинки для окна
    var max_img_width = $(window).width() - razn_width;
    //if (max_img_width < 200) return false;
    //else if (cur_img_width < 300) max_img_width = cur_img_width;
   
    // текущая высота картинки
    var cur_img_height = $('#gallery_image .img').height();
    
    // разница между высотой контейнера и картинкой
    var razn_height = 49;
    
    // максимальная высота картинки для окна
    var max_img_height = $(window).height() - razn_height;
    if (max_img_height < 200) return false;
    
    // вычисляем соотношение сторон
    var p = cur_img_width / cur_img_height;
    
    if (or_width + 100 < max_img_width) {
        $('#gallery_image .img').width(or_width);
        $('#simplemodal-container-gallery').width(or_width + razn_width);

        $('#gallery_image .img').height(or_height);
        $('#simplemodal-container-gallery').height(or_height + razn_height);
        
        var left = ($(window).width() - $('#simplemodal-container-gallery').width()) / 2 - 13;
        $('#simplemodal-container-gallery').css('left', left);
        
        return false;
    }
    
    // горизонтальные фотки
    var new_img_width = max_img_width - 100;

    var p = cur_img_width / new_img_width;
    cur_img_height = cur_img_height / p;
    
    $('#gallery_image .img').width(new_img_width);
    $('#simplemodal-container-gallery').width(new_img_width + razn_width);

    $('#gallery_image .img').height(cur_img_height);
    $('#simplemodal-container-gallery').height(cur_img_height + razn_height);
    
    cur_img_width = new_img_width;
    
    // вертикальные фотки
    /*if (cur_img_height + 100 > max_img_height) {
        var new_img_height = max_img_height - 100;

        var p = cur_img_height / new_img_height;
        cur_img_width = cur_img_width / p;

        $('#gallery_image .img').height(new_img_height);
        $('#simplemodal-container-gallery').height(new_img_height + razn_height);
        
        $('#gallery_image .img').width(cur_img_width);
        $('#simplemodal-container-gallery').width(cur_img_width + razn_width);
    }*/
    
    var left = ($(window).width() - $('#simplemodal-container-gallery').width()) / 2 - 13;
    $('#simplemodal-container-gallery').css('left', left);
}

