$(document).ready(function() {
    // file at fileadmin/templates_3/js/pi_grdList.js
    /*------------------------------------------------------------------------------------------------------*/
    /* silbentrennung */
    function trennung() {
        if (glLocalConf.trennung === true) {
            var grdText = $('.grdList table thead tr th.we_grundrisse');
            if (grdText.text() == 'Grundrisse') grdText.text('Grund- risse');
            var grdText = $('.grdList table thead tr th.we_flaeche_hobbyraum');
            if (grdText.text() == 'Fläche Hobbyraum') grdText.text('Fläche Hobby- raum');
            var grdText = $('.grdList table thead tr th.we_anzahl_zimmer');
            if (grdText.text() == 'Zimmer-anzahl') grdText.text('Zimmer- anzahl');
            var grdText = $('.grdList table thead tr th.we_nummer');
            if (grdText.text() == 'Wohnung Nr.') grdText.html('Wohnung <br />Nr.');
        }
    }
    /*------------------------------------------------------------------------------------------------------*/
    /* get dom-elements */
    var gl = new Object;
    gl.trHead = $('.grdList table thead th');
    gl.trShort = $('.grdList table tbody tr.grdList_short');
    gl.trDetail = $('.grdList table tbody tr.grdList_detail');
    /*------------------------------------------------------------------------------------------------------*/
    /* browser detection */
    var client = parseInt(jQuery.browser.version);

    /*------------------------------------------------------------------------------------------------------*/
    /* reclink */
    /* we use addClass/removeClass to store the current cmd-string in the page */
    /* we get the orig-rec-url from spacial a */
    /* we append the rec-hash as get-param at the end of the recLink-get-params, */
    /* to convert it in the rec-form back to #hash */
    var recGrd_last = '';
    var recGrd_key = 'recGrd';
    var recUrl = $('#rec a#recCmd_initUrl').attr('href');

    function clearCmdGrd() {
        if (recGrd_last != '') {
            $('#recCmd').removeClass(recGrd_last);
            recGrd_last = '';
        }
        updateRecLinkGrd();
    }
    function updateRecLinkGrd() {
        var hash = $('#recCmd').attr('class');
        hash = jQuery.trim(hash);
        if (hash) {
            hash = '&recCmd=' + hash;
            hash = hash.replace(' ', '_');
        }
        $('#recCmd').html(hash);
        var recUrl_update = recUrl + hash;
        $('div a.jqRecCmd').attr('href', recUrl_update);
		return hash;
    }
    function parseIncomingHashGrd() {
        var inHash = window.location.hash;
        $('#inHash').html(inHash);
        var inCmd_i = '';
        if (inHash) {
            inHash = inHash.substr(1);
            inHash = inHash.split('_');
            inHash = jQuery.makeArray(inHash);
            inHash = jQuery.grep(inHash,
            function(v, i) {
                var v_arr = v.split('.');
                if (v_arr[0] == recGrd_key) {
                    return (v);
                }
            });
            inCmd_i = inHash[0].split('.');
            inCmd_i_number = Number(inCmd_i[1]);
            return (inCmd_i_number);
        }
    }
    /* ------------------------------------------------------------------------------------------------------*/
    /* reclink inject local */
    function injectLocal() {
        gl.trDetail.each(function(i) {
            $('#recLocal_draft').clone().removeAttr('id').prependTo($(this).children('td'));
        });
    }
    /* ------------------------------------------------------------------------------------------------------*/
    /* init functions */
    function grdInit(i) {
        resetFilter();
        trennung();
        if ($.browser.msie && client <= 7) $('.grdList table').attr('cellspacing', "0").attr('cellpadding', "0");
        gl.trHead.each(function(j) {
            $(this).width($(this).width());
        })
        gl.trShort.each(function(j) {
            if (j != i) hideDetail(j);
        })
        injectLocal();
        if (i >= 0) showDetail(i);
    }
    /* ------------------------------------------------------------------------------------------------------*/
    /*detail - show / hide functions */
    last_i = '';
    function showDetail(i) {
        //setCmdGrd(i);
        gl.trShort.addClass('passiveSkin');
        gl.trShort.eq(i).removeClass('passiveSkin').addClass('active');
        loadDetail(i);
        gl.trDetail.eq(i).addClass('active').fadeIn('slow');
        last_i = i;
    }
    function hideDetail(i) {
        clearCmdGrd();
        gl.trShort.removeClass('passiveSkin');
        gl.trShort.eq(i).removeClass('active');
        gl.trDetail.eq(i).removeClass('active').hide();
        last_i = '';
    }
    /* ------------------------------------------------------------------------------------------------------*/
    /* show / hide - both functions */
    function showByFilter(dom) {
        dom.addClass('active_filter').show();
        hideDetailAll();
        //gl.trDetail.eq(i).addClass('active_filter');
    }
    function hideByFilter(dom) {
        dom.removeClass('active_filter').hide();
        //gl.trDetail.eq(i).removeClass('active_filter').hide();
    }
    // used by filter select : reset switchboard, hide all detail-rows
    function hideDetailAll() {
        gl.trShort.removeClass('passiveSkin').removeClass('active');
        gl.trDetail.removeClass('active').hide();
        last_i = '';
    }
    // used by filter reset : reset switchboard, show all short-rows, hide all detail-rows
    function showShortAll() {
        gl.trShort.removeClass('passiveSkin').removeClass('active').removeClass('active_filter').fadeIn(1500);
        gl.trDetail.removeClass('active').hide();
        last_i = '';
    }
    /*------------------------------------------------------------------------------------------------------*/
    /* filter-DOM */
    jqhSelectors = $('.jqHead select');
    jqhResetButton = $('.jqHead input');
    /*------------------------------------------------------------------------------------------------------*/
    /* filter-resets */
    // resets the whole filter
    function resetFilter() {
        jqhSelectors.each(function() {
            var opts = $(this).children('option');
            opts.filter(':selected').removeAttr('selected');
            opts.eq(0).attr('selected', 'selected');
            // neede for some browsers
        });
        showShortAll();
        jqhResetButton.fadeOut('fast');
        return false;
    }
    // resets selects other than the current
    function resetForeignSelector(k) {
        $('.jqHead select').each(function(i) {
            if (i != k) {
                $(this).children('option').eq(0).attr('selected', 'selected');
            }
        });
    }
    /*------------------------------------------------------------------------------------------------------*/
    /* filter actions */
    jqhResetButton.click(function() {
        resetFilter();
    });
    jqhSelectors.each(function(i) {
        csb = $(this);
        csbOption = $(this).children('option');
        csb.change(function() {
            resetForeignSelector(i);
            // current option value from current selector
            sel = $(this).children("option:selected").val();
            if (sel != $(this).children().eq(0).val()) {
                // get affected class name from selector and assemble td-class-selector
                var affClass = $(this).attr('id');
                var affTd = $('.grdList table tbody td.' + affClass);
                if (affClass == 'we_flaeche_wohn') {
                    // --- wohnfläche
                    wflWanted = sel.split('.');
                    affTd.each(function() {
                        wflLocal = $(this).text();
                        wflLocal = Number(wflLocal.replace(',', '.'));
                        if (wflLocal >= wflWanted[0] && wflLocal <= wflWanted[1]) {
                            showByFilter($(this).parent());
                            // zsId = $(this).parent().attr('id');
                            // zsIdJQ = '#' + zsId + '_zs';
                            // $(zsIdJQ).show();
                        } else {
                            hideByFilter($(this).parent());
                        }
                    });

                } else {
                    // --- andere als wohnfläche
                    $(affTd).each(function() {
                        if ($(this).text() == sel) {
                            showByFilter($(this).parent());
                            // zsId = $(this).parent().attr('id');
                            // zsIdJQ = '#' + zsId + '_zs';
                            // $(zsIdJQ).show();
                        } else {
                            hideByFilter($(this).parent());
                        }
                    });
                }
                jqhResetButton.fadeIn();
            } else {
                // --- reset filter on option-0
                resetFilter();
            }
        });
    });
    /*------------------------------------------------------------------------------------------------------*/
    /* switchboard */
    gl.trShort.each(function(i) {
        var tar = $(this)
        tar.click(function() {
            if (tar.hasClass('active')) {
                hideDetail(i);
                // last_i = '';
            } else {
                hideDetail(last_i);
                showDetail(i);
                // last_i = i;
            }
        });
    });
    /*------------------------------------------------------------------------------------------------------*/
    /* load detail img function */
    function loadDetail(i) {
        var tar = gl.trDetail.eq(i);
        if (!tar.hasClass('loaded')) {
            // do set switch
            tar.addClass('loaded');
            // do get code
            var detailID = tar.attr('id');
            detailID = detailID.slice(7);
            var zoomUrls = eval('zoomUrls_' + detailID);
            // do get layout class
            if (zoomUrls.length > 1) layoutClass = 'layoutLeft';
            else layoutClass = 'layoutCenter';
            // do get insertTar
            var insertInDOM = tar.children('td').children('div').children('a.lb');
            // do set layoutLastClass
            insertInDOM.filter(':odd').addClass('layoutOdd')
            insertInDOM.filter(':last').addClass('layoutLast');
            // do insert
            insertInDOM.each(function(j) {
                // lightBox JS from fileadmin/templates/ts_page.ts page.includeJS.file4 = fileadmin/templates_3/js/jquery-lightbox-0.5/js/jquery.lightbox-0.5.pack.js
                // lightBox CSS from fileadmin/templates/ts_page.ts includeCSS.file1 = fileadmin/templates_3/js/jquery-lightbox-0.5/css/jquery.lightbox-0.5.css
                var temp = $(this).html(zoomUrls[j]).lightBox().addClass(layoutClass);
            });
        }
    }
    /*------------------------------------------------------------------------------------------------------*/
    /* show/hide short info function */
    var si = new Object;
    si.indices = $('.grdList_head .index');
    last_i_indices = '';
    si.indices.each(function(i) {
        var tar = $(this).children('ul').children('li').children('a');
        var tar_sec = $(this).siblings('div.section');
        tar.filter(':last').addClass('last').show();
        tar_sec.each(function(k) {
            var temp = tar.eq(k);
            temp.toggle(function() {
                temp.addClass('active');
                tar_sec.eq(k).show();
            },
            function() {
                temp.removeClass('active');
                tar_sec.eq(k).hide();
            });
        })
    });
    function getPageScroll() {
        var yScroll;
        if (self.pageYOffset) {
            yScroll = self.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            yScroll = document.documentElement.scrollTop;
        } else if (document.body) {
            // all other Explorers
            yScroll = document.body.scrollTop;
        }
        return yScroll;
    }
    /*------------------------------------------------------------------------------------------------------*/
    /* scroll to element */
    var recScrollAmount = 0;
    var recScrollDelta = 100;
    var rec_timer = null;
    var recEven = 0;
    function recScroll(top) {
        rec_timer = window.setTimeout(function() {
            // do transition
            recScrollAmount += recScrollDelta;
            if (recScrollDelta > 1) {
                recScrollDelta = Math.floor(recScrollDelta / 2);
            }
            else {
                recScrollDelta = 1;
            }
            window.scrollTo(0, recScrollAmount);
            // clear out
            window.clearTimeout(rec_timer);
            rec_timer = null;
            // restart
            if (recScrollAmount < top) recScroll(top);
        },
        20);
    }
    var rec_timer_init = null;
    function scrollToElement(i) {
        if (i > 0) {
            recScrollAmount = getPageScroll();
            window.scrollTo(0, recScrollAmount);
            $(window).load(function() {
                // run code
                var el = gl.trShort.eq(i);
                var offset = el.offset();
                var top = Math.floor(offset.top);
                recScrollDelta = (top - recScrollAmount) / 2;
                recScroll(top);
            });
        }
    }

    /*------------------------------------------------------------------------------------------------------*/
    /* execute init */
    if (glLocalConf.init_i !== false) {
        grdInit(glLocalConf.init_i);
    }
    else {
        var in_i_grd = parseIncomingHashGrd();
        scrollToElement(in_i_grd);
        grdInit(in_i_grd);
    }
});
