/**
 * Zakladni objekt cele aplikace.<br><br>
 * Po udalosti <b>DOM ready</b> <i>(dokument jiz je plne nacten, donacitaji se pouze obrazky)</i> se zavola metoda <b>Educity.data.fetch()</b>,
 * ktera se v dokumentu pokusi vyhledat/naparsovat promene a ciselniky pro dalsi chod aplikace. Nalezene promene jsou ukladany do <b>Educity.data</b>.<br><br>
 * Nasledne je zavolana metoda <b>Educity.data.init()</b>, ktera instancuje jednolive tridy objektu pouzitych ve strance. Instance trid jsou ukladany do <b>Educity.instances</b>.<br><br>
 * Instance trid jsou volany v poradi v jakem byli ve strance vlozeny do pole <b>cmd</b> pomoci <b>cmd.add(</b><i>string</i> <b>commandName)</b>.
 * Jednotlive prikazy k instancovani trid jsou definovany <b>az</b> pri volani <b>Educity.data.init()</b> <i>(Vyzaduji data ziskane pri Educity.data.fetch())</i> a jsou ulozeny v objektu <b>Educity.command</b>.<br><br>
 * Staticke nastaveni je ulozeno v objektu <b>Educity.settings</b>, typicky id a classy html objektu ve strance.
 */
var Educity = {
    settings: {
        idPrefix: 'jq_',
        selector: {
            selectorId: '#coursesNavigation',
            formId: '#selectorForm',
            itemTemplate: '<div class="checkbox"><input type="checkbox" value="{id}" id="popupItem_{id}" /></div><div class="label"><label for="popupItem_{id}">{name}</label></div>'
        },
        popup: {
            includeElementId: 'body'
        },
        topics: {
            elementId: '#topicsPopup',
            selectId: '#topicsSelect',
            panelId: '#topicsPanel',
            openId: '#topicsOpen',
            selectedItemsElementId: '#topicsSelectedItems',
            hiddenItemName: 'topic2'
        },
            languageContent: {
            elementId: '#languageContentPopup',
            panelId: '#languageContentPanel',
            openId: '#languageContentOpen',
            selectedItemsElementId: '#languageContentSelectedItems',
            hiddenItemName: 'languageContent'
        },
        languageLevel: {
            elementId: '#languageLevelPopup',
            panelId: '#languageLevelPanel',
            openId: '#languageLevelOpen',
            selectedItemsElementId: '#languageLevelSelectedItems',
            hiddenItemName: 'languageLevel'
        },
        companies: {
            elementId: '#companyPopup',
            panelId: '#companyPanel',
            openId: '#companyOpen',
            selectId: '#companiesMultiSelect',
            selectedItemsElementId: '#companySelectedItems',
            hiddenItemName: 'company'
        },
        calendar: {
            path: '/static/educity/js/libraries/jquery.dateChooser.js',
            inputFromId: '#dateFrom',
            inputTillId: '#dateTill'
        }
    },
    init: function() {
        this.instances = {}

        // definice commandu k instancovani trid
        this.command = {
            run: function(command){
                this[command]()
            },
            kidsPictures: function () {
                $('#vykresy .gallery').hide()
                $('ul.thumbnails').galleria({
                    history   : true, // activates the history object for bookmarking, back-button etc.
                    clickNext : true, // helper for making the image clickable
                    insert    : '#vykresy .large-image', // the containing selector for our main image
                    onImage   : function(image,caption,thumb) { // let's add some image effects for demonstration purposes
                        // fade in the image & caption
                        image.css('display','none').fadeIn(1000);
                        // fetch the thumbnail container
                        var _li = thumb.parents('li');
                        // fade out inactive thumbnail
                        _li.siblings().children('img.selected').fadeTo(500,0.3);
                        // fade in active thumbnail
                        thumb.fadeTo('fast',1).addClass('selected');
                        // add a title for the clickable image
                        image.attr('title', Educity.data.selectorStrings['kidsPictures'].next);
                    },
                    onThumb : function(thumb) {
                        // thumbnail effects goes here
                        // fetch the thumbnail container
                        var _li = thumb.parents('li');
                        // if thumbnail is active, fade all the way.
                        var _fadeTo = _li.is('.active') ? '1' : '0.3';
                        // fade in the thumbnail when finnished loading
                        thumb.css({display:'none',opacity:_fadeTo}).fadeIn(1500);
                        // hover effects
                        thumb.hover(
                            function() {
                                thumb.fadeTo('fast',1)
                            },
                            function() {
                                _li.not('.active').children('img').fadeTo('fast',0.3)
                            } // don't fade out if the parent is active
                        )
                    }
                })
                $('#vykresy .nav .prev').click(function(event) {
                    $.galleria.prev()
                    event.stopPropagation()
                    event.preventDefault()
                })
                $('#vykresy .nav .next').click(function(event) {
                    event.stopPropagation()
                    event.preventDefault()
                    $.galleria.next()
                })
                window.setTimeout(function() {
                    $('#vykresy .gallery').show()
                }, 500)
            },
            loginAsUser: function() {
                Educity.instances.loginAsUser = new LoginAsUser()
            },
            fulltext: function(){
                Educity.instances.fulltext = new Fulltext({
                    strings: Educity.data.selectorStrings['fulltext']
                })
                $('#fulltext').blur()
            },
            introJobcity: function(){
                Educity.instances.introJobcity = new IntroJobcity()
            },
            utils: function(){
                Educity.instances.utils = new Utils()
            },
            partners: function(){
                Educity.instances.partners = new Partners()
            },
            scheduledSelector: function(){
                Educity.instances.type = 'scheduled'
                Educity.instances.topics = new SelectorTopics({
                    tree: Educity.data.tree[0].children,
                    strings: Educity.data.selectorStrings['topics'],
                    data: Educity.data.fromPageTopics ? Educity.data.fromPageTopics : null,
                    menuitem:Educity.data.fromPageMenuitem ? Educity.data.fromPageMenuitem : null
                })
                Educity.instances.calendar = new Calendar({
                    strings: Educity.data.selectorStrings['calendar']
                })
                EducityUtilities.registerEvents()
            },
            scheduledLanguageSelector: function() {
                Educity.instances.type = 'scheduled'
                Educity.instances.topics = new SelectorTopics({
                    tree: Educity.data.tree[0].children[2].children,
                    strings: Educity.data.selectorStrings['topics'],
                    data: Educity.data.fromPageTopics ? Educity.data.fromPageTopics : null
                })
                Educity.instances.companies = new SelectorCompanies({
                    tree: Educity.data.companiesTree,
                    strings: Educity.data.selectorStrings['companies'],
                    data: Educity.data.fromPageCompanies ? Educity.data.fromPageCompanies : null
                })
                Educity.instances.languageLevel = new SelectorLanguageLevel({
                    tree: Educity.data.enums['lc-level'],
                    strings: Educity.data.selectorStrings['languageLevel'],
                    data: Educity.data.fromPageLanguageLevel ? Educity.data.fromPageLanguageLevel : null
                })
                Educity.instances.languageContent = new SelectorLanguageContent({
                    tree: Educity.data.enums['lc-content'],
                    strings: Educity.data.selectorStrings['languageContent'],
                    data: Educity.data.fromPageLanguageContent ? Educity.data.fromPageLanguageContent : null
                })
                Educity.instances.calendar = new Calendar({
                    strings: Educity.data.selectorStrings['calendar']
                })
                EducityUtilities.registerEvents()
            },
            customSelector: function(){
                Educity.instances.type = 'custom'
                Educity.instances.topics = new SelectorTopics({
                    tree: Educity.data.tree[1].children,
                    strings: Educity.data.selectorStrings['topics'],
                    data: Educity.data.fromPageTopics ? Educity.data.fromPageTopics : null
                })
                EducityUtilities.registerEvents()
            },
            customLanguageSelector: function() {
                Educity.instances.type = 'custom'
                Educity.instances.companies = new SelectorCompanies({
                    tree: Educity.data.companiesTree,
                    strings: Educity.data.selectorStrings['companies'],
                    data: Educity.data.fromPageCompanies ? Educity.data.fromPageCompanies : null
                })
                EducityUtilities.registerEvents()
            },
            companiesSelector: function() {
                Educity.instances.type = 'companies'
                EducityUtilities.registerEvents()
            },
            companiesLanguageSelector: function() {
                Educity.instances.type = 'companies'
                EducityUtilities.registerEvents()
            },
            consultingsSelector: function() {
                Educity.instances.type = 'consultings'
                Educity.instances.topics = new SelectorTopics({
                    tree: Educity.data.tree[2].children,
                    strings: Educity.data.selectorStrings['topics'],
                    data: Educity.data.fromPageTopics ? Educity.data.fromPageTopics : null
                })
                EducityUtilities.registerEvents()
            },
            consultingsCompaniesSelector: function() {
                Educity.instances.type = 'consultings'
                EducityUtilities.registerEvents()
            },
            topCompanies: function() {
                Educity.instances.topCompanies = new TopCompanies({
                    strings: Educity.data.selectorStrings['topCompanies']
                })
            },
            subTopCompanies: function() {
                $(topCompaniesLogoCache).each(function(index, item) {
                    if (item && item.logo) {
                        var img = new Image()
                        img.src = item.logo
                        var link = $('#company_a_' + item.id)
                        link.bind('mouseover', function(event) {
                            $('#topCompaniesNote').find('a').attr('href', link.attr('href')).find('img').attr('src', img.src).attr('alt', link.text())
                            link.addClass('active')
                        }).bind('mouseout', function(event) {
                            link.removeClass('active')
                        })
                    }
                })
            },
            categoryTree: function() {
                Educity.instances.tree = new CategoryTree({
                    strings: Educity.data.selectorStrings['categoryTree']
                })
                Educity.instances.tree.initTree('#scheduledTree')
                Educity.instances.tree.initTree('#customTree')
                Educity.instances.tree.initTree('#languageTree')
                Educity.instances.tree.initTree('#customLanguageTree')
                Educity.instances.tree.initTree('#consultingTree')
            },
            courseDetailTree: function() {
                Educity.instances.tree = new CategoryTree()
                Educity.instances.tree.initCourseTree('#katalog')
            }
        }

        // projde pole s commandy a zacne je vykonavat
        if (cmd && cmd.querry) {
            var _this = this
            $(cmd.querry).each(function(i, value){
                console.time('Init - ' + value)
                _this.command.run(value)
                console.timeEnd('Init - ' + value)
            })
        }

        console.timeEnd('TOTAL Educity.Init time')
    },
    data: {
        fetch: function() {
            console.time('TOTAL Educity.Init time')

            if (typeof(json) != 'undefined') {
                console.time('Parsing JSON')
                this.enums = eval("(" + json.enums + ")")
                this.tree = eval("(" + json.tree + ")")
                delete json
                console.timeEnd('Parsing JSON')
            }

            console.time('Getting other data from page')

            if (typeof(mapping) != 'undefined') {
                this.sectionsMapping = mapping
                delete mapping
            }
            if (typeof(topics) != 'undefined') {
                this.fromPageTopics = topics
                delete topics
            }
            if (typeof(languageLevel) != 'undefined') {
                this.fromPageLanguageLevel = languageLevel
                delete languageLevel
            }
            if (typeof(languageContent) != 'undefined') {
                this.fromPageLanguageContent = languageContent
                delete languageContent
            }
            if (typeof(companies) != 'undefined') {
                this.fromPageCompanies = companies
                delete companies
            }
            if (typeof(companiesTree) != 'undefined') {
                this.companiesTree = companiesTree
                delete companiesTree
            }
            if (typeof(menuitem) != 'undefined') {
                this.fromPageMenuitem = menuitem
                delete menuitem
            }
            if (typeof(selectorStrings) != 'undefined') {
                this.selectorStrings = selectorStrings
                delete selectorStrings
            }

            console.timeEnd('Getting other data from page')

            Educity.init()
        },
        // TODO konverzni mapa by mela byt nactena z enumu, nikoliv takto staticky
        convertMap: {
            scheduledToCustom: {35:270,39:271,38:284,551201:551120,36:551121,3498:551122,41:null,551202:281,37:282,551203:551196,551204:null,551205:551197,287:null,286:283,3830:22100,551206:null,40:285},
            customToScheduled: {270:35,271:39,284:38,551120:551201,551121:36,551122:3498,281:551202,282:37,551196:551203,47673:null,551197:551205,283:286,22100:3830,285:40}
        }
    }
}

/**
 * Pomocna trida pro praci s hodnotami selectoru.
 * @alias EducityUtilities
 */
var EducityUtilities = {
    /**
     * Zaregistruje event listener, ktery po kliknuti vyvola zmenu url linku.
     * @param {Object} bindTo
     */
    registerEvents: function(bindTo) {
        $('#hiddenSelector .tabsGray a').each(function(num, item) {
            $(item).bind('click', EducityUtilities.changeAddress)
        })
    },
    /**
     * Event handler vyvolany po kliknuti na link, zmeni url linku na ktery se klikne, tak aby se prenesli aktualni hodnoty selectoru a pokracuje v propagaci eventu.
     * @param {Event} event
     * @param {Object} type
     */
    changeAddress: function(event, type) {
        if (Popup.visible) {
            console.warn('Selector popup is visible, can\'t transfer data.')
            return
        }
        console.log('Selector form - data transport begin, removing topic2')
        $('#selectorForm .hiddenSelectedItem').each(function(item){item.remove()})
        if($('#selectorForm')[0].topic1) {
            if (Educity.instances.type == 'custom') {
                var convertedId = Educity.data.convertMap.customToScheduled[$('#selectorForm')[0].topic1.value]
            } else {
                var convertedId = Educity.data.convertMap.scheduledToCustom[$('#selectorForm')[0].topic1.value]
            }
            if (convertedId) {
                $('#topicsSelect')[0].options[$('#topicsSelect')[0].selectedIndex].value = convertedId
            } else {
                $('#topicsSelect')[0].options[$('#topicsSelect')[0].selectedIndex].value = -1
            }
        }
        data = $('#selectorForm').serialize()
        event.target.href += event.target.href.indexOf('?') < 1 ? '?' + data : '&' + data
    },
    submitForm: function(event) {
        if (event) {
            if (event.target.href.indexOf('advanced') > -1) {
                $('#selectorForm').append($.create('input', {
                    'type': 'hidden',
                    'name': 'advanced',
                    'value': 1
                }))
            }
        } else {
            // remove advanced if exist
        }
        $('#selectorForm .selector-submit').click()
    },
    appendToForm: function(name, value) {
        $('#selectorForm').append($.create('input', {
            'type': 'hidden',
            'name': name,
            'value': value
        }))
    },
    runClickHeat: function(path, site) {
        console.time('ClickHeat loading time')
        $.getScript(path, function(){
            clickHeatSite = site
            clickHeatGroup = window.location.pathname
            clickHeatQuota = 2
            clickHeatServer = 'http://clickheat.ivitera.com/click.php'
            var reloadCount = 1
            $.timer(10 * reloadCount, function(timer) {
                if (typeof(initClickHeat) != 'undefined') {
                    timer.stop()
                    initClickHeat()
                    console.timeEnd('ClickHeat loading time')
                }
                if (reloadCount++ > 1000) {
                    timer.stop()
                    console.warn('Exceded maximum number of attempts, ClickHeat cannot be loaded.')
                }
            })
        })
    },
    runGoogleAnalytics: function(path, code) {
        console.time('Google Analytics loading time')
        $.getScript(path, function(){
            var pageTracker = _gat._getTracker(code)
            pageTracker._trackPageview()
            console.timeEnd('Google Analytics loading time')
        })
    },
    getJsLibrary: function(path, callback, object) {
        console.time(path + ' loading time')
        this.jsPath = path
        this.jsCallback = function(){
            callback(self)
        }
        this.jsObject = object
        var reference = this
        $.getScript(path, function(){
            $.timer(50 * reference.reloadCount, function(timer) {
                if (reference.checkJsLibraryAvailability()) {
                    timer.stop()
                    reference.jsCallback()
                    console.timeEnd(path + ' loading time')
                }
                if (reference.reloadCount > 10) {
                    timer.stop()
                    console.warn('Exceded maximum number of attempts, ' + console.path + ' cannot be loaded.')
                }
            })
        })
    },
    checkJsLibraryAvailability: function() {
        if (this.jsObject(self)) {
            return true
        }
        if (!this.reloadCount) {
            this.reloadCount = 1
        }
        console.warn(this.jsPath + ' cannot be loaded, checking again after ' + (50 * this.reloadCount) + 'ms, number of attempts: ' + this.reloadCount)
        this.reloadCount++
        return false
    }
}

/**
 * Blocek top firem, po inicializaci ridi nacitani a zobrazovani informaci o spolecnostech.
 * Informace jsou ziskavany ajaxovym volanim po vykonani eventu mouseOver nad nazvem spolecnosti.
 * Po uspesnem nacteni je informace cachovana.
 * @alias TopCompanies
 * @param {Object} settings[optional]
 * @return {TopCompanies}
 * @constructor
 */
    var TopCompanies = new $.klass({
    initialize: function(settings) {
        jQuery.extend(this, settings)
        this.showingTimer = new Timer('showingTimer', 350, 'Educity.instances.topCompanies.show()')
        this.hidingTimer = new Timer('hidingTimer', 350, 'Educity.instances.topCompanies.hide()')
        this.redrawTimer = new Timer('redrawTimer', 40, 'Educity.instances.topCompanies.show()')
        this.toShow = null
        this.lastEventIsOut = null
        this.cache = []
        var _reference = this

        $(topCompaniesLogoCache).each(function(index, item) {
            var link = $('#company_a_' + item.id)
            var li = $(link[0].parentNode).data('index', index).bind('mouseover', _reference, function(event) {
                var index = $(event.target).data('index')
                if (typeof(index) == 'undefined') {
                    index = $(event.target.parentNode).data('index')
                }
                event.data.mouseOver(index)
            }).bind('mouseout', _reference, function(event) {
                event.data.mouseOut(index)
            })
            _reference.cache.push({
                id: item.id,
                logo: item.logo,
                link: link.attr('href')
            })
        })

        // clear junk
        delete topCompaniesLogoCache

        // prepare popup
        this.popup = new Popup({strings:this.strings, modal:false, color:'wheat'}) // $('#topCompany').hide().removeClass('display-none')
        this.popup.header.empty()
        this.popup.header.append($.create('h2', {}, this.strings.popup_header).prepend($.create('a', {'id':'topCompanyClose','class':'close','href':'javascript:void(0);','title':this.strings.close})))
        this.popup.body.attr({'id':'topCompanyBody'})

        // remove useless footer
        if (this.popup.footer.html().length === 0) {
            $('.popupFooter', this.popup.element).remove()
            delete this.popup.footer
        }

        $('#topCompanyClose').bind('click', this, function(event) {
            event.data.hide()
        })

        this.popup.element.bind('mouseover', this, function(event) {
            var timer = event.data.hidingTimer
            if (timer.running) {
                timer.stop()
            }
        }).bind('mouseout', this, function(event) {
            var timer = event.data.hidingTimer
            if (!timer.running) {
                timer.start()
            }
        })
    },
    mouseOver: function(index) {
        this.lastEventIsOut = false
        var company = this.cache[index]
        this.toShow = index
        if (this.hidingTimer.running) {
            this.hidingTimer.stop()
        }
        if (!company.requestSend) {
            // send AJAX request
            this.getCompanyData(company)
        } else if (!company.requestComplete) {
            // still waiting for response
        } else {
            // company is loaded to cache, try to show
            if (this.popup.element.css('display') != 'none') {
                // visible popup
                this.redrawTimer.start()
            } else if (!this.showingTimer.running) {
                // popup hidden and timer stopped
                this.showingTimer.start()
            }
        }
    },
    mouseOut: function() {
        this.lastEventIsOut = true
        // remove index
        if (this.toShow) {
            this.toShow = null
        }
        // if popup is visible start hiding
        if (this.popup.element.css('display') != 'none') {
            this.hidingTimer.start()
            this.showingTimer.stop()
            this.redrawTimer.stop()
        }
    },
    show: function() {
        this.showingTimer.stop()
        // must be "if (this.toShow != null)", because "if (this.toShow)" returns false when "toShow = 0" and 0 is valid index
        if (this.toShow != null && this.cache[this.toShow].requestComplete) {
            // redraw popup
            this.redrawPopup()
            // show popup
            var target = $('#right')
            var width = target.width()
            var position = target.offset()
            position.left -= width + 10
            this.popup.show(position, width)
        }
    },
    hide: function() {
        // hide popup
        this.hidingTimer.stop()
        this.popup.hide()
        this.toShow = null
        if (this.activeElement) {
            this.activeElement.removeClass('active')
            this.activeElement.parent().removeClass('active')
            this.activeElement = null
        }
    },
    checkVisibility: function() {
        if (this.lastEventIsOut && !this.hidingTimer.running) {
            this.hide()
        }
    },
    getCompanyData: function(company) {
        // get logo
        company.img = new Image()
        company.img.src = company.logo
        // get other information

    $.getJSON("/portal/template/EcTopCompanyInfo",{id:company.id},
        function(data){
                company.name = $.trim(data.name)
                company.name = company.name.length > 0 ? company.name : false
                company.description = $.trim(data.description)
                company.description = company.description.length > 0 ? company.description : false
                company.address = $.trim(data.address)
                company.address = company.address.length > 0 ? company.address : false
                company.phone = $.trim(data.phone)
                company.phone = company.phone.length > 0 ? company.phone : false
                company.fax = $.trim(data.fax)
                company.fax = company.fax.length > 0 ? company.fax : false
                company.email = $.trim(data.email)
                company.email = company.email.length > 0 ? company.email : false
                company.courses = $.trim(data.scheduledCourses)
                company.courses = company.courses.length > 0 ? company.courses : false
                company.customCourses = $.trim(data.customCourses)
                company.customCourses = company.customCourses.length > 0 ? company.customCourses : false
                company.languages = $.trim(data.scheduledLanguageCourses)
                company.languages = company.languages.length > 0 ? company.languages : false
                company.customLanguages = $.trim(data.customLanguageCourses)
                company.customLanguages = company.customLanguages.length > 0 ? company.customLanguages : false
                company.consultings = $.trim(data.consultings)
                company.consultings = company.consultings.length > 0 ? company.consultings : false
                company.requestComplete = true
                // try to show popup
                if (!Educity.instances.topCompanies.showingTimer.running && Educity.instances.topCompanies.toShow != null) {
                    Educity.instances.topCompanies.showingTimer.start()
                }
        });
        company.requestSend = true
    },
    redrawPopup: function(company, strings) {
        var company = this.cache[this.toShow]
        var strings = this.strings
        // contact block
        var resultBuffer = '<span class="arrow"></span><div class="contact">'
        // name, logo
        resultBuffer += '<div class="name"><a href="' + company.link + '">' + company.name + '</a></div><div class="logo"><a href="' + company.link + '"><img src="' + company.logo + '" title="' + company.name + '" width="120" height="60" /></a></div>'
        if (company.description) {
            // description
            resultBuffer += '<div>' + company.description + '</div>'
        } else {
            // contact information
            if  (company.address || company.phone || company.fax || company.email) {
                resultBuffer += '<div><ul class="pairList">'
                if (company.address) {resultBuffer += '<li class="address"><div class="label">' + strings.address + '</div><span class="value">' + company.address + '</span></li>'}
                if (company.phone) {resultBuffer += '<li class="phone"><div class="label">' + strings.phone + '</div><span class="value">' + company.phone + '</span></li>'}
                if (company.fax) {resultBuffer += '<li class="fax"><div class="label">' + strings.fax + '</div><span class="value">' + company.fax + '</span></li>'}
                if (company.email) {resultBuffer += '<li class="email"><div class="label">' + strings.email + '</div><span class="value"><a href="mailto:' + company.email + '">' + company.email + '</a></span></li>'}
                resultBuffer += '</ul><div class="clear"></div></div>'
            }
        }
        // close contact block
        resultBuffer += '</div>'
        // products links
        if (company.courses || company.customCourses || company.languages || company.customLanguages || company.consultings) {
            resultBuffer += '<h3>' + strings.links + '</h3><div class="links">'
            if (company.courses) {resultBuffer += '<a class="scheduledLink" href="' + company.courses + '">' + strings.courses + '</a>'}
            if (company.customCourses) {resultBuffer += '<a class="customLink" href="' + company.customCourses + '">' + strings.customCourses + '</a>'}
            if (company.languages) {resultBuffer += '<a class="scheduledLink" href="' + company.languages + '">' + strings.languages + '</a>'}
            if (company.customLanguages) {resultBuffer += '<a class="customLink" href="' + company.customLanguages + '">' + strings.customLanguages + '</a>'}
            if (company.consultings) {resultBuffer += '<a class="consultingLink" href="' + company.consultings + '">' + strings.consultings + '</a>'}
            resultBuffer += '<div class="clear"></div>'
            resultBuffer += '</div>'
        }
        // insert buffer content into popup
        this.popup.body.html(resultBuffer)
        // remove previous active element class
        if (this.activeElement) {
            this.activeElement.removeClass('active')
            this.activeElement.parent().removeClass('active')
        }
        // highlight current active element
        this.activeElement = $('#company_a_' + company.id).addClass('active')
        this.activeElement.parent().addClass('active')
    }
})

/**
 * Obecna trida pro popupu pro prvky stranky.
 * @alias Popup
 * @param {Object} settings[optional]
 * @return {Popup}
 * @constructor
 */
var Popup = new $.klass({
    initialize: function(settings) {
        jQuery.extend(settings, Educity.settings.popup)
        jQuery.extend(this, settings)

        if (!this.strings) {
            console.warn('Inicializace popupu bez zadanych stringu!')
            this.strings = {
                popup_header: ''
            }
        }

        // render elements
        this.element = $.create('div', {'class':'popup'}).hide()
        this.header = $.create('div', {'class': 'popupHeader'})
        this.body = $.create('div', {'class': 'content'})
        this.footer = $.create('div', {'class': 'popupFooter'})
        this.headerClose = $.create('a', {'href':'javascript:void(0)','class':'close'})

        // determine header color
        if (this.color) {
            var appendTo = $.create('div', {'class':this.color}).appendTo(this.element)
        } else {
            var appendTo = this.element
        }

        appendTo.append($.create('div',{'class':'tl'}).append($.create('div',{'class':'tr'}).append($.create('div',{'class':'t'}).append($.create('div',{'class':'t2'})))))
        appendTo.append(this.header.append($.create('h2').append(this.headerClose).append($.create('span', {}, this.strings.popup_header))))
        appendTo.append($.create('div',{'class':'body'}).append(this.body))
        appendTo.append(this.footer)
        appendTo.append($.create('div',{'class':'bl'}).append($.create('div',{'class':'br'}).append($.create('div',{'class':'b'}))))

        // identify element
        if (!this.elementId) {
            this.elementId = Educity.settings.idPrefix + jQuery.data(this.element)
        }
        this.element.attr('id', this.elementId)

        // set zindex, create info about popup
        if (this.element.css('z-index') == 'auto') {
            this.element.css('z-index', 1100)
        }
        this.info = '(title = ' + this.strings.popup_header + ', id = ' + this.elementId + ', z-index = ' + this.element.css('z-index') + ')'

        // insert element to page
        $(this.includeElementId).append(this.element)

        // ie6 iframe workaround
        if ($.browser.msie && $.browser.version == '6.0') {
            this.iframe = $.create('iframe', {'class':'popupIframe','scrolling':'no', 'frameBorder':'0', 'src':'javascript:\'\''}).hide()
            this.iframeId = Educity.settings.idPrefix + jQuery.data(this.iframe)
            $(this.includeElementId).append(this.iframe)
        }

        // if modal popup create background to catch clicks event
        if (this.modal) {
            this.modalBackground = $.create('div', {'class':'modalBackground', zIndex: 1000}).hide()
            this.element.after(this.modalBackground)
            $(this.modalBackground).bind('click', this, this.modalClick)
            this.modalInfo = '(background z-index = ' + this.modalBackground.css('z-index') + ')'
        }

        // prevent text selection inside popup
        if ($.browser.msie) {
            $(this.element)[0].ondrag = function () {return false}
            $(this.element)[0].onselectstart = function () {return false}
        }
    },
    show: function(position, width) {
        // popup is locked
        if (this.locked) {
            return
        }

        // if exist parent popup, must be locked
        if (this.parent) {
            this.parent.locked = true
        }

        // move and size element
        this.element.css(position)
        this.element.css({
            width: width
        })

        // show element, ie6 iframe workaround
        if ($.browser.msie && $.browser.version == '6.0') {
            this.iframe.css(position)
            this.iframe.css({
                width: width
            })
            this.element.show()
            this.iframe.show()
        } else {
            this.element.show(444)
        }

        // show modal background, register event
        if (this.modal) {
            this.modalBackground.css({height: this.modalBackground.parent().height()})
            this.modalBackground.show()
            console.log('Popup - show modal background ' + this.modalInfo)
        }

        console.log('Popup - show ' + this.info)
    },
    hide: function() {
        // popup is locked
        if (this.locked) {
            return
        }

        // if exist parent popup, must be unlocked
        if (this.parent) {
            this.parent.locked = false
        }

        // hide element, ie6 iframe workaround
        if ($.browser.msie && $.browser.version == '6.0') {
            this.iframe.hide()
        }

        // hide modal background, unregister event
        if (this.modal) {
            this.modalBackground.hide()
        }

        this.element.hide()
        console.log('Popup - hide ' + this.info)
    },
    modalClick: function(event) {
        var _this = event.data
        console.log('Popup - background clicked, hiding popup ' + _this.modalInfo)
        _this.hide()
    }
})

/**
* Popup pro selectory.
* @alias SelectorsPopup
* @param {Object} settings[optional]
* @return {SelectorsPopup}
* @constructor
*/
var SelectorsPopup = new $.klass(Popup, {
    initialize: function($super, settings) {
        $super(settings)

        // create list
        this.list = $.create('ul', {'class': 'pairList'}).appendTo(this.body)
        this.body.append(this.list).append($.create('div', {'class':'clear'}))

        // different header
        this.countLabel = $.create('span', {'class':'countLabel'})
        this.headerClose = $.create('a', {'href':'javascript:void(0)','class':'fright'}).append(this.strings.popup_close)
        this.header.empty()
        this.header.append($.create('h2').append(this.headerClose).append(this.countLabel).append($.create('span', {}, this.strings.popup_header)))

        // different footer
        this.bottomButton = $.create('input',{'type':'submit','class':'button','value': this.strings.submit_value});
        this.footer.append($.create('div', {'class':'confirm'}).append(this.bottomButton).append($.create('div', {'class':'button-end'})))

        $(this.bottomButton).bind("click", function(event) {
            EducityUtilities.submitForm()
        })
    }
})

var CompanyPopup = new $.klass(SelectorsPopup, {
    initialize: function($super, settings) {
        $super(settings)

        this.body.empty()

        this.body.append('Vyhledávání ')
        this.body.append($.create('input',{'type':'text','class':'companiesInputText','autocomplete':'off','id':'searchSuggest'}))

        var select=$.create()
        var companiesArray= new Array();

        $(this.selectItems).each(function(index, item) {
            for (var key in item) {}
            if(Educity.instances.companies.isSelectedItem(item.id)) {
                select.append($.create('option',{'value':item.id,'class':'option','selected':'selected'}).append(item.name))
            } else {
                select.append($.create('option',{'value':item.id,'class':'option'}).append(item.name))
            }
            companiesArray.push(item.name+"||"+item.id);
        })

        select.wrapInner('<select class="companiesMultiSelect" id="companiesMultiSelect" multiple="multiple"></select>')

        this.body.append(select)
        this.multiselect()

        function findValue(li) {
            if( li == null ) {
                return false
            }
            var companyId=li.selectValue.split("||")
            companyId=companyId[1]

            $('#companiesMultiSelect').toChecklist("check-"+companyId)
            $("#searchSuggest").val("")
        }

        function selectItem(li) {
            findValue(li)
        }

        function formatItem(row) {
            var companyName=row[0].split("||");
            return companyName[0];
        }

        function lookupLocal() {
            var oSuggest = $("#searchSuggest").autocompleter
            oSuggest.findValue()
            return false
        }

        $("#searchSuggest").autocompleteArray(companiesArray, {
            delay:10,
            minChars:1,
            matchSubset:1,
            matchContains:1,
            cacheLength:10,
            onItemSelect:selectItem,
            onFindValue:findValue,
            formatItem:formatItem,
            autoFill:0,
            selectOnly:true,
            selectFirst:true,
            maxItemsToShow:10
        })
    },
    multiselect: function() {
        $('#companiesMultiSelect').toChecklist()
    }
})

/**
 * Spolecna trida pro selectorove prvky
 * @alias SelectorBase
 * @param {Object} settings[optional]
 * @return {SelectorBase}
 * @constructor
 */
var SelectorBase = new $.klass({
    initialize: function(settings) {
        jQuery.extend(settings, Educity.settings.selector)
        jQuery.extend(this, settings)

        // get selected items from page
        var _this = this
        this.selectedItems = new Array()
        if (this.data) {
            $(this.data).each(function(index, item) {
                _this.selectedItems.push(item)
            })
        }

        // page elements
        this.selector = $(this.selectorId)
        this.form = $(this.formId)

        // red elements
        this.selectedItemsElement = $(this.selectedItemsElementId)
        this.selectedItemsContainer = $(this.selectedItemsElementId + ' .container')
    },
    /*
     * update selected items count and links text
     */
    updateSelectedItemsText: function() {
        var size = this.selectedItems.length
        if (size > 0) {
            this.openLink.text(this.strings.edit)
            if (this.popup) {
                this.popup.countLabel.text(this.strings.popup_count_label + ' ' + size)
            }
            this.selectedItemsElement.show()
            $(this.selectedItemsElementId + ' .all').hide()
        } else {
            $(this.openLink).text(this.strings.enter)
            if (this.popup) {
                this.popup.countLabel.empty()
            }
            $(this.selectedItemsElementId + ' .all').show()
        }
    },
    /*
     * remove item
     */
    removeItem: function(id) {
        this.selectedItems = jQuery.grep(this.selectedItems, function(value, index){
            return (value != id)
        })

        if ($('#popupItem_' + id).length > 0) {
            $('#popupItem_' + id).attr('checked', false)
        }
        if ($('#selectedItem_' + id).length > 0) {
            $('#selectedItem_' + id).remove()
        }
        if ($('#hiddenItem_' + id).length > 0) {
            $('#hiddenItem_' + id).remove()
        }

        this.updateSelectedItemsText()

        console.log('remove item - id = ' + id)
    },
    /*
     * add item
     */
    addItem: function(id) {
        var item = this.getNode(id, this.tree)
        var name = item.name.split(" ").join("&nbsp;")

        if ($('#popupItem_' + id).length > 0) {
            $('#popupItem_' + id).checked = true
        }

        if ($('#hiddenItem_' + id).length < 1) {
            var hiddenInput = $.create('input',{'type':'hidden','class':'hiddenSelectedItem','name':this.hiddenItemName,'value':id,'id':'hiddenItem_'+id})
            this.form.append(hiddenInput)
        }

        if ($('#selectedItem_'+id).length < 1) {
            var link = $.create('a',{'href':'javascript:void(0)','id':'selectedItem_'+id,'class':'selectedItem','_id':id}).html(name)
            this.selectedItemsContainer.append(link)
            $(link).bind('click', this, this.removeSelectedItem)
        }

        this.selectedItems.push(id)
        this.updateSelectedItemsText()

        console.log('add item - id = ' + id + ', ' + name)
    },
    isSelectedItem: function (id) {
        for (var i = this.selectedItems.length; i--;) {
            if (this.selectedItems[i] == id) {
                return true
            }
        }
        return false
    },
    /*
     * shows this element, register selector events ignore handler
     */
    show: function() {
        // get position
        position = this.panel.offset()
        position.top = this.panel.offset().top + this.panel.height()
        position.left += 10
        width = $("#body").width()

        // show
        this.popup.show(position, width)
    },
    /*
     * unregister selector handler, hide this element, updates link text,
     */
    hide: function() {
        if (this.popup) {
            this.popup.hide()
        }
    },
    /***
     * Vyrenderuje do ciloveho popupu seznam checkboxu z enumeration.
     *
     * @param {Object} enumeration
     * @param {Object} targetPopup
     */
    render: function(enumeration, targetPopup) {
     var _this = this
        if (targetPopup) {
            targetPopup.list.empty()
            $(enumeration).each(function(index, item) {
                hasChildren = typeof(item.children) == 'undefined' ? false : true
                if (item.id && item.name) {
                    var pairValue = item
                } else {
                 for (var key in item) {}
                    var pairValue = {id: key, name: item[key]}
                }

                if (hasChildren) {
                    // first need of second level popup, create it
                    if (!_this.secondPopup) {
                        _this.createSecondLevelPopup()
                    }

                    // isert item (which has children) to first level popup
                    link = $.create('a', {'href':'javascript:void(0)','class':'closed subcategory','_id':item.id}, item.name)
                    listItem = $.create('li', {'class':'pair'}).append(link)
                    targetPopup.list.append(listItem)
                    $(link).bind('click', _this, function(event) {
                        link = event.target
                        _this = event.data
                        // TODO header _this.secondPopup.header.update(link.text)
                        _this.render(_this.getNode($(link).attr('_id'), _this.tree).children, _this.secondPopup)
                        position = targetPopup.element.offset()
                        position.top += 50
                        position.left += 20
                        width = targetPopup.element.width()
                        _this.secondPopup.show(position, width)
                    })
                } else {
                    var li = $.create('li', {'class':'pair'}).html($.template(pairValue, _this.itemTemplate)).bind('click', _this, _this.popupItemClick)
                    targetPopup.list.append(li)
                    if (_this.hiddenItemName == 'topic2') {
                        _this.selectedItems = Educity.data.fromPageTopics
                    }
                    if (_this.isSelectedItem(pairValue.id)) {
                        // check checkbox
                        $('#popupItem_' + pairValue.id).attr('checked', true)
                        console.log("Checking selected checkbox with id = " + pairValue.id + ", name = '" + pairValue.name + "'.")
                    }
                }
            })
        }
        if (_this.selectedItems.length > 0) {
            var items = this.selectedItems
            this.selectedItems = new Array()

            $(items).each(function(index, item) {
                if ($('#selectedItem_' + item).length > 0) {
                    $('#selectedItem_' + item).remove()
                }
                _this.addItem(item)
            })
        } else {
            this.updateSelectedItemsText()
        }
    },
    createSecondLevelPopup: function() {
        console.log('creating second level popup')
        this.secondPopup = new Popup({strings:this.strings})
        //different header
        this.secondPopup.countLabel = $.create('span')
        this.secondPopup.headerClose = $.create('a', {'href':'javascript:void(0)','class':'fright'}).append(this.secondPopup.strings.popup_close)
        this.secondPopup.header.empty()
        this.secondPopup.header.append($.create('h2').append(this.secondPopup.headerClose).append(this.secondPopup.countLabel).append($.create('span', {}, this.secondPopup.strings.popup_header)))

        this.secondPopup.list = $.create('ul', {'class': 'pairList'}).appendTo(this.secondPopup.body)
        this.secondPopup.body.append($.create('div', {'class':'confirm'}).append(this.secondPopup.countLabel).append(this.secondPopup.bottomClose))
        this.secondPopup.body.append($.create('div', {'class':'clear'}))
        this.secondPopup.parent = this.popup
        this.secondPopup.element.css({zIndex:parseInt(this.secondPopup.parent.element.css('z-index'), 10) + 1})

        // different footer
        this.bottomButton = $.create('input',{'type':'submit','class':'button','value': this.secondPopup.strings.submit_value});
        this.secondPopup.body.append($.create('div', {'class':'confirm'}).append(this.bottomButton).append($.create('div', {'class':'button-end'})))

        $(this.bottomButton).bind("click", function(event) {
            EducityUtilities.submitForm()
        })

        if (this.secondPopup.headerClose) {this.secondPopup.headerClose.bind('click', this.secondPopup, function(event){
            event.data.hide()
     })}

    },
    getNode: function(id, tree) {
        topic = null
        var _this = this
        $(tree).each(function(index, item) {
            if (topic) {
                return false
            }

            if (!item.id) {
                for (var key in item) {}
                var pair = {
                    id: key,
                    name: item[key]
                }

                if (pair.id == id) {
                    topic = pair
                    return topic
                }
            }

            if (item.id == id) {
                topic = item
                return topic
            }

            if (typeof(item.children) != 'undefined') {
                temp = _this.getNode(id, item.children)
                if (temp) {
                    topic = temp
                    return topic
                }
            }
        })
        console.log(topic)
        return topic
    },

    // --- HANDLERS

    /*
     * remove selected item handler
     */
    removeSelectedItem: function(event) {
        event.data.removeItem($(event.target).attr('_id'))
    },
    /*
     * popup item click event handler
     */
    popupItemClick: function(event) {
        if (!event.target.id) {
            return
        }

     // this reference
        var _this = event.data

        var id = event.target.value
        if (event.target.checked) {
            _this.addItem(id)
        } else {
            _this.removeItem(id)
        }
    },
    /*
     * stops event default action and propagation
     */
    ignoreEventHandler: function(event) {
        event.preventDefault()
        event.stopPropagation()
    }
})

var SelectorTopics = new $.klass(SelectorBase, {
    initialize: function($super, settings) {
        jQuery.extend(settings, Educity.settings.topics)
        $super(settings)

        // page elements
        this.select = $(this.selectId).empty()
        this.openLink = $(this.openId)
        this.panel = $(this.panelId).hide().removeClass('display-none')

        // fill topics select with data
        var _this = this
        this.select.append($.create('option', {'value':-1,'selected':'selected'}, '-------- vše --------'))
        $(this.tree).each(function(index, value) {
            var option = $.create('option', {'value':value.id}, value.name)
            _this.select.append(option)
        })

        // register event handlers
        if (this.openLink) {
            $(this.openLink).bind('click', this, function(event) {
                event.data.show()
            })
        }
        if (this.select) {
            $(this.select).bind('change', this, this.changeTopic)
            $(this.select).bind('keyup', this, this.changeTopic)
        }

        // load fetched values
        console.log('SLECTED topics : ' + this.selectedItems)
        if (this.selectedItems.length > 0) {
            // prvni vybrane tema
            id = this.selectedItems[0]

            // existuje id?
            if (id > 0) {
                //
                if (this.isTopic(id)) {
                    console.info('Topics - found selected topic')
                    option = {id:id,index:this.getTopicIndex(id),isTopic:true}
                    this.changeTopic(null, option)
                    this.selectedItems = new Array()
                } else {
                    console.info('Topics - found selected subtopics')
                    var topicObj = this.getParentTopic(id)
                    if (topicObj) {
                        option = {
                            id: topicObj.id,
                            index: this.getTopicIndex(topicObj.id)
                     }
                        this.changeTopic(null, option)
                    } else {
                        console.warn('Topics - cannot find topic for selected subtopics, subtopics IDs: ' + this.selectedItems)
                    }
                }
            } else {
                this.loadSelectedMenuitem()
            }
        } else {
            this.loadSelectedMenuitem()
        }
        console.info(Educity.instances.type + 'Selector: Topics loaded')
       if($('#topicsSelect').length > 0){
            $('#topicsSelect').selectbox({replaceInvisible: true})
       }

    },
    loadSelectedMenuitem: function() {
        if (this.menuitem) {
            option = {id:this.menuitem,index:this.getTopicIndex(this.menuitem)}
            this.changeTopic(null, option)
        }
    },
    show: function($super) {
        // rendered elements
        if (!this.popup) {
            console.log('Creating popup')
            this.popup = new SelectorsPopup({strings:this.strings, modal:true})

            if (this.popup.bottomClose) {
                $(this.popup.bottomClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }
            if (this.popup.headerClose) {
                $(this.popup.headerClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }

            var id = this.select[0].options[this.select[0].selectedIndex].value
            if (id > -1) {
                if (this.isTopic(id)) {
                    option = {id:id,index:this.getTopicIndex(id),isTopic:true}
                    this.changeTopic(null, option)
                } else {
                    console.log('Topics - found selected subtopics')
                    option = {id:this.getParentTopic(id).id,index:this.getTopicIndex(this.getParentTopic(id).id)}
                    this.changeTopic(null, option)
                }
            } else {
                this.loadSelectedMenuitem()
            }
        }

        $super()
    },
    addItem: function($super,id) {
        if (!this.isTopic(id)) {
            $super(id)
        }
    },
    // --- TOPIC SPECIFIC FUNCTIONS

    /*
     * tries to find node from id in tree
     */
    getNode: function(id, tree) {
        topic = null
     var _this = this
        $(tree).each(function(index, value) {
            if (topic) {
                return false
            }

            if (value.id == id) {
                topic = value
                return topic
            }

            if (typeof(value.children) != 'undefined') {
                temp = _this.getNode(id, value.children)
                if (temp) {
                    topic = temp
                    return topic
                }
            }
        })
        return topic
    },
    /*
     * tries to find topic from id in tree, topic must have children
     */
    getTopic: function(id, tree) {
        topic = null
        $(tree).each(function(index, value) {
            if (typeof(value.children) != 'undefined' && value.id == id) {
                topic = value.children
            }
        })
        return topic
    },
    /*
     * returns true if item is first level topic
     */
    isTopic: function(id) {
        topic = false
        $(this.tree).each(function(index, value) {
            if (topic) {
                return false
            }
            if (value.id == id) {
                topic = true
            }
        })
        return topic
    },
    /*
     * returns first level topic
     */
    getParentTopic: function(id) {
        topic = null
        var _this = this
        $(this.tree).each(function(index, value) {
            if (topic) {
                return false
            }
            if (typeof(value.children) != 'undefined') {
                if (_this.getNode(id, value.children)) {
                    topic = value
                }
            }
        })
        return topic
    },
    /*
     * returns first level topic
     */
    getTopicIndex: function(id) {
        result = null
        $(this.tree).each(function(index, value) {
            if (result) {
                return false
            }
            if (value.id == id) {
                result = index + 1
            }
        })
        return result
    },
        updateSelectedItemsText: function() {
        var size = this.selectedItems.length
        if (size > 0) {
            $(this.panel).children('.caption9').text(this.strings.edit)
            if (this.popup) {
                this.popup.countLabel.text(this.strings.popup_count_label + ' ' + size)
            }
            this.selectedItemsElement.show()
            $(this.selectedItemsElementId + ' .all').hide()
        } else {
            $(this.panel).children('.caption9').text(this.strings.enter)
            if (this.popup) {
                this.popup.countLabel.empty()
            }
            $(this.selectedItemsElementId + ' .all').show()
        }
    },
    /*
     * select change handler
     */
    changeTopic: function(event, value) {
        if (event == null) {
            var _this = this
            var id = value.id
            _this.select[0].selectedIndex = value.index
            if (value.isTopic) {
                _this.selectedItems = new Array()
            }
        } else {
            var _this = event.data
            id = event.target.value
            $('#selectorForm').attr('action', topicsUrls["" + id])

            $(_this.selectedItems).each(function(index, item) {

                console.log(item)
                if (item >0) {
                    $('#hiddenItem_' + item).remove()
                    $('#selectedItem_' + item).remove()
                    _this.selectedItems.splice(index)
                }
            })
            _this.selectedItems = new Array()

        }

        if (_this.selectedItemsContainer) {
            if (id < 0) {
                _this.panel.hide()
                _this.hide()
                return
            }
            topic = _this.getTopic(id, _this.tree)

            if (topic) {
             _this.render(topic, _this.popup)
                _this.panel.show()
            } else {
                _this.panel.hide()
                _this.hide()
            }
        }
    }
})

var SelectorLanguageLevel = $.klass(SelectorBase, {
    initialize: function($super, settings) {
        jQuery.extend(settings, Educity.settings.languageLevel)
        $super(settings)

        // page elements
        this.openLink = $(this.openId)
        this.panel = $(this.panelId).removeClass('display-none')

        // register event handlers
        if (this.openLink) {
            $(this.openLink).bind('click', this, function(event) {
                event.data.show()
            })
        }

        // load fetched values
        this.render(this.tree, this.popup)
        console.info(Educity.instances.type + 'Selector: Language level loaded')
    },
    show: function($super) {
        // rendered elements
        if (!this.popup) {
            console.log('Creating popup')

            this.popup = new SelectorsPopup({strings:this.strings, modal:true})

            if (this.popup.bottomClose) {
                $(this.popup.bottomClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }
            if (this.popup.headerClose) {
                $(this.popup.headerClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }

            this.render(this.tree, this.popup)
        }

        $super()
    },
    updateSelectedItemsText: function() {
        var size = this.selectedItems.length
        if (size > 0) {
            this.panel.text(this.strings.edit)
            if (this.popup) {
                this.popup.countLabel.text(this.strings.popup_count_label + ' ' + size)
            }
            this.selectedItemsElement.show()
            $(this.selectedItemsElementId + ' .all').hide()
        } else {
            $(this.panel).text(this.strings.enter)
            if (this.popup) {
                this.popup.countLabel.empty()
            }
            $(this.selectedItemsElementId + ' .all').show()
        }
    }
})

var SelectorLanguageContent = $.klass(SelectorBase, {
    initialize: function($super, settings) {
        jQuery.extend(settings, Educity.settings.languageContent)
        $super(settings)

        // page elements
        this.openLink = $(this.openId)
        this.panel = $(this.panelId).removeClass('display-none')

        // register event handlers
        if (this.openLink) {
            $(this.openLink).bind('click', this, function(event) {
                event.data.show()
            })
        }

        // load fetched values
        this.render(this.tree, this.popup)
        console.info(Educity.instances.type + 'Selector: Language content loaded')
    },
    show: function($super) {
        // rendered elements
        if (!this.popup) {
            console.log('Creating popup')

            this.popup = new SelectorsPopup({strings:this.strings, modal:true})

            if (this.popup.bottomClose) {
                $(this.popup.bottomClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }
            if (this.popup.headerClose) {
                $(this.popup.headerClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }

            this.render(this.tree, this.popup)
        }

        $super()
    },
    updateSelectedItemsText: function() {
        var size = this.selectedItems.length
        if (size > 0) {
            this.panel.text(this.strings.edit)
            if (this.popup) {
                this.popup.countLabel.text(this.strings.popup_count_label + ' ' + size)
            }
            this.selectedItemsElement.show()
            $(this.selectedItemsElementId + ' .all').hide()
        } else {
            $(this.panel).text(this.strings.enter)
            if (this.popup) {
                this.popup.countLabel.empty()
            }
            $(this.selectedItemsElementId + ' .all').show()
        }
    }
})

var SelectorCompanies = $.klass(SelectorBase, {
    initialize: function($super, settings) {
        jQuery.extend(settings, Educity.settings.companies)
        $super(settings)

        // page elements
        this.openLink = $(this.openId)
        this.panel = $(this.panelId).removeClass('display-none')

        // register event handlers
        if (this.openLink) {
            $(this.openLink).bind('click', this, function(event) {
                event.data.show()
            })
        }

        var _this = this
        $('#companySelect option').each(function(index, item){
            $(this).bind('click', function(event) {
                option = event.target
             company = {id:option.value, index:option.index, name:option.text}
                if (option.selected) {
                    _this.addItem(company)
                } else {
                    _this.removeItem(company)
                }
            })
        })

        console.info(Educity.instances.type + 'Selector: Companies loaded')
    },
    show: function($super) {
        if (!this.popup) {
            console.time('Rendering companies popup')
            this.popup = new CompanyPopup({strings:this.strings, selectItems:this.tree, modal:true})

            if (this.popup.bottomClose) {
                $(this.popup.bottomClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }

            if (this.popup.headerClose) {
                $(this.popup.headerClose).bind('click', this, function(event) {
                    event.data.hide()
                })
            }

            this.render(this.tree, this.popup)
            console.timeEnd('Rendering companies popup')
        }

        $(this.selectId).toChecklist('update')
     $super()
        $('#searchSuggest').focus()
    },
    updateSelectedItemsText: function() {
        var size = this.selectedItems.length
        if (size > 0) {
            this.panel.text(this.strings.edit)
            if (this.popup) {
                this.popup.countLabel.text(this.strings.popup_count_label + ' ' + size)
            }
            this.selectedItemsElement.show()
            $(this.selectedItemsElementId + ' .all').hide()
        } else {
            $(this.panel).text(this.strings.enter)
            if (this.popup) {
                this.popup.countLabel.empty()
            }
            $(this.selectedItemsElementId + ' .all').show()
        }
    }
})

var Timer = $.klass({
    initialize: function(name, timeout, callback) {
        this.name = name
        this.timeout = timeout
        this.callback = callback
        this.id = null
        this.running = false
        console.log('Timer ' + this.name + ' - initialized')
    },
    start: function() {
        this.id = setTimeout(this.callback, this.timeout)
        this.running = true
    },
    stop: function() {
        clearTimeout(this.id)
        this.running = false
    }
})

var Partners = $.klass({
    initialize: function() {
        if($('#partneri').hasClass('hide-me')) {
            $('#partneri').hide()
            $('#partnersLink').bind('click', function(event) {
                $('#partneri').toggle()
            })
        }
    }
})

var Calendar = $.klass({
    initialize: function(settings) {
        jQuery.extend(settings, Educity.settings.calendar)
        jQuery.extend(this, settings)
        var reference = this
        EducityUtilities.getJsLibrary(this.path, function() {
            reference.construct()
        }, function() {
            return window.DateChooser ? true : false
        })
        console.info(this.path + ' loading started')
    },
    construct: function () {
        this.from = $(this.inputFromId)
        this.from.DateChooser = new DateChooser()
        this.from.DateChooser.setUpdateField(this.inputFromId, 'j.n.Y')
        this.from.DateChooser.setOpen(this.from)
        this.from.DateChooser.setYOffset(22)
        this.from.next().bind('click', this.from, function(event){
            event.data.focus()
        })
        this.till = $(this.inputTillId)
        this.till.DateChooser = new DateChooser()
        this.till.DateChooser.setUpdateField(this.inputTillId, 'j.n.Y')
        this.till.DateChooser.setOpen(this.till)
        this.till.DateChooser.setYOffset(22)
        this.till.next().bind('click', this.till, function(event){
            event.data.focus()
        })
        jQuery.extend(objPHPDate, this.strings)
    }
})

var Fulltext = $.klass({
    initialize: function(settings) {
        jQuery.extend(this, settings)

        // click on list item
        $('.fulltextLink').click(function(event) {
            event.preventDefault()
            Educity.instances.fulltext.switchTab($(event.target).closest('li'), $('#fulltextSearch .selected'))
            if($('#fulltext').attr('value')!=Educity.instances.fulltext.strings[$('#fulltextSearch .selected').attr('id')]){
                $('#fulltextSubmit').click()
            }
        })

        // input events
        var fulltext = $('#fulltext').focus(function(event) {
            Educity.instances.fulltext.focus(fulltext)
        }).blur(function(event) {
            Educity.instances.fulltext.blur(fulltext)
        })

        // prevent submiting default texts
        $('#fulltextSubmit').click(function(event) {
            if (fulltext.attr('value') === Educity.instances.fulltext.strings[$('#fulltextSearch .selected').attr('id')]) {
                fulltext.attr('value', '')
            }
        })

        // clear input before page reload
        $(window).unload(function(event) {
            fulltext.attr('value','')
        })
    },
    switchTab: function(clicked, selected) {
        // if selected tab is clicked do nothing
        if (clicked[0] === selected[0]) {
            console.log('Fulltext - clicked same tab, ignoring')
            return
        }

        //change helpText
        if ($('#fulltext').attr('value') === Educity.instances.fulltext.strings[$('#fulltextSearch .selected').attr('id')]){
            $('#fulltext').attr({
                'value': Educity.instances.fulltext.strings[clicked.attr('id')],
                'class':'fulltextHelper'
            })
        }

        // switch 'selected' class
        selected.removeClass('selected')
        clicked.addClass('selected')

        // switch form action attribute to selected link address
        $('#fulltextForm').attr('action', clicked.find('a').attr('href'))

        console.log('Fulltext - switched selected tab from \'' + selected.attr('id') + '\' to \'' + clicked.attr('id') + '\'')
    },
    focus: function(fulltext) {
        if ($(fulltext).attr('value') == Educity.instances.fulltext.strings[$('#fulltextSearch .selected').attr('id')]) {
            $(fulltext).attr('value', '')
            $(fulltext).removeClass('fulltextHelper')
        }
    },
    blur: function(fulltext) {
        if (!$(fulltext).attr('value')) {
            $(fulltext).addClass('fulltextHelper')
            $(fulltext).attr('value', Educity.instances.fulltext.strings[$('#fulltextSearch .selected').attr('id')])
        }
    }
})

var LoginAsUser = $.klass({
    initialize: function() {
        // for each link with username register click event
        var _this = this
        $('#loginAsUser .value').each(function(index, item) {
            $(this).bind('click', _this, _this.loadLogin)
        })
    },
    loadLogin: function(event) {
        var _this = event.data

        // stops event propagation
        event.preventDefault()

        // update input
        $('#login-as-username').attr('value', event.target.text)

     console.log('LoginAsUser value has been set to: ' + event.target.text)
    }

})

var IntroJobcity = $.klass({
    initialize: function(){
        //intro jobcity
        $('#introJobcitySearch').attr('value', Educity.data.selectorStrings['jobcity'].findBetterJob)
        $('#introJobcitySearch').bind('focus', this, function(event){
            if ($(this).attr('value') == Educity.data.selectorStrings['jobcity'].findBetterJob) {
                $(this).attr('value', '').removeClass('gray')
            }
        })
        $('#introJobcitySearch').bind('blur', this, function(event){
            if (!$(this).attr('value')) {
                $(this).attr('value', Educity.data.selectorStrings['jobcity'].findBetterJob).addClass('gray')
            }
        })
    }
})


var Utils = $.klass({
    initialize: function() {
        // presunuti sponzorovanch kurzu do vypisu
        if ($('.hiddenSponsored').length > 0) {
            $('#coursesList').children('.head').after($('.hiddenSponsored').children('.sponsored').removeClass('display-none'))
        }
        // bookmarky v administraci
        $("#checkAll").click(function(){
            var checked_status = this.checked
            $("#bookmarksForm input[type=checkbox]").each(function(){
                this.checked = checked_status
            })
        })
        // poptavkove formulare - vybirani firmy/osoby
        $("#radioPerson").click(function(){
            $("#dutyCompany").html("").parents('.line').find('input').removeClass('required')
        })
        $("#radioCompany").click(function(){
            $("#dutyCompany").html("* ").parents('.line').find('input').addClass('required')
        })

        // zobrazeni a skryti rozsireneho selectoru
        $('#toggleAdvanced a').bind('click', function(event){
            // stops event propagation
            event.preventDefault()
            event.stopPropagation()
            // show element with link
            if($('#advancedSelector').hasClass('display-none')){
                $('#advancedSelector').removeClass('display-none')
                $('#selectorFulltext, #selectorSubmit').removeAttr('style')
                $(this).removeClass('increase').addClass('collapse')
            }else{
                $('#advancedSelector').addClass('display-none')
                $('#selectorFulltext').attr('style','width:85%;')
                $('#selectorSubmit').attr('style','margin-top:-2.6em;')
                $(this).removeClass('collapse').addClass('increase')
            }
            var linkText=$(this).attr("name")
            $(this).attr("name",$(this).html()).html(linkText)
        })

        // skryti selectoru
        if($('#toggleAdvanced a').length){
            $('#toggleAdvanced a').click()
        }



        // bubliny
        if (typeof($.fn.bt) == 'function') {
            $('.popupHelp').bt({
                trigger: ['focus', 'blur'],
                vposition: "right"
            })
            // bubliny - vypis kurzu
            $('#coursesList').find('.price').find('a').bt({})
            // bubliny - last minute vypis
            $('#lastMinuteList').find('.price').children('a').bt({})
            //bublina u cerva na uvodce
            $('#benefit .worm').bt({})
            //bubliny - hlavni menu
            $('#navigation:not(.sub)').find('a').bt({})
        }
        function resetForm(id){
            $('#' + id).each(function(){
                this.reset()
            })
        }
        // katalogy - zobrazovani a skryvani kategorii
        $('.block-catalogue .showCategories').bind('click', function(event){
            var hiddenCategories = $(this).parents('.catItems').children('ul').children('.hidden')
            if ($(hiddenCategories).length > 0) {
                event.preventDefault()
                event.stopPropagation()
            }
            if (hiddenCategories.hasClass('display-none')) {
                //show element
                $(hiddenCategories).removeClass('display-none')
                $(hiddenCategories).addClass('display-inline')
                $(this).html('Skrýt kategorie')
            }
            else {
                // hide element
                $(hiddenCategories).removeClass('display-inline')
                $(hiddenCategories).addClass('display-none')
                $(this).html('Více kategorií')
            }
        })
        //tisk stranky
        $('.openPrintDialog').bind('click', this, function(event){
            event.preventDefault()
            event.stopPropagation()
            window.print();
        })

       $('#searchSiteSub').click(function(){
           $('#fulltextForm').attr('action',$(this).attr('value'))
       })

       $('#searchSiteEdu').click(function(){
           $('#fulltextForm').attr('action',$(this).attr('value'))
       })
    }
})

// strom kategorii
var CategoryTree = $.klass({
    initialize: function(settings) {
        jQuery.extend(this, settings)
    },
    toggleTree: function(id) {
        $(id + ' .treeview, ' + id + ' .open').toggle()
        $(id + ' .toggle').children().toggleClass('expanded')
        if ($(id + ' .toggle').children().hasClass('expanded')) {
            $(id + ' .toggle').children().text(this.strings.close)
        } else {
            $(id + ' .toggle').children().text(this.strings.open)
        }
    },
    initTree: function(id) {
        if ($(id).length) {
            // schovavaci link v nadpisu
            $(id + ' h2').before($.create('span', {'class':'toggle'}).append('( ').append($.create('a', {'href':'#katalog', 'class':'expanded'}, this.strings.close)).append(' )'))
            // zaviraci link
            $(id + ' .treeview').before($.create('p', {'class':'open'}).hide().append($.create('span', {'class':'hitarea'})).append($.create('a', {'href':'#katalog'}, this.strings.open)))
            // spusteni stromu
            $(id + ' .treeview').treeview({animated:100, collapsed: true})
            // event kliknuti schovavaci a zaviraci link
            $(id + ' .open a, ' + id + ' .toggle a').click(function(event) {
                Educity.instances.tree.toggleTree(id)
                event.preventDefault()
                event.stopPropagation()
            })
            // event kliknuti na link vetve
            $(id + ' .branch a').click(function(event) {
                event.preventDefault()
                event.stopPropagation()
                $(this).parent().siblings('.hitarea').click()
            })
            // event kliknuti na obrazek slozky
            $(id + ' strong:has(img)').click(function(event) {
                $(this).siblings('.hitarea').click()
            })
            // event kliknuti na +/- ve stromu
            $(id + ' .hitarea').click(function(event) {
                var img = $(this).siblings('strong').children('img')
                if(img.attr('src') == '/static/educity/images/category-tree-node.gif') {
                    img.attr('src','/static/educity/images/category-tree-node-opened.gif')
                } else {
                    img.attr('src','/static/educity/images/category-tree-node.gif')
                }
            })
        }
    },
    initCourseTree: function(id) {
        // spusteni stromu
        $(id + ' .treeview').treeview({animated:100, collapsed: true})
        // event kliknuti na ikonku vetve
        $(id + ' .branch img').click(function(event) {
            event.preventDefault()
            event.stopPropagation()
            $(this).parent().siblings('.hitarea').click()
        })
        // event kliknuti na link vetve
        $(id + ' .branch a').click(function(event) {
            event.preventDefault()
            event.stopPropagation()
            $(this).parent().siblings('.hitarea').click()
        })
        // event kliknuti na +/- ve stromu
        $(id + ' .hitarea').click(function(event) {
            var img = $(this).siblings('strong').children('img')
            if(img.attr('src') == '/static/educity/images/category-tree-node.gif') {
                img.attr('src','/static/educity/images/category-tree-node-opened.gif')
            } else {
                img.attr('src','/static/educity/images/category-tree-node.gif')
            }
        })
    }
})

var ImageHover = new $.klass({
    initialize: function(id, img) {
        var images = img
        var elem = $(id)
        if(elem.length < 1) {
            return false
        }
        elem.each(function(index, item) {
            var img = new Image()
            $(img).load(function() {
                var smallDimensions = {width: $(item).attr('width'), height: $(item).attr('height')}
                var bigDimensions = {width: $(this).attr('width'), height: $(this).attr('height')}
                var div = $.create('div',{'class':'bigger'}).css({
                    'position': 'absolute',
                    'width': $(this).attr('width'),
                    'height': $(this).attr('height'),
                    'top': 0,
                    'left': 0,
                    'z-index': 100
                }).hide()
                if($(item).parent().filter('a').length > 0) {
                    div.append($.create('a',{
                        'href':$(item).parent().filter('a').attr('href'),
                        'class':'display-block'
                    }).append(img))
                } else {
                    div.append(img)
                }
                $('body').append(div)
                $(item).mouseover(function(event) {
                    var position = $(item).offset()
                    position.left -= (bigDimensions.width - smallDimensions.width) / 2
                    position.top -= (bigDimensions.height - smallDimensions.height) / 2
                    $(item).css('visibility','hidden')
                    div.css({
                        left: position.left,
                        top: position.top
                    }).show()
                })
                div.mouseout(function(event) {
                    div.hide()
                    $(item).css('visibility','')
                })
            }).attr('src', images[index])
        })
    }
})

$(document).ready(function() {
    var introCatalogueAnimation = new ImageHover('#introCatalogue .foto img', ['/static/educity/images/graphics-education-catalogue-large.gif'])
    var catalogueAnimation =  new ImageHover('.katalog-vzdelavani .education img', ['/static/educity/images/graphics-education-catalogue-large.gif'])

    /*
    console.time('Catalogue images loading')
    var introPromoAnimation = new ImageHover('#visual .graphics img', ['/static/educity/images/graphics-visual-promo1-large.jpg','/static/educity/images/graphics-visual-promo2-large.jpg'])
    var introCatalogueAnimation2 =  new ImageHover('#introCatalogue2 .foto img', ['/static/educity/images/graphics-catalogs-large.gif'])
    var catalogueAnimation =  new ImageHover('#katalog-vzdelavani .education img', ['/static/educity/images/graphics-catalogs-large.gif'])
    var catalogueAnimation2 =  new ImageHover('#katalog-vzdelavani .hotels img', ['/static/educity/images/graphics-catalogs-large.gif'])

    var introCourses =  new ImageHover('#introCourses img', ['/static/educity/images/categories/cat-intro-language.gif','/static/educity/images/categories/cat-intro-manager.gif','/static/educity/images/categories/cat-intro-it.gif','/static/educity/images/categories/cat-intro-courses.gif'])
    var introCompanies =  new ImageHover('#introCompanies img', ['/static/educity/images/categories/cat-intro-companies-courses.gif','/static/educity/images/categories/cat-intro-companies-consultings.gif','/static/educity/images/categories/cat-intro-companies-language.gif'])

    var courses = new ImageHover('.block-catalogue .courses img', ['/static/educity/images/categories/cat-courses-scheduled.gif','/static/educity/images/categories/cat-courses-custom.gif','/static/educity/images/categories/cat-companies-courses-scheduled.gif'])
    var languages = new ImageHover('.block-catalogue .languages img', ['/static/educity/images/categories/cat-language-scheduled.gif','/static/educity/images/categories/cat-language-custom.gif','/static/educity/images/categories/cat-companies-language-scheduled.gif'])
    var consultings = new ImageHover('.block-catalogue .consultings img', ['/static/educity/images/categories/cat-consultings.gif','/static/educity/images/categories/cat-companies-consultings.gif'])
    var companies = new ImageHover('.block-catalogue .companies img', ['/static/educity/images/categories/cat-companies-courses-scheduled.gif','/static/educity/images/categories/cat-companies-courses-custom.gif','/static/educity/images/categories/cat-companies-language-scheduled.gif','/static/educity/images/categories/cat-companies-language-custom.gif','/static/educity/images/categories/cat-companies-consultings.gif'])
    console.timeEnd('Catalogue images loading')
    */
})

$(document).ready(function() {
    if (jQuery.validator) {
        jQuery.extend(jQuery.validator.messages, {
            required: "Tento údaj je povinný.",
            remote: "Prosím, opravte tento údaj.",
            email: "Prosím, zadejte platný e-mail.",
            url: "Prosím, zadejte platné URL.",
            date: "Prosím, zadejte platné datum.",
            dateISO: "Prosím, zadejte platné datum (ISO).",
            number: "Prosím, zadejte číslo.",
            digits: "Prosím, zadávejte pouze číslice.",
            creditcard: "Prosím, zadejte číslo kreditní karty.",
            equalTo: "Prosím, zadejte znovu stejnou hodnotu.",
            accept: "Prosím, zadejte soubor se správnou příponou.",
            maxlength: jQuery.format("Prosím, zadejte nejvíce {0} znaků."),
            minlength: jQuery.format("Prosím, zadejte nejméně {0} znaků."),
            rangelength: jQuery.format("Prosím, zadejte od {0} do {1} znaků."),
            range: jQuery.format("Prosím, zadejte hodnotu od {0} do {1}."),
            max: jQuery.format("Prosím, zadejte hodnotu menší nebo rovnu {0}."),
            min: jQuery.format("Prosím, zadejte hodnotu větší nebo rovnu {0}.")
        });
    }
})

/* rozbalovaci editorial */
$(document).ready(function() {
    var text = $('#editorial h1')
    var span = $('#editorialMoreInfo span')
    var link = $('#editorialMoreInfo a').click(function(event) {
        event.preventDefault()
        event.stopPropagation()
        if (text.hasClass('visible')) {
            text.removeClass('visible')
            text.hide(300)
            link.text('Více informací')
            span.html('&#187;')
        } else {
            text.addClass('visible')
            text.show()
            link.text('Méně informací')
            span.html('&#171;')
        }
    })
})

/* rotovaci novinky */
$(document).ready(function() {
    var animate = function() {
        $('#newsBar .news > :first').fadeOut(400, function() {
            $('#newsBar .news > :last').fadeIn(400, function() {
                $('#newsBar .news > :first').before($('#newsBar .news > :last'))
            })
        })
    }
    var timer = $.timer(7000, function(timer) {
        animate()
    })
    $('#newsBar .news > *').hide()
    $('#newsBar .news > :first').show()
})

/* napoveda v selectorech */
$(document).ready(function() {
    var selectorFulltext = $('#selectorFulltext').focus(function(event) {
        if ($(selectorFulltext).attr('value') == $(selectorFulltext).attr('title')) {
            $(selectorFulltext).attr('value', '')
            $(selectorFulltext).removeClass('fulltextHelper')

            console.log($(selectorFulltext).attr('value'))
        }
    }).blur(function(event) {
        if (!$(selectorFulltext).attr('value')) {
            $(selectorFulltext).addClass('fulltextHelper')
            $(selectorFulltext).attr('value', $(selectorFulltext).attr('title'))
        }
    })

    // prevent help text submitting
    $('#selectorForm').find('.submit').find('input').click(function(event) {
        if (selectorFulltext.attr('value') == $(selectorFulltext).attr('title')) {
            selectorFulltext.attr('value', '')
        }
    })

    // clear input before page reload
    $(window).unload(function(event) {
        $(selectorFulltext).attr('value','')
    })
})

/* hover radek ve vypisu */
$(document).ready(function() {
    $('#coursesList .scheduled tr, #coursesList .custom tr, #coursesList .consultings tr, #sponsoredLinks tr').mouseenter(function(event) {
        $(this).addClass('over')
    }).mouseleave(function(event) {
        $(this).removeClass('over')
    })

/*
    $('#companiesList tr').mouseover(function(event) {
        console.log(this)
    }).mouseout(function(event) {
        console.log(this)
    })
*/
})

/*animovani cervi*/
$(document).ready(function() {
    var _this=$("#navigation .right.selected:not(.none), #navigation .left.selected:not(.none)")
    if(_this.css("background-image"))
    {
        _this.css("background-image",_this.css("background-image").replace(".jpg",".gif"))
        setTimeout('if($("#navigation .selected.double").length>0){$("#navigation .selected.double").attr("style",$("#navigation .selected.double").attr("style").replace(".gif","2.gif"))}', 4000)
    }
})

/*educity news - nacitani clanku*/
$(document).ready(function() {
    $(".articles-list a[rel=loadArticle]").click(function(event){
        event.stopPropagation()
        event.preventDefault()
        $('html,body').animate({scrollTop: $('#breadcrumb').offset().top},500);
        $(".educity-news").html("");
        $("#contentLoading").show()
        title=$(this).attr("title")
        url=$(this).attr('href')
        affix=', novinka z HR News';
        $(".educity-news").load('/portal/template/EcAjaxArticleDetail/id/'+$(this).attr("class"), {}, function(){
            $("#breadcrumb a:last").attr('href',url).html(title+affix)
            document.title=title+affix+' | EduCity';
            $("#contentLoading").hide()
        })
    })
})

$(document).ready(function() {
    // zbalovani slozek ve firemnim detailu
    function switchFolders(hide, folders) {
        var children = $(folders).children()
        var size = children.size()
        for (var i = 3; i < size; i++) {
            if (hide) {
                $(children[i]).hide()
            } else {
                $(children[i]).show()
            }
        }
    }

    // uvodni schovani vsech topicu
    $('#firma .folders .caption ul').each(function() {
        if ($(this).children().size() > 3) {
            // schovani slozek
            switchFolders(true, $(this))

            // pridani akcniho linku
            $(this).after('<a href="#" class="more-topics-switch">Rozbalit</a>')
        }
    })

    // event pro akcni link
    $('.more-topics-switch').click(function(event) {
        if ($(this).hasClass('less-topics-switch')) {
            $(this).removeClass('less-topics-switch')
            $(this).text('Rozbalit')
            switchFolders(true, $(this).siblings('ul'))
        } else {
            $(this).addClass('less-topics-switch')
            $(this).text('Sbalit')
            switchFolders(false, $(this).siblings('ul'))
        }
        event.preventDefault()
    })

    //ankety
    $(".survey a.vote").live("click",function(event){
        event.stopPropagation()
        event.preventDefault()

        surveyBlock=$(this).parents(".survey")
        surveyBlock.addClass("loader")

        $.get($(this).attr("href"), function(data) {
            surveyBlock.parent().load("/portal/template/EcAjaxLatestSurvey?surveyClass="+surveyBlock.children().attr("class"), false, function(){
                surveyBlock.removeClass("loader")
            });
        });
    })
})

$(document).ready(function() {
    if($(".social-links").length>0){
        function hideMenu() {
            if (!$('.custom_button').data('in') && !$('.hover_menu').data('in') && !$('.hover_menu').data('hidden')) {
                $('.hover_menu').fadeOut('fast');
                $('.custom_button').removeClass('active');
                $('.hover_menu').data('hidden', true);
            }
        }

        $('.custom_button, .hover_menu').mouseenter(function() {
            $('.hover_menu').fadeIn('fast');
            $('.custom_button').addClass('active');
            $(this).data('in', true);
            $('.hover_menu').data('hidden', false);
        }).mouseleave(function() {
            $(this).data('in', false);
            setTimeout(hideMenu, 400);
        });
    }
})
