var html = (document.getElementsByTagName('html').length)?document.getElementsByTagName('html')[0]:null;
var f_current = 0;
var f_window = 0;

// функции для preview
function f_show(index) {
    try {
        // make navigations for this picture
        if (!ms.turned_on) {
            if (pics[f_current]) pics[f_current].tile.className = 'photo-tile';
            pics[index].tile.className = 'photo-tile photo-gray';
        }

        f_current = index;
        f_prev = (index==0)?-1:(index-1);
        f_next = (index==(pics.length-1))?-1:(index+1);
        url = '/foto-images'+pics[index].mountpoint+'/'+pics[index].cache+'-'+pics[index].random_id+'.jpg';

        // init containers
        f_showShadow(f_close);
        f_showLoading();
        _removeNode(f_window); // remove node before drawing next page
        _ac(document.body, f_window = _div({id: 'TB_window'}));

        // start preload image
        imgPreloader = new Image();
        imgPreloader.onload = f_onLoadImage;
        imgPreloader.src = url;
    } catch(e) {
        // nothing here
    }
}

// вызывается, когда загрузилась картинка
function f_onLoadImage() {
    imgPreloader.onload = null; // turn onload off

    // Resizing large images - orginal by Christian Montoya edited by me.
    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;
    var x = w - 150;
    var y = h - 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 + 24;
    TB_HEIGHT = imageHeight + 70;
    if (TB_WIDTH < 300) TB_WIDTH = 300;

    function goPrev(){
        if (f_prev != -1) f_show(f_prev);
    }
    function goNext(){
        if (!f_window) return; // уже закрыли окошко
        if (f_next != -1) f_show(f_next); else f_close();
    }

    // make preview window
    var close_button = _div({id: 'TB_close'}, button(_lz('Закрыть'), 'close', f_close, 'button-close'));
    var caption = _span({id: 'TB_caption', title: pics[f_current].title}, _span({style: {fontSize: '10pt'}}, '' + (f_current+1) + '. '), pics[f_current].filename);
    if (pics[f_current].selected) f_window.style.border = '2px solid #E020C1';

    _ac(f_window, caption);
    _ac(f_window, close_button);
    _ac(f_window, _div({style: {clear: 'both'}}));
    _ac(f_window, _img({id: 'TB_Image', src: url, width: imageWidth, height: imageHeight, onclick: goNext}));

    var buttons_left = _div({id: 'TB_buttons_left'});
    //_ac(buttons_left, _img({src: '/foto/images/blank.gif'}));
    if (f_prev != -1) _ac(buttons_left, button(_lz('Пред.'), 'back-32x32', goPrev, 'button-prev'));
    if (f_next != -1) _ac(buttons_left, button(_lz('След.'), 'next-32x32', goNext, 'button-next'));
    _ac(f_window, buttons_left);

    var buttons_right = _div({id: 'TB_buttons_right'});
    _ac(buttons_right, button(_lz('послать'), 'mail', f.send2friend_one, _lz('Послать другу')));
    if (group.allow_hires == '1')
        _ac(buttons_right, button(_lz('скачать'), 'download', f.downloadsources_one, _lz('Скачать оригинал')));
    //_ac(buttons_right, _img({src: '/foto/images/blank.gif'}));
    if (unknown_load || (logged_in && pics[f_current].client_id==auth.client_id)) {
        //_ac(buttons_right, _lz('Поворот: '));
        _ac(buttons_right, button(_lz('левый'), 'rotate-left', f_rotate270, _lz('Повернуть влево')));
        _ac(buttons_right, button(_lz('правый'), 'rotate-right', f_rotate90, _lz('Повернуть вправо')));
    }
    _ac(f_window, buttons_right);

    // capture keys
    document.onkeydown = function(e) {
        if (e == null) { // ie
            keycode = event.keyCode;
        } else { // mozilla
            keycode = e.which;
        }
        if (keycode == 27) f_close();
        if (keycode == 188) goPrev();
        if (keycode == 190) goNext();
        if (keycode == 32) {
            if (ms.turned_on) {
                ms.select_photo(f_current);
                if (pics[f_current].selected) {
                    f_window.style.border = '2px solid #E020C1';
                } else {
                    f_window.style.border = '2px solid #CCC';
                }
                setTimeout(goNext, 500);
            } else goNext();
        }
        return false;
    };

    // resize and show image
    f_window.style.marginLeft = '-' + parseInt((TB_WIDTH / 2),10) + 'px';
    f_window.style.width = TB_WIDTH + 'px';
    if (typeof document.body.style.maxHeight != 'undefined') { // if not IE6
        f_window.style.marginTop = '-' + parseInt((TB_HEIGHT / 2),10) + 'px';
    }
    f_window.style.display = 'block'; // for safari we using css instead of show
    caption.style.width = (TB_WIDTH - close_button.clientWidth - 23) + 'px';
    f_hideLoading();

    if (f_next != -1) { // pre-caching next image
        nextImagePreloader = new Image();
        nextImagePreloader.src = '/foto-images/'+pics[f_next].cache+'-'+pics[f_next].random_id+'.jpg';
    }
}

function f_showShadow(callback) {
    if (typeof f_ovr == 'undefined') { // if not shadowed yet
        if (typeof document.body.style.maxHeight === 'undefined') { // add iframe to hide select elements in ie6
            document.body.style.height = '100%';
            document.body.style.width = '100%';
            if (html) html.style.overflow = 'hidden';
            _ac(document.body, f_hideselect = _iframe({id: 'TB_HideSelect'}));
        }
        _ac(document.body, f_ovr = _div({id: 'TB_overlay'}));
        if (callback) f_ovr.onclick = callback;
    }
}
function f_hideShadow() {
    if (typeof f_hideselect != 'undefined') {
        document.body.style.height = 'auto';
        document.body.style.width = 'auto';
        if (html) html.style.overflow = '';
        _removeNode(f_hideselect);
        delete f_hideselect;
    }
    if (typeof f_ovr != 'undefined') { // if shadowed
        _removeNode(f_ovr);
        delete f_ovr;
    }
}

var f_loading = _div({id: 'TB_load'}, _img({src: '/foto/images/loading.gif'}));
function f_showLoading() {
    _ac(document.body, f_loading); // add 'loading' image
}
function f_hideLoading() {
    _removeNode(f_loading);
}


function f_scroll(index) {
    var pic_top = pics[index].tile.offsetTop;
    var pic_height = pics[index].tile.clientHeight;
    var de = document.documentElement;
    var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
    var s = window.pageYOffset || self.pageYOffset || (de&&de.scrollTop) || document.body.scrollTop;
    var top_diff = pic_top - s;
    var bottom_diff = s + h - pic_top - pic_height;
    if (top_diff<0) de.scrollTop = pic_top;
    if (bottom_diff<0) de.scrollTop = pic_top - h + pic_height;
}

function f_close() {
    document.onkeydown = null;
    f_hideLoading();
    f_hideShadow();
    f_scroll(f_current);
    _removeNode(f_window);
    f_window = 0;
    return false;
}

// rotate
// -----------------------------------------------------------------------------------------------------
function f_rotate90() {  // поворот 90 градусов
    document.onkeydown = null;
    _removeNode(f_window);
    f_showLoading();
    do_ajax(null, 'action=rotate&degrees=90&index=' + f_current + '&list=' + pics[f_current].random_id);
}
function f_rotate270() {  // поворот 270 градусов
    document.onkeydown = null;
    _removeNode(f_window);
    f_showLoading();
    do_ajax(null, 'action=rotate&degrees=270&index=' + f_current + '&list=' + pics[f_current].random_id);
}

function _removeNode(node) { // для грохания самого объекта
    if (node.parentNode) node.parentNode.removeChild(node);
}

