$(function () {    
    $('#serviceholder li').click(_selectService);
    $('#serviceholder ul').first().css('z-index', 30).show();
    $('#btnback').click(_backOneLevel);

    var _columnWidth = $('#serviceholder ul').first().width() + 1;
    var _columns = 1;
    var _currentLevel = 1;
    var _currentLI;

    $(window).resize(_resizeContainer).trigger('resize');
   
    _restorePosition();
    _setHeight();

    function _restorePosition() {        
        if ($('#serviceid').val()) {
            var $li = $('li.service[data-service-id="' + $('#serviceid').val() + '"]');
            $($li.parents('li').get().reverse()).trigger('click');
            
            if ($li.length > 0) {
                var $parent = $li.parents('li:first');
                if ($parent.length === 0)
                    $parent = $li;
                var scroll = $parent.position().top - $('#servicecontainer').height() / 2;
                if (scroll < 0)
                    scroll = 0;

                $('#servicecontainer').scrollTop(scroll);
            }
            if (!$li.hasClass('endpoint'))
                $li.trigger('click');
            $('#serviceid').val('');
            $('#typeid').val('');
        }
    }

    function _selectService(event) {        
        var $li = $(this);
        var $parent = $li.parents('ul:first');
        var $ul = $li.find('ul:first');

        event.stopPropagation();
        $li.siblings().removeClass('selected').find('h3').removeClass('selected');
        $li.children().removeClass('selected').find('h3').removeClass('selected');

        $('ul:visible', $li.siblings()).hide();
        $('ul:visible', $li.children()).hide();
        $li.addClass('selected').find('h3:first').addClass('selected');


        //Если мы на последнем уровне - отпавляем запрос на создание заявки
        if ($li.find('ul').length == 0) {
            $('#serviceid').val($li.attr('data-service-id'));
            $('#typeid').val($li.attr('data-type-id'));
            //if ($('#typeid').val() != '' && $('#tariff').val().toUpperCase() != 'SaaSPlus'.toUpperCase() && $('#tariff').val().toUpperCase() != 'Enterprise'.toUpperCase()) {
            //    alert(TaskResources.DisabledInThisTariff);
            //    return;
            //}

            //TODO: $li.attr('data-type-id') == '1001' -- бред 
            if (
                    (!!$('#taskid').val() || $('#taskid').val() == '0') && $('#oldtypeid').val() != '1001' && $('#oldserviceid').val() != 0 && $li.attr('data-type-id') == '1001'
                    ) {
                alert(TaskResources.NoChangeToMeetingRoom);
                $('#typeid').val('');
                return;
            }
            $li.parents('form').submit();
            return;
        }

        _currentLevel = $li.parents('ul').length + 1;
        _currentLI = $li;
        $('#btnback').attr('disabled', _currentLevel <= _columns);
        if ((_currentLevel <= _columns) == true) $('#btnback').hide();
        else $('#btnback').show()

        var scrolled = _scrollContainer();

        _setRolloutUlPosition($ul, $li);
        _setHeight();

        if (!scrolled)
            $ul.animate({ 'left': _columnWidth }, 'fast');
        else
            $ul.css('left', _columnWidth);
    }

    function _setRolloutUlPosition($ul, $li) {
        $ul.css('left', 0);
        var windowScrollTop = $('#servicecontainer').scrollTop();
        var freeTop = $li.offset().top - windowScrollTop - (windowScrollTop < $('#serviceholder').offset().top ? $('#serviceholder').offset().top - windowScrollTop : 0);
        var freeBottom = $('#servicecontainer').height() - freeTop;

        if ($ul.height() <= freeBottom) {
            $ul.css('top', $li.position().top).show();
        }
        else if ($ul.height() <= freeTop) {
            $ul.css('top', $li.position().top + $li.height() - $ul.height() + 2).show();
        }
        else {
            if (_currentLevel <3) {
                $ul.css('top', windowScrollTop).show();
            }
            else {
                if ($li.position().top + $li.height() - $ul.height() + 2>0) {
                    $ul.css('top', $li.position().top + $li.height() - $ul.height() + 2).show();
                }
                else {
                    $ul.css('top', $li.position().top).show();
                }
            }
        }
    }

    function _setHeight() {
        var height = 0;
        $('#serviceholder ul:visible').each(function (i, el) { var $el = $(el); if ($el.height() + $el.position().top > height) height = $el.position().top + $el.height(); });
        $('#serviceholder').height(height);
    }

    function _backOneLevel() {
        var $parent = _currentLI.parents('li:first');
        if ($parent.length > 0) {
            $parent.trigger('click');
        }
        else {
            _currentLevel = 1;
            $('#serviceholder ul:first li h3').removeClass('selected');
            $('#serviceholder ul:first li ul').hide();
            _scrollContainer();
        }
    }

    function _scrollContainer() {
        if (_currentLevel > _columns) {
            var offset = (_columns - _currentLevel) * _columnWidth;
            $('#serviceholder').animate({ left: offset }, 'fast');
            return true;
        }
        else if (_currentLevel == _columns) {
            $('#serviceholder').animate({ left: 0 }, 'fast');
        }
        return false;
    }

    function _resizeContainer() {
        _columns = Math.floor(($('#servicecontainer').width() - 70) / _columnWidth);
        $('#servicecontainer').height($(window).height() - 180);
        _scrollContainer();
    }

    //Подключим плагин автозаполнения выпадающего списка только для Desktop-платформ
    if (!$.browser.mobile && !($.browser.msie && parseInt($.browser.version, 10) <= 7)) {
        $("select[id='findserviceid']").chosen({ search_contains: true, is_last_element: 'true', no_results_text: TaskResources.ServiceNotFound, onsetstar: fsaveElectedState, onsavestatusorder: fsaveElectedOrder });
    }
    else {
        $("select[id='findserviceid']").removeClass('visibilityhidden');
    }

    $('#findserviceid').change(function (e) {
        changeResetButton();
        //   $('li[data-service-id="' + $('#findserviceid').val() + '"]').focus().click();
        $('#serviceholder ul li.selected').removeClass('selected');        
        $('#serviceholder>ul>li').hide();
        $('#serviceholder>ul>li ul').hide();
        if ($('#findserviceid').val() == '0') $('#serviceholder>ul>li').show();
        var $li = $('li[data-service-id="' + $('#findserviceid').val() + '"]');
        focusService($li);
        e.preventDefault();
        return false;
    });

});
function focusService($li) {
    $li.show();
    var $parentLi = $li.parent().closest('li.service');
    if ($parentLi.length) focusService($parentLi);
    if (!$li.hasClass('endpoint'))
         $li.focus().click(); 
    else
        $li.addClass('selected');

}
function fsaveElectedState(event) {
    console.log('fsaveElectedState - ',event)
    return false;
}

function fsaveElectedOrder(event) {
    console.log('fsaveElectedOrder - ', event)
}

function toDefaultService() {
    if ($('#resetservice').hasClass('disabled')) return false;
    $("#findserviceid").val("0");
    $("#findserviceid").trigger("chosen:updated");
    $('#findserviceid').change();
    changeResetButton();
    return false;
}

function changeResetButton() {
    if ($('#resetservice').length) {
        if ($('#findserviceid').val() > 0) {
            $("#resetservice").removeClass("disabled");
            $('#resetservice img').attr('src', $('#resetservice img').attr('src').replace('_gray', ''));
        }
        else {
            $("#resetservice").addClass("disabled");
            $('#resetservice img').attr('src', $('#resetservice img').attr('src').replace('_gray', '').replace('.gif', '_gray.gif'));

        }
    }
}