/*
 *
 *  "galname" initialized in every page controller
 */

//resize thumb

var thumbs = null;
var thumbsScroll = null;
var thumbsize = null;
doResize = function()
{
    h = $(document).height();
    //h = screen.height - 200;
    
    // resize thumbs
    if(thumbsScroll != null)
    {
        thumbsize = parseInt(h * 0.74 * 0.1);

        thumbsScroll.css({'width' : (thumbs.length * (thumbsize + 2)) + "px"})

        thumbs.each(
            function()
            {
                $(this).css({'height': thumbsize + 'px', 'width': thumbsize + 'px'});
            }
        );
    }

    //resize fonts
    newFontSize = parseInt(11 * h / 600);
    $(document.body).css({'fontSize': newFontSize + "px"});

    //resize menu icon
    $('#mainmenuhead').css({'height': h * 0.035 + "px"});

}
initResize = function()
{
    thumbsScroll = $('#photolist .scroll');
    if(thumbsScroll != null)
        thumbs = thumbsScroll.children();

    $(window).resize(doResize);
    doResize();
}
$(document).ready(initResize);

initMainMenu = function()
{
    $('#mainmenucnt').hover(
        function() {
            $(this).addClass('over');
            $('#mainmenublock').show();
        },
        function() {
            $('#mainmenublock').hide();
            $('#mainmenucnt').removeClass('over');
        }
    );
}
$(document).ready(initMainMenu);

initToolbox = function(cnt)
{
    $(cnt).find('.scroll').children().each(
    function() {
        $(this).hover(
            function() {
                $(this).find('.toolbox').animate({'top': '0px'}, 'slow');
            },function() {
                $(this).find('.toolbox').animate({'top': '-30px'}, 'slow');
            });
    });
}

initVToolbox = function(cnt)
{
    $(cnt).hover(
        function() {
            $(this).find('.vtoolbox').stop().animate({'left': '10px'}, 'slow');
        },function() {
            $(this).find('.vtoolbox').stop().animate({'left': '-200px'}, 'slow');
    });
}

showModal = function()
{
    //back
    oBack = document.createElement('DIV');
    oBack.id = 'modalback';
    document.body.appendChild(oBack);

    //back
    oFront = document.createElement('DIV');
    oFront.id = 'modalbody';
    document.body.appendChild(oFront);

    return oFront;
}

dropModal = function()
{
    mb = document.getElementById('modalback');
    mbd = document.getElementById('modalbody');

    mb.parentNode.removeChild(mb);
    mbd.parentNode.removeChild(mbd);
}

showEditGroupForm = function(gid, parentGid)
{
    if(typeof gid == "undefined") gid='';
    if(typeof parentGid == "undefined") parentGid='';

    m = showModal();
    m.innerHTML = 'Подождите, идет загрузка...';

    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        {'cmd': 'getgroupeditform', 'gid': gid, 'pgid': parentGid, 'galname': galname},
        function(res, text)
        {
            if(res)
                m.innerHTML = res;
            else
                m.innerHTML = text;
        },
        true
    );
}

showEditPhotoForm = function(id, gid)
{
    m = showModal();
    m.innerHTML = 'Подождите, идет загрузка...';

    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        {'cmd': 'getphotoeditform', 'id': id, 'gid': gid, 'galname': galname},
        function(res, text)
        {
            if(res)
                m.innerHTML = res;
            else
                m.innerHTML = text;
        },
        true
    );
}

doSavePhoto = function(frm)
{
    var gid = frm.gid.value; //gallery id to store photo
    
    status = document.getElementById('pstatus');
    status.innerHTML = 'Подождите, идет сохранение...';
    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        {
            'cmd':      'savephoto',
            'id':       frm.pid.value,
            'gid':      gid,
            'name':     frm.pname.value,
            'descr':    frm.pdescr.value,
            'photo':    frm.photo,
            'galname':  galname
        },
        function(res, text)
        {
            if(res.success)
            {
                dropModal();

                content  = '<div onclick="loadPhoto(this)" photoid="' + res.id + '" photogid="' + gid + '" photodescr="" photoname="" id="photo' + res.id + '" class="trumb" style="height: ' + thumbsize + 'px; width: ' + thumbsize + 'px; display: none;">';
                content += '<img height="100%" src="/img/gallery/' + galname + '/' + gid + '/prw_' + res.id + '.jpg"/>';
                content += '<div class="toolbox" style="top: -30px;">';
                content += '<a title="Редактировать фото" onclick="showEditPhotoForm(' + res.id + ')" href="javascript:void(0);"><img border="0" src="/tpl/Basic/img/fileedit.png"/></a>';
                content += '<a title="Удалить иллюстрацию" onclick="doDropPhoto(' + res.id + ', \'photo' + res.id + '\')" href="javascript:void(0);"><img border="0" src="/tpl/Basic/img/cross.png"/></a>';
                content += '</div>';
                content += '</div>';

                scroll = $('#photolist .scroll');
                scrollWidth = parseInt(scroll.css('width')) + thumbsize + 2 + "px";
                scroll.css({'width': scrollWidth});
                scroll.prepend(content);
                $('#photo' + res.id).show('slow');
                initToolbox('#photolist');
            }
            else
                status.innerHTML = '<div style="color: red;">Ошибка при сохранении. ' + text + '</div>';
        },
        true
    );
}

doSaveGroup = function(frm)
{
    status = document.getElementById('gstatus');
    status.innerHTML = 'Подождите, идет сохранение...';

    insert = (frm.gid.value == '');

    params = {
        'cmd':      'savegroup',
        'id':       frm.gid.value,
        'pid':      frm.pgid.value,
        'name':     {},
        'descr':    frm.gdescr.value,
        'icon':     frm.gikon,
        'galname':  galname
    };

    gname = document.getElementsByName('gname');
    for(gnlength = gname.length, i=0; i < gnlength; i++)
    {
        input = gname[i];
        params.name[input.getAttribute('lang')] = input.value;
    }

    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        params,
        function(res, text)
        {
            if(res.success)
            {
                frm.gid.value = res.success;

                // prepare content of thumb html
                function getThumbCode(type, gid)
                {
                    content =  '<div class="trumb" id="' + type + 'sgi' + gid + '" style="display: none;">';
                    content += '<a href="/gallery/index.html?s=' + gid + '">';
                    content += '<img src="/img/gallery/' + galname + '/' + gid + '.jpg" border="0"></a>';
                    content += '<div class="toolbox">';
                    content += '<a href="javascript:void(0);" onclick="showEditPhotoForm(null, ' + gid   + ')" title="Добавить иллюстрацию в эту группу"><img src="/tpl/Basic/img/picture--plus.png" border="0"></a>';
                    content += '<a href="javascript:void(0);" onclick="showEditGroupForm(' + gid + ')" title="Редактор галлереи"><img src="/tpl/Basic/img/fileedit.png" border="0"></a>';
                    content += '<a href="javascript:void(0);" onclick="doDropGroup(' + gid + ')" title="Удалить галлерею"><img src="/tpl/Basic/img/cross.png" border="0"></a></div></div>';

                    return content;
                }

                // drop
                dropModal();

                if(!insert) return;
                // add to mod
                $('#subgidlist .scroll').prepend(getThumbCode('m', res.success));
                $('#msgi' + res.success).show('slow');
                initToolbox('#subgidlist');
                // add to page
                scroll = $('#photoscroll .scroll');
                newwidth = parseInt(scroll.css('width'))+154;
                scroll.css({'width': newwidth});
                scroll.prepend(getThumbCode('u', res.success));
                $('#usgi' + res.success).show('slow');
                initToolbox('#photoscroll');
            }
            else
                status.innerHTML = '<div style="color: red;">Ошибка при сохранении. ' + text + '</div>';
        },
        true
    );
}

doDropGroup = function(gid)
{
    if(!confirm('Действительно удалить эту группу?')) return;
    
    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        {'cmd': 'dropgallery','gid': gid, 'galname': galname},
        function(res, text)
        {
            if(res)
            {
                $('#galmenu' + gid).remove(); // /tpl/Basic/gallery/menu.tpl
                $('#msgi' + gid).hide('slow', function() { this.parentNode.removeChild(this); });
                $('#usgi' + gid).hide('slow', function() { this.parentNode.removeChild(this); });
            }
            else
                alert('Удалить галлерею не одалось. Причина ошибки: ' + text);
        },
        true
    );
}

doDropPhoto = function(id, cnt)
{
    if(!confirm('Действительно удалить эту иллюстрацию?')) return;

    JsHttpRequest.query(
        '/pub/ajax/gallery.php',
        {'cmd': 'dropphoto','id': id, 'galname': galname},
        function(res, text)
        {
            if(res)
            {
                ocnt = document.getElementById(cnt);
                $(ocnt).hide('slow', function() { ocnt.parentNode.removeChild(ocnt); });
            }
            else
                alert('Удалить иллюстрацию не одалось. Причина ошибки: ' + text);
        },
        true
    );
}

loadPhoto = function(thumb)
{
    var id = thumb.getAttribute('photoid');
    var gid = thumb.getAttribute('photogid');
    
    var l = $('#pslayer');
    var lp = $('#pspreload');

    //show preloader
    lp.show();

    //preload image
    var cacheimg = document.createElement('IMG');
    
    cacheimg.onload = function()
    {
        setTimeout( function ()
        {

            // set arrow handlers
            $('#moveForward').unbind('click').click( function() { doMoveSmallForvard(thumb); } );
            $('#moveBack').unbind('click').click( function() { doMoveSmallBack(thumb); } );
            $(document).unbind('keydown').keydown(function(e) {
                if(e.keyCode == 39)
                {
                    if(document.getElementById('bigPhotoCnt'))
                        doMoveBigForvard(thumb);
                    else
                        doMoveSmallForvard(thumb);

                    // hide
                    $('#zoomindiv').fadeOut('slow');
                    $('#moveForward').fadeOut('slow');
                    $('#moveBack').fadeOut('slow');
                    $('#moveBigForward').fadeOut('slow');
                    $('#moveBigBack').fadeOut('slow');
                    $('#zoomout').fadeOut('slow');
                }
                else if(e.keyCode == 37)
                {
                    if(document.getElementById('bigPhotoCnt'))
                        doMoveBigBack(thumb);
                    else
                        doMoveSmallBack(thumb);

                    // hide
                    $('#zoomindiv').fadeOut('slow');
                    $('#moveForward').fadeOut('slow');
                    $('#moveBack').fadeOut('slow');
                    $('#moveBigForward').fadeOut('slow');
                    $('#moveBigBack').fadeOut('slow');
                    $('#zoomout').fadeOut('slow');

                }
            });

            $('#zoomin').unbind('click').click(
                function() {
                    showBigPhoto(thumb);
                }
            );

            $('#openinnewwindow').attr('href', '/img/gallery/' + galname + '/' + gid + '/big_' + id + '.jpg');

            // show new image
            lp.hide();
            l.attr({'src': cacheimg.src});
            
        }, 150);
    }
    cacheimg.src = '/img/gallery/' + galname + '/' + gid + '/' + id + '.jpg';
}

loadBigPhoto = function(thumb)
{
    var id = thumb.getAttribute('photoid');
    var gid = thumb.getAttribute('photogid');

    img = document.getElementById('bigPhotoLayer');
    img.style.visibility = 'hidden';
    img.onload = function()
    {
        resizeBigPhoto();
        img.style.visibility = 'visible';
        
        // set arrow handlers
        $('#moveBigForward').unbind('click').click( function() { doMoveBigForvard(thumb); });
        $('#moveBigBack').unbind('click').click( function() { doMoveBigBack(thumb); });

        $('#openinnewwindow').attr('href', img.src);
    }
    img.style.height = '';
    img.style.width = '';
    img.src = '/img/gallery/' + galname + '/' + gid + '/big_' + id + '.jpg';
}

resizeBigPhoto = function()
{
    img = document.getElementById('bigPhotoLayer');
    imgh = img.height; 
    imgw = img.width;
    
    imgcurh = parseInt($(window).height() * 0.8);
    img.style.height = imgcurh + "px";
    img.style.width = parseInt(imgw * imgcurh / imgh) + "px";
}

doMoveSmallForvard = function(thumb)
{
    var next = $(thumb).next().get(0);
    if(next) loadPhoto( next );
}

doMoveSmallBack = function(thumb)
{
    var prev = $(thumb).prev().get(0);
    if(prev) loadPhoto( prev );
}

doMoveBigForvard = function(thumb)
{
    var next = $(thumb).next().get(0);
    if(next)
    {
        loadBigPhoto( next );
        loadPhoto( next );
    }
}

doMoveBigBack = function(thumb)
{
    var prev = $(thumb).prev().get(0);
    if(prev)
    {
        loadBigPhoto( prev );
        loadPhoto( prev );
    }
}

showBigPhoto = function(thumb)
{
    if(document.getElementById('bigPhotoCnt')) return;

    var back = document.createElement('DIV');
    back.id = 'bigPhotoCnt';
    back.style.cssText = 'text-align: center; position: absolute; top: 0px; left: 0px; height: 100%; width: 100%; z-index: 9990; background: #000000; ';
    document.body.appendChild(back);
    $('#bigPhotoCnt').hover(
        function() {
            $('#moveBigForward').fadeIn('slow');
            $('#moveBigBack').fadeIn('slow');
            $('#zoomout').fadeIn('slow');
        },
        function() {
            $('#moveBigForward').fadeOut('slow');
            $('#moveBigBack').fadeOut('slow');
            $('#zoomout').fadeOut('slow');
        }
    ).mousemove(
        function()
        {
            $('#moveBigForward').fadeIn('slow');
            $('#moveBigBack').fadeIn('slow');
            $('#zoomout').fadeIn('slow');
        }
    );

    var prel = document.createElement('DIV');
    prel.style.cssText = 'position: absolute; top: 50%; left: 50%; height: 100px; width: 100px; margin-left: -50px; margin-top: -50px; z-index: 9991; background: #ffffff url(/tpl/Basic/img/preload.gif) no-repeat center center; opacity: 0.6; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0.6); -moz-border-radius: 8px; -webkit-border-radius: 8px;';
    back.appendChild(prel);

    var img = document.createElement('IMG');
    img.id = 'bigPhotoLayer';
    img.style.cssText = 'position: relative; top: 10%; z-index: 9999; margin: 0px auto; visibility: hidden;';
    back.appendChild(img);

    $(window).resize(resizeBigPhoto);
    
    img.onload = function()
    {
        setTimeout(
            function() {
                img.style.visibility = 'visible';
                resizeBigPhoto();
                obvesHTML  = '<div id="moveBigForward"></div><div id="moveBigBack"></div>';
                obvesHTML += '<div style="position: absolute; left: 50%; margin-left: -90px; bottom: 10px; z-index: 9999;" id="zoomout">';
                obvesHTML += '    <img src="/tpl/Basic/img/d/zoomout.png" usemap="#zoomout" border="0">';
                obvesHTML += '    <map name="zoomout">';
                obvesHTML += '        <area coords="100,10,130,40" href="javascript:void(0);" onclick="hideBigPhoto()" title="Уменьшить">';
                obvesHTML += '        <area coords="144,10,174,40" href="/img/gallery/' + galname + '/' + thumb.getAttribute("photogid") + '/big_' + thumb.getAttribute("photoid") + '.jpg" id="openinnewwindow" target="_blank" title="Открыть в новом окне">';
                obvesHTML += '    </map>';
                obvesHTML += '</div>';
                back.innerHTML += obvesHTML;


                // set arrow handlers
                $('#moveBigForward').unbind('click').click( function() { doMoveBigForvard(thumb); } );
                $('#moveBigBack').unbind('click').click( function() { doMoveBigBack(thumb); } );
            },
            200
        );
    }
    var id = thumb.getAttribute('photoid');
    var gid = thumb.getAttribute('photogid');
    img.src = '/img/gallery/' + galname + '/' + gid + '/big_' + id + '.jpg';
}

hideBigPhoto = function()
{
    $(window).unbind('resize', resizeBigPhoto);
    $('#bigPhotoCnt').remove();
}

initMovie = function()
{    
    l1 = $('#mvlayer1');
    l2 = $('#mvlayer2');

    cachesprite = document.createElement('IMG');
    cachesprite.onload = function()
    {
        l2.removeClass('preloader');
        l1.css({'background-image': 'url(/img/presentation/sprite.jpg)'});
        l2.css({'background-image': 'url(/img/presentation/sprite.jpg)'});
        top = 300;
        t = setInterval(
            function() {
                l2.css({
                    'opacity' : '0'
                }).animate({'opacity': '1'}, 3000, 'swing', function() {
                    l1.css({'background-position': '0px -' + top + 'px'});
                    top += 300;
                    if(top >= cachesprite.height) top = 0;
                    l2.css({'background-position': '0px -' + top + 'px', 'opacity': '0'});
                });
            },
            4000
        );
    }
    cachesprite.src = '/img/presentation/sprite.jpg';
}

initSlider = function(cnt, slave, orient)
{
    $(cnt).slider({
        orientation: orient,
        value: orient == 'vertical' ? 100  : 0,
        slide: function(event, ui)
        {

            var sc = $(slave + ' .scroll');

            if(orient == 'vertical')
            {
                perc = 100 - ui.value;
                size = 'height';
            }
            else
            {
                perc = ui.value;
                size = 'width';
            }

            if(sc.css(size) !== 'auto')
            {
                scrollsize = parseInt(sc.css(size));
            }
            else
            {
                scrollsize = parseInt(size == 'height' ? sc.outerHeight() : sc.outerWidth());
            }
            windowsize = parseInt($(slave).css(size));


            if(scrollsize < windowsize) return;
            switch(perc)
            {
                case 0: shift = 0; break;
                case 100: shift = scrollsize - windowsize; break;
                default: shift = (scrollsize - windowsize)*perc/100;
            }

            

            if(orient == 'vertical')
                animparams = {'top': '-' + shift + 'px'};
            else
                animparams = {'left': '-' + shift + 'px'};
            
            sc.stop().animate(animparams, 'slow');
        }
    });
}

doMoveForward = function()
{
    cnt = $('#photolist');
    scroll = $('#photolist .scroll');

    time = scroll.children().length * 250;

    pos = parseInt(scroll.css('width')) - parseInt(cnt.css('width'));

    scroll.stop().animate(
        {'left': "-" + pos + "px"},
        time
    );
}

doMoveBack = function()
{
    cnt = $('#photoscroll');
    scroll = $('#photolist .scroll');

    time = scroll.children().length * 250;

    scroll.stop().animate(
        {'left': '2px'},
        time
    );
}

doMoveStop = function()
{
    scroll = $('#photolist .scroll');
    scroll.stop();
}

doInitSortable = function()
{
    var sortimer = null;
    $('#GALERYMENU').sortable({
        revert: true,
        update: function(event, ui) {
            sortimer = setTimeout(function() {
                arr = $('#GALERYMENU').sortable('toArray');
                var arrToSend = {};
                for(arrlen = arr.length, i=0; i<arrlen; i++)
                {
                    key = parseInt(arr[i].replace('galmenu', ''));
                    value = i;
                    arrToSend[key] = value;
                }
                JsHttpRequest.query(
                    '/pub/ajax/gallery.php',
                    {cmd: 'sortgallery', ord: arrToSend, 'galname': galname},
                    function(res, text)
                    {
                        if(text != '') alert('Сортировка не удалась! Звони 8-067-791-29-63 :)');
                    }
                );
            }, 1000);
        },
        start: function(event, ui)
        {
            if(sortimer != null) clearTimeout(sortimer);
        }
    }).disableSelection();
}
