$(function onDocumentReady() {
    if ($.browser.msie && $.browser.version == 8) {
        $(".search.ie8").show();
    } else {
        $(".search.notIE8").show();
    }
    document.getElementById('decrease').style.display = 'none';
    setTimeout(showSuggestion, (15 * 1000));

    var search = Search.getInstance();
    search.setEngine(new Questions());

    var input = $('.search .input');
    input.val('');
    input.focus();
    input.keypress(hideSuggestion);
    input.keypress(onEnterKeyPress);
    input.click(hideSuggestion);

    delaySearch(input);
    $('.prev').click(previous);
    $('.next').click(next);
});

function showSuggestion() {
    var search = Search.getInstance();

    if ( ! search.results ) {
        $('.suggestion').not('.nothing-found').show();
    }
}

function hideSuggestion() {
    $('.suggestion').not('.nothing-found').hide();
}

function onEnterKeyPress(event) {
    var enterKeyCode = 13;

    if ( event.which === enterKeyCode ) {
        search($(this).val())
    }
}

function delaySearch(input) {
    var timer = null;
    var timeout = 1000;

    input.keyup(function(event) {
        clearTimeout(timer);
        timer = setTimeout(function() {
            if ( ! ($.inArray(event.which, [0, 13, 16, 17, 18, 20, 27]) !== -1) ) {
                if ( input.val() ) {
                    search(input.val());
                }
            }
        }, timeout);
    });
}

function search(searchString) {
    var search = Search.getInstance();

    if ( search.results
         && (typeof search.results.getCriteria === 'function')
         && (search.results.getCriteria() === searchString) )
    {
        return next();
    }

    search.find(searchString);
    if ( typeof search.results.count === 'function' ) {
        $('.nothing-found').hide();
        $('.prev').show();
        $('.next').show();

        scroll(search.results.current());
    } else {
        document.querySelector('.nothing-found').style.display = 'block';
        $('.prev').hide();
        $('.next').hide();
    }
}

function previous() {
    var search = Search.getInstance();
    var previous = search.results.previous();

    if ( previous ) {
        scroll(previous);
    } else {
        search.results.gotoLast();
        scroll(search.results.current());
    }
}

function next() {
    var search = Search.getInstance();
    var next = search.results.next();

    if ( next ) {
        scroll(next);
    } else {
        search.results.gotoFirst();
        scroll(search.results.current());
    }
}

function scroll(id) {
    var target = document.getElementById(id);

    var paragraph = $(target).closest('.question-list')[0];
    if ( paragraph.style.display === 'none' ) {
        $(paragraph).show();
    }

    if ( $(target).parent().hasClass('questions') ) {
        var answer = $(target).parents('.with_icon').find('.faq')[0];
    } else {
        var answer = $(target).closest('.faq')[0];
    }
    if ( typeof(answer) != 'undefined' && answer !== null && answer.style.display === 'none' ) {
        $(answer).show();
        swapTextOfSlide($(answer).parent().find('.slide')[0]);
    }

    var top = document.getElementById(id).offsetTop;
    window.scrollTo(0, (top - 200));
}

function swapTextOfSlide(element) {
    $(element).text(
        $(element).text() == 'Показать ответ' ? 'Скрыть ответ' : 'Показать ответ'
    );
}

function Search() {
    if ( arguments.callee._singletonInstance ) {
        return arguments.callee._singletonInstance;
    }
    arguments.callee._singletonInstance = this;

    var engine = null;
    var results = null;

    this.setEngine = function(searchEngine) {
        engine = searchEngine;
    };

    this.find = function(searchString) {
        this.results = engine.mark(searchString);
    };
}

Search.getInstance = function() {
    return new Search();
};

function Questions() {

    var index = getIndex();

    this.mark = function(searchString) {
        $('.highlight').contents().unwrap();
        $('.slide').text('Показать ответ');
        $('.question-list').hide();
        $('.faq').hide();

        if ( ! searchString ) {
            return null;
        }

        var criteria = searchString.toLowerCase();

        var found = [];
        var current = 0;
        for ( var i = 0; i < index.length; ++i ) {
            var row = index[i];

            if ( ~row.text.indexOf(criteria) ) {
                var content = row.element.innerHTML;
                var re = new RegExp(escape(searchString), 'gi');

                var highlighted = '';
                var htmlTagRe = new RegExp(/\s*(<[^>]*>)/g);
                var parts = content.split(htmlTagRe);

                for ( var j = 0; j < parts.length; ++j ) {
                    var part = parts[j];

                    if ( part.match(htmlTagRe) ) {
                        highlighted += part;
                    } else {
                        highlighted += part.replace(re, function(match) {
                            var id = 'match-' + current++;
                            found.push(id);
                            return '<span id="' + id + '" class="highlight">' + match + '</span>';
                        });
                    }
                }
                row.element.innerHTML = highlighted;

                var paragraph = $(row.element).closest('.question-list')[0];
                if ( paragraph.style.display === 'none' ) {
                    $(paragraph).show();
                }

                var answer = row.element.querySelector('.faq');
                if ( typeof(answer) != 'undefined' && answer !== null && answer.style.display === 'none' ) {
                    $(answer).show();
                }

                var slide = row.element.querySelector('.slide');
                swapTextOfSlide(slide);

                $(slide).click(function(event) {
                    event.preventDefault();
                    $(this).parent().find('.faq').slideToggle('slow');
                    swapTextOfSlide(this);
                });
            }
        }

        return new SearchResults(searchString, found);
    }

    function getIndex() {
        var items = document.querySelectorAll('.with_icon');

        var entries = [];
        for ( var i = 0; i < items.length; ++i ) {
            var item = items[i];

            entries.push({
                'element': item,
                'text': getTrimmedTextInLowerCase($(item).text())
            });
        }

        return entries;
    }

    function getTrimmedTextInLowerCase(text) {
        return $.trim(text.toLowerCase());
    }

    function escape(line) {
        return line.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    }
}

function SearchResults(searchString, result) {
    if ( (! result.hasOwnProperty('length')) || (result.length < 1) ) {
        return null;
    }

    var criteria = searchString;
    var current = 0;
    var bundle = result;

    this.getCriteria = function() {
        return criteria;
    };

    this.getCurrentElementNumber = function() {
        return (current + 1);
    };

    this.gotoFirst = function() {
        current = 0;
    };

    this.gotoLast = function() {
        current = (bundle.length - 1);
    };

    this.count = function() {
        return bundle.length;
    };

    this.current = function() {
        return getValue(current);
    };

    this.next = function() {
        var nextElementPosition = (current + 1);
        var nextElement = getValue(nextElementPosition);

        if ( nextElement ) {
            current = nextElementPosition;

            return nextElement;
        }

        return null;
    };

    this.previous = function() {
        var previousElementPosition = (current - 1);
        var previousElement = getValue(previousElementPosition);

        if ( previousElement ) {
            current = previousElementPosition;

            return previousElement;
        }

        return null;
    };

    function inRange(position) {
        if ( (position >= 0) && (position <= bundle.length) ) {
            return true;
        }

        return false
    }

    function getValue(position) {
        if ( inRange(position) ) {
            return bundle[position];
        }

        return null;
    }
}

function showAllItems(open){
    function hasClass(el, cls) {
        return el.className && new RegExp("(\\s|^)" + cls + "(\\s|$)").test(el.className);
    }
    var subClass = open ? "opened" : "closed";

    var paragraphs = $(".toggleParagraph"); if(!paragraphs) return false;
    for( var i = 0; i < paragraphs.length; i++){
        if(hasClass(paragraphs[i], subClass)) continue;
        paragraphs[i].click();
    }

    var slides = $(".slide"); if(!slides) return false;
    for( var j = 0; j < slides.length; j++){
        if(hasClass(slides[j], subClass)) continue;
        slides[j].click();
    }

    if(open) $('.div_more.faq').show();
    else $('.div_more.faq').hide();
}