$(function(){
    
    /* ГЛАВНОЕ МЕНЮ */
    /*
    $('#menu1st').mouseenter(function(){
        $('#menu1st li').not('#menu2nd li').hover(function(){
            showSubMenu($(this));
        })
    }).mouseleave(function(){
        showSubMenu($('#menu1st li.active_static'));
    });

    showSubMenu = function(obj)
    {
        $('#menu2nd ul.submenu_active').removeClass('submenu_active');
        $('#menu1st li.active').not('#menu2nd li').removeClass('active');

        $(obj).addClass('active');
        $('#menu2nd ul.submenu_source_' + (obj).attr('target')).addClass('submenu_active');
    }*/
    
    /* /ГЛАВНОЕ МЕНЮ */
    
    /* menu popup*/
    
    mPopup_Interval_in  = 250;
    mPopup_Interval_out = 250;
    
    mPopup_Act_Interval     = 500;
    mPopup_Act_Interval_Out = 500;
    
    
    mPopup_Current     = null;
    mPopup_PrevCurrent = null;
    
    mPopup_TimerIn   = null;
    mPopup_TimerOut  = null;
    mPopup_Act_Timer = null;
    
    mPopup_Obj = null;
    mPopup_ObjHeight = 0;
   
    $('#menu2nd li').hover(
        function(){
            mPopup_Current = $(this);
            mPopup_Act_Timer = setTimeout(mPopupAction, mPopup_Act_Interval);
        },
        function(){
            mPopup_Current = null;
            mPopup_Act_Timer = setTimeout(mPopupAction, mPopup_Act_Interval_Out);
        }
    );
        
    $('#menu_pop_up_container .one').hover(function(){
        mPopup_Current = mPopup_PrevCurrent;
        clearTimeout(mPopup_Act_Timer);
    }, function(){
        mPopup_Current = null;
        mPopup_Act_Timer = setTimeout(mPopupAction, mPopup_Act_Interval_Out);

    })
    
        
    mPopupAction = function()
    {
        
        if ($(mPopup_PrevCurrent).attr('id:')!=$(mPopup_Current).attr('id:'))
        {
            clearTimeout(mPopup_Act_Timer);
            
            if (mPopup_Current) //Показываем менюшку
            {
                mPopup_Obj = $('#menu_pop_up_container #pop_up_' + $(mPopup_Current).attr('id:'));
               
                if ($(mPopup_Obj).html())
                {
                    
                    
                    if (mPopup_PrevCurrent == null)
                    {
                        
                        mPopup_ObjHeight = $(mPopup_Obj).height();
                        $(mPopup_Obj).css('height', '0px');
                        $(mPopup_Obj).show();
                        $(mPopup_Obj).animate({height:mPopup_ObjHeight}, mPopup_Interval_in, function(){
                            $(this).css('height', 'auto');
                        });
                    }
                    else
                    {
                        $('#menu_pop_up_container .one').css('height', 'auto').hide();

                        mPopup_ObjHeight = $(mPopup_Obj).height();
                        $(mPopup_Obj).css('height', '0px');
                        $(mPopup_Obj).show();
                        $(mPopup_Obj).animate({height:mPopup_ObjHeight}, mPopup_Interval_in, function(){
                            $(this).css('height', 'auto');
                        });

                    }
                }
                else
                {
                    $('#menu_pop_up_container .one').animate({height:0}, mPopup_Interval_out, function(){
                        $('#menu_pop_up_container .one').css('height', 'auto').hide();
                    });
                }

            }
            else //Убираем менюшку
            {
                $('#menu_pop_up_container .one').animate({height:0}, mPopup_Interval_out, function(){
                    $('#menu_pop_up_container .one').css('height', 'auto').hide();
                });
            }
            
            mPopup_PrevCurrent = mPopup_Current;
        }
        
        
     }
   
    /* /menu popup*/
    
    /* ЗАКЛАДКИ */
    $.each($('.tabs-container'), function(i,e){
        $(e).children('.body').html($(e).children('.tabs').children('.active').children('.content').html());
    });
    $('.tabs-container .tabs .tab .title').click(function(){
        $.each($(this).parent().parent().parent().children('.tabs').children('.tab'), function(i,e){
            $(e).removeClass('active');
        });
        $(this).parent().addClass('active');
        $(this).parent().parent().parent().children('.body').html($(this).parent().children('.content').html());
        
        
        
    });
    
    /* /ЗАКЛАДКИ */
    
    /* ПОДВАЛ */
    
    /* ДЕНЬ В ИСТОРИИ */
    
        $('#footer .history_day').click(function(){
            window.location.replace($(this).children('a').attr('href'));
        });
        $('#footer .tabs-container .tabs .tab .title').click(function(){
            $('#footer .history_day').click(function(){
                window.location.replace($(this).children('a').attr('href'));
            });
        });
        

    /* /ДЕНЬ В ИСТОРИИ */
        
    
    /* /ПОДВАЛ */
    
    /* листалка для голосований */
    $('.vote_informer .mid_listalka #scroll_right').click(function(){
        actBlock = $('.vote_informer').parent().find('.display_block');
        $(actBlock).removeClass('display_block');
        nextBlock = $(actBlock).next();
        if (!$(nextBlock).hasClass('vote_informer')) {
            nextBlock = $('.vote_informer').first();
        }
        $(nextBlock).addClass('display_block');
    });
    
    // Открытие формы логинезации
    $('#enter,.close,#expert_enter').click(function () {
        $("#avtoriz,#avtoriz_bg").toggle();
        $("#avtoriz").css('top', $(window).scrollTop()+210+'px');
    });
    
    // переключение табо в поп ап регистрации
    $('#sign-up').click(function () {
        sign_up_in('up');
    });
    $('#sign-in').click(function () {
        sign_up_in('in');
    });
    
    // показывать пароль при регистрации
    $('#login-show-pass').showPassword('.login-checker', {
        text: 'Показать пароль',
        className: 'showpass',
        name: 'showpass'
    });
    
    // определяем высоту страници
    $("#avtoriz_bg").height($("body").innerHeight());

    $('a.selAll').click(function() {
        $('.deliveryCheckbox').attr('checked', 'checked');
    });
    $('a.unselAll').click(function() {
        $('.deliveryCheckbox').attr('checked', '');
    });
    
    // рег блогера
    addAvatarWindow = $('#add_avatar_window').html();
    $('body').prepend('<div id="add_avatar_window">'+addAvatarWindow+'</div>');

    $('#add_avatar_window .close').click(function(){
        $('#add_avatar_window').hide('slow');
        $("#avtoriz_bg").toggle();
        jcrop_api.destroy();
        $('#imgSendSubmit').html('');
    });
    
    /* scroller */
    ubr_scroller_locked = false;
    ubr_scroller_scroll = function (direction, who)
    {
        if (!ubr_scroller_locked) {
            ubr_scroller_locked = true;
            scrollEasing = 'swing';

            scrollFactor = direction == 'left' ? -1 : 1;
            ab_parent = $(who).parent('.ubr_scroller');
            scroller = $(ab_parent).children('.ubr_scroller_images');
            tdPadding = parseInt($(scroller).find('td').css('padding-right').replace("px", ""));
            tdWidth = parseInt($(scroller).find('td').css('width').replace("px", ""));
            scrollerWidth = $(scroller).width();
            currentPosition = $(scroller).scrollLeft();
            tableWidth = $(scroller).children('table').width();
            tr = $(scroller).find('tr');
            pixelsToScroll = scrollerWidth + tdPadding;

            // Определяем с какой скоростью прокручивать в зависимости от видимой области
            scrollSpeed = pixelsToScroll > 400 ? 1500 : 1000;

            numOfElements = parseInt(scrollerWidth / (tdWidth + tdPadding));

            newPosition = currentPosition + ( pixelsToScroll * scrollFactor);
            if (newPosition < 0)
            {
                newPosition = 0;
            }

            //Проскок вправо
            if ((scrollFactor > 0) && (newPosition + tdPadding >= tableWidth)) {
                for (i=0; i<numOfElements; i++)
                {
                   $(tr).append('<td class="ubr_scroller_tmp_row">' + $(tr).find('td:eq('+i+')').html() + '</td>');
                }
                $(scroller).animate({scrollLeft: newPosition}, scrollSpeed, scrollEasing, function(){
                    $(scroller).scrollLeft(0);
                    $('.ubr_scroller_tmp_row').remove();
                    ubr_scroller_locked = false;
                });
            } else
            //Проскок влево
            if ((scrollFactor < 0) && (currentPosition == 0)) {
                lastTd = $(tr).find('td:last');
                for (i=numOfElements; i>0; i--)
                {
                   $(tr).prepend('<td class="ubr_scroller_tmp_row">' + $(lastTd).html() + '</td>');
                   lastTd = $(lastTd).prev();
                }

                currentPosition = scrollerWidth;
                $(scroller).scrollLeft(currentPosition);
                newPosition = currentPosition + ( pixelsToScroll * scrollFactor);

                $(scroller).animate({scrollLeft: newPosition}, scrollSpeed, scrollEasing, function(){
                    $('.ubr_scroller_tmp_row').remove();
                    $(scroller).scrollLeft(tableWidth - (scrollerWidth + tdPadding));
                    ubr_scroller_locked = false;
                });

            //Обыкновенный скроллинг
            } else {
                //Контроль точности остановки скролинга (актуально для крайних элементов)
                while(newPosition>(tableWidth-pixelsToScroll))
                {
                    newPosition = newPosition - (tdPadding/2);
                }
                $(scroller).animate({scrollLeft: newPosition}, scrollSpeed, scrollEasing, function(){
                    ubr_scroller_locked = false;
                });
            }
        }

    }

    //Включаем кнопки скроллинга влево-вправо
    $('.ubr_scroller_left').click(function(){
        ubr_scroller_scroll('left', $(this));
    });
    $('.ubr_scroller_right').click(function(){
        ubr_scroller_scroll('right', $(this));
    });

    //Убираем кнопки скроллинга в случае, если елементов не больше чем может вместиться в область
    $('.ubr_scroller').each(function(index, element) {
        scrollerElementsCount = $(element).find('.ubr_scroller_images tr td').size();
        scroller = $(element).children('.ubr_scroller_images');
        tdPadding = parseInt($(scroller).find('td').css('padding-right').replace("px", ""));
        tdWidth = parseInt($(scroller).find('td').css('width').replace("px", ""));
        scrollerWidth = $(scroller).width();
        numOfElements = parseInt(scrollerWidth / (tdWidth + tdPadding));
        if (scrollerElementsCount <= numOfElements) {
            $(element).children('.ubr_scroller_left').unbind('click').addClass('nocursor').addClass('nobg');
            $(element).children('.ubr_scroller_right').unbind('click').addClass('nocursor').addClass('nobg');
        }
    });

    /* /scroller */
    
    //ubr tabs
    $('.ubr_tabs ul li').click(function(){
        if (!$(this).hasClass('disabled')){
            $(this).parent('ul').children('li').removeClass('active');
            $(this).addClass('active');
            $(this).parent('ul').children('li').each(function(index, element){
                $('#' + $(element).attr('for:')).hide();
            })
            $('#' + $(this).attr('for:')).show();
            eval($(this).attr('callback:'));
        }
    });
    $('.ubr_tabs ul li.active').click();
    
    //dropdown эксперты
    $('.dropdownSelector').each(function(index, element){
        if ($(element).children('ul').children('li').length < 1)
        {
            $(element).remove();
        }
    });
    $('.dropdownSelector').hover(function(){
        $(this).children('ul').width($(this).parent().width());
        if($(this).children('ul').width()<200)
        {
            $(this).children('ul').width(200);
        }
        $(this).children('ul').show()
    }, function(){
        $(this).children('ul').hide();
    })
    
    
    
    /**
     * Фото-галерея
     */

   $.offset = 87;

   $('.galleryline .one_prev').click( function () {
       $('.galleryline .one_prev').removeClass('one_prev_act');
       $(this).addClass('one_prev_act');
       window.location = $('#gallery_path').html() + '/img' + $(this).children('img').attr('name') + '/scroll' + $('.galleryline').scrollLeft();
   });

   $('#prev_photo').click(function(){
      scrollL = $('.galleryline').scrollLeft();
      scrollR = scrollL + $.offset * 6;
      prevPhoto = ($('.one_prev_act').children('img').attr('name')*1-1);
      if ( (prevPhoto * $.offset) <= scrollL ) {
          scrollL = prevPhoto * $.offset;
      }
      window.location = $('#gallery_path').html() + '/img' + prevPhoto + '/scroll' + scrollL;
   });

   $('#next_photo').click(function(){
      $('.gallery_big_image img').click();
   });




   $('.gallery_big_image img, .gallery_big_image div, .gallery_big_image').click(function () {
      scrollL = $('.galleryline').scrollLeft();
      scrollR = scrollL + $.offset * 6;
      nextPhoto = ($('.one_prev_act').children('img').attr('name')*1+1);
      if ( (nextPhoto * $.offset) >= scrollR ) {
         scrollL = nextPhoto * $.offset;
      }

      if (scrollL+10 >= $('.galleryline').children('table').width() ) {
        nextPhoto = 0;
        scrollL = 0;
      }

      window.location = $('#gallery_path').html() + '/img' + nextPhoto + '/scroll' + scrollL;
   })
    $('.gallery_big_image div').height($('.gallery_big_image img').height());


    if ($.browser.msie) {
            $.delayForScroller = 5;
            $.sizeForScroll = 10;
        } else {
            $.delayForScroller = 15;
            $.sizeForScroll = 2;
        }
    
    $('#gallery_scroll_right').hover(function(){
        stopMove();
        $.timer = setInterval('moveAreaR();', $.delayForScroller);
    }, function(){stopMove()} );

    $('#gallery_scroll_left').hover(function(){
        stopMove();
        $.timer = setInterval('moveAreaL();', $.delayForScroller);
    }, function(){stopMove()} );
    
    //$('#gallery_scroll_left, #gallery_scroll_right').hover(false, function(){stopMove()} );

    $('img.social').hover(
        function(){
            $.old = $(this).attr('src');
            $.url = $.old.substr(0, $.old.length-4) + '_active.gif';
            $(this).attr('src', $.url);
        },
        function (){
            $(this).attr('src', $.old);
        }
    );
    
    // на разводной топ тем смена новостей
    $(function(){
        $('.themes-box .theme-imgs .one-img').hover(function(){
            $('.one-img').removeClass('one-img_active');
            $(this).addClass('one-img_active');
            $('.theme-titles').html($(this).children('.display_none').html());

        }, function(){})

    })

});



//Галерея

function moveAreaR() {
    $('.galleryline').scrollLeft($('.galleryline').scrollLeft()+$.sizeForScroll);
    initScrollButtons ();
}
function moveAreaL() {
    $('.galleryline').scrollLeft($('.galleryline').scrollLeft()-$.sizeForScroll);
    initScrollButtons ();
}

function stopMove() {
    clearInterval($.timer);
    delete $.timer;
}

function initScrollButtons (){
   if ($('.galleryline').scrollLeft() == 0) {
       $('#gallery_scroll_left').removeClass('gallery_scroll_left');
       stopMove();
   } else {
       $('#gallery_scroll_left').addClass('gallery_scroll_left');
   }
   
   if ($('.galleryline').scrollLeft() == ( $('.galleryline table').width() - $('.galleryline').width() ) ) {
       $('#gallery_scroll_right').removeClass('gallery_scroll_right');
       stopMove();
   } else {
       $('#gallery_scroll_right').addClass('gallery_scroll_right');
   }
}

// голосовалка с информера
function doVote(form)
{
    a = $(form).find('input:checked').val();
    q = $(form).children('input').val();
    if (a && q)
    {
        $.post("/ajax/dovote",
            {a: a, q: q},
            function(json) {
                results_table = $(form).parent().children('table.vote_results');
                $(results_table).show();
                $(form).remove();
                json = eval(json);
                count = json.count;
                $('#overall'+q).text('Проголосовало всего: '+count);
                answers = json.answers;
                $('table.vote_results .vote_res_digits').each(function(index, element){
                    votes = answers[$(element).attr('for_answer:')];
                    percent = ((votes/count*100)+'').replace(/\.\d+/, '');
                    $(element).text(percent + '% (' + votes + ')');
                    $(element).next().find('div.vote_rate_line').css('width', percent+'%');
                })
            }, 'json'
        );
    }

    return false;
}

// голосовалка со страници
function doVoteBig(form)
{
    tbl = $(form).parent('table');

    q = $(tbl).attr('for:');
    a = $(tbl).find('input:checked').val();

    if (a && q)
    {
        $.post("/ajax/dovote",
            {a: a, q: q},
            function(json) {

                tbl.find('.vote_please').hide();
                tbl.find('.results').show();
                
                json = eval(json);
                count = json.count;
                answers = json.answers;

                $(tbl).find('.results b').each(function(index, element){
                    votes = answers[$(element).attr('for:')];
                    percent = votes/count*100;
                    $(element).text(percent.toFixed(2)+'% (' + votes + ')');
                    $(tbl).find('#rate_line_big_'+$(element).attr('for:')).css('width', percent.toFixed(0)+'%');
                    $('#want_vote_'+q).remove();
                    $(tbl).find('.overall').text(count);
                    $(tbl).find('.lasttd').append('<div class="results"><strong>(Ваш голос учтен)</strong></div>');
                })
            }, 'json'
        );
    }

    return false;
}

// переключение табов в поп апе залогиневания
function sign_up_in (way)
{

    if (way == 'up')
    {
        a_close = 'up';
        a_open  = 'in';
    }
    else
    {
        a_open  = 'up';
        a_close = 'in';
    }

    $('#sign-' + a_open).removeClass('active-tab');
    $('#sign-' + a_close).addClass('active-tab');
    
    $('.form-' + a_open).removeClass('active-tab');
    $('.form-' + a_close).addClass('active-tab');
}

// --- рег блогера ---
function submitAvatarForm()
{
    origAction = $('#reg_form').attr('action');
    origTarget = $('#reg_form').attr('target');

    $('#reg_form').attr('target', 'imgSendSubmit');
    $('#reg_form').attr('action', '/ajax/uploadavatar');

    $('#reg_form').submit();

    $('#reg_form').attr('target', origTarget);
    $('#reg_form').attr('action', origAction);
}


formValidation = true;

function onChangeAvatar()
{
    disableValidation();
    submitAvatarForm();
    enableValidation();
    echoImgFlg = setInterval(echoImg,500);
}



function disableValidation()
{
    formValidation = false;
}
function enableValidation()
{
    formValidation = true;
}

function setCropCoords(coords)
{
        rxGlobal = 100 / coords.w;
        ryGlobal = 100 / coords.h;
        coordsGlobal = coords;

}

function cropApply()
{
    //PreviewSet
    $('.avatar_mother img').remove();
    $('.avatar_mother').append('<img src="' + $('#cropbox').attr('src') + '" alt="preview" id="avatarCropImg" />');

    $('#avatarCropImg').css({
            width: Math.round(rxGlobal * $('#cropbox').width()) + 'px',
            height: Math.round(ryGlobal * $('#cropbox').height()) + 'px',
            marginLeft: '-' + Math.round(rxGlobal * coordsGlobal.x) + 'px',
            marginTop: '-' + Math.round(ryGlobal * coordsGlobal.y) + 'px'
    });

    $('#avatar_x').val(coordsGlobal.x);
    $('#avatar_y').val(coordsGlobal.y);
    $('#avatar_w').val(coordsGlobal.w);
    $('#avatar_h').val(coordsGlobal.h);
    $('#avatar_ow').val($('#cropbox').width());
    $('#avatar_oh').val($('#cropbox').height());
    $('#avatar_name').val($('#cropbox').attr('src'));
    
    $('#add_avatar_window').hide('slow');
    $("#avtoriz_bg").toggle();
    jcrop_api.destroy();
    $('#imgSendSubmit').html('');
}

function changeDisplayName()
{
    nick    = $('input[name=nick]').val();
    name    = $('input[name=name]').val();
    surname = $('input[name=surname]').val();
    
    pos     = $('#display_name').val();

    str = '<option value="1" ' + (pos == 1 ? 'selected="selected"' : '') + '>' + nick + '</option>';
    if (name != '')
        str = str + '<option value="2" ' + (pos == 2 ? 'selected="selected"' : '') + '>' + name + '</option>';
    
    if (surname != '')
        str = str + '<option value="3" ' + (pos == 3 ? 'selected="selected"' : '') + '>' + surname + '</option>';
    
    if (surname != '' && name != '')
    {
        str = str + '<option value="4" ' + (pos == 4 ? 'selected="selected"' : '') + '>' + name + ' ' + surname + '</option>';
        str = str + '<option value="5" ' + (pos == 5 ? 'selected="selected"' : '') + '>' + surname + ' ' + name + '</option>';
    }
    
    $('#display_name').html(str);
}

function insNick(val)
{
    if ($('input[name=nick]').val() == '')
    {
        $('input[name=nick]').val(val);
        changeDisplayName();
    }
}

function echoImg()
{
    sContent = document.getElementById('imgSendSubmit').contentWindow.document.documentElement;

    ImageName = $(sContent).contents().find('span').text();

    if (ImageName)
    {
        if (ImageName=='error')
        {
            clearInterval(echoImgFlg);
        } else {
            clearInterval(echoImgFlg);

            $("#avtoriz_bg").show();

            $("#add_avatar_window").css('top', $(window).scrollTop()+130+'px');
            
            $('#add_avatar_window .img img').remove();
            $('#add_avatar_window .img').append('<img src="http://img.ubr.ua/tmp/'+ImageName+'" align="absmiddle" alt="preview" id="cropbox" />');

            $('#cropbox').load(function(){

                $('#add_avatar_window').show('slow', function(){

                    origWidthAvatar = $('#add_avatar_window .img img').width();
                    origHeightAvatar = $('#add_avatar_window .img img').height();

                    avatar_max_width = $('#add_avatar_window .img').innerWidth();
                    avatar_max_height = $('#add_avatar_window .img').innerHeight();

                    $('#avatar_resized_koef').remove();

                    if ((origWidthAvatar > avatar_max_width) || (origHeightAvatar > avatar_max_height))
                    {

                       if (origWidthAvatar > origHeightAvatar)
                       {
                           $('#add_avatar_window .img img').width(avatar_max_width);
                           avatar_height = $('#add_avatar_window .img img').height();
                           if (avatar_height > avatar_max_height)
                           {
                               $('#add_avatar_window .img img').height(avatar_max_height);
                               $('#add_avatar_window .img img').width('auto');
                           }
                       }
                       else
                       {
                           $('#add_avatar_window .img img').height(avatar_max_height);
                           avatar_width = $('#add_avatar_window .img img').width();
                           if (avatar_width > avatar_max_width)
                           {
                               $('#add_avatar_window .img img').width(avatar_max_width);
                               $('#add_avatar_window .img img').width('auto');
                           }
                       }
                       
                       $('#reg_form').append('<input type="hidden" name="avatar_resized_koef" value="' + origWidthAvatar / $('#add_avatar_window .img img').width() + '" id="avatar_resized_koef" />');
 
                    }


                    jcrop_api = $.Jcrop('#cropbox');
                    jcrop_api.setOptions({
                            bgColor:     'black',
                            bgOpacity:   .7,
                            aspectRatio: 1,
                            minSize: [10, 10],
                            onChange: setCropCoords,
                            onSelect: setCropCoords
                        });
                    

                    $('.jcrop-holder').css('margin-top', ($('#add_avatar_window .img').height()/2 - $('#add_avatar_window .img img').height()/2 ) );
                    
                    jcrop_api.setSelect([ 0, 0, 100, 100 ]);
                    

                    

                });


                

            });


        }
    }
}
// --- /рег блогера ---
