var currSize = 1;

function switchStyleSheetSrc(size) {
    var styleName = 'size'+size;
    $('link[@rel*=STYLE][@title]').each(function() {
        this.disabled = true;
        if($(this).attr('title')==styleName) {
            this.disabled = false;
        }
    });
    $.cookie('styles',size,{expires:7,path:'/'});
}

function disableAll() {
    $('link[@rel*=STYLE]').each(function() {
        this.disabled = true;
    });
}


function setBookmark() {
    var bookmarkurl = location.href;
    var text = document.title;
    text = text.replace(/:/ ,"");
    text = text.replace(/\*/ ,"");
    text = text.replace(/\?/ ,"");
    text = text.replace(/\\/ ,"");
    text = text.replace(/"/ ,"");
    text = text.replace(/</ ,"");
    text = text.replace(/>/ ,"");
    text = text.replace(/|/ ,"");
    if (window.sidebar) { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(text, bookmarkurl,"");
    } else if( window.external ) { // IE Favorite
        window.external.AddFavorite( bookmarkurl, text);
    } else if(window.opera && window.print) { // Opera Hotlist
        return true;
    }
}

$().ready(function() {
    if(document.all) {
        try {document.execCommand("BackgroundImageCache",false,true);} catch(e){}
    }
    $('#AddBookmark').click(function(){setBookmark(); return false;});
    $('#TextVersion').click(function(){disableAll(); return false;});

    if($.cookie('styles')) {
        currSize = parseInt($.cookie('styles'));
        var isActive = false;
        $('link[@rel*=STYLE][@title]').each(function() {
              if($(this).attr('rel').indexOf('ALTERNATE')==-1
                && $(this).attr('title')=='size'+currSize) {
                    isActive = true;
              }
        });
        $('#fs_size'+currSize).addClass('active');
        if(!isActive) {
            switchStyleSheetSrc(currSize);
        }
    }
    var maxSizes = $('#FontSizer .size').size();
    if(maxSizes > 0) {
        if(currSize==1) {
            $('#fs_minus').addClass('disabled');
        } else if(currSize==maxSizes) {
            $('#fs_plus').addClass('disabled');
        }
        $('#FontSizer .size').click(function() {
            currSize = parseInt(this.id.replace(/fs_size/g,''));
            $('#FontSizer .size').each(function(){$(this).removeClass('active');});
            $(this).addClass('active');
            if(currSize==1) { $('#fs_minus').addClass('disabled');}
            else {$('#fs_minus').removeClass('disabled');}
            if(currSize==maxSizes) { $('#fs_plus').addClass('disabled');}
            else {$('#fs_plus').removeClass('disabled');}
            switchStyleSheetSrc(currSize);
            return false;
        });
         $('#fs_minus').click(function(){
            if(currSize > 1) {
                currSize--;
                $('#FontSizer .size').each(function(){$(this).removeClass('active');});
                $('#fs_size'+currSize).addClass('active');
                if(currSize==1) { $('#fs_minus').addClass('disabled');}
                else {$('#fs_minus').removeClass('disabled');}
                $('#fs_plus').removeClass('disabled');
                switchStyleSheetSrc(currSize);
            }
            return false;
         });
         $('#fs_plus').click(function(){
                 if(currSize < maxSizes) {
                     currSize++;
                     $('#FontSizer .size').each(function(){$(this).removeClass('active');});
                     $('#fs_size'+currSize).addClass('active');
                     if(currSize==maxSizes) { $('#fs_plus').addClass('disabled');}
                     else {$('#fs_plus').removeClass('disabled');}
                     $('#fs_minus').removeClass('disabled');
                     switchStyleSheetSrc(currSize);
                 }
                 return false;
         });
     }
     $('a[@rel*=mail]').click(function() {
        var url = this.href;
        if (navigator.appName == "Netscape"){
            url = url.replace(/index\.php/,'index_ns.php');
        }
        window.open(url,'Mail','width=468,height=565,scrollbars=yes');
        return false;
     });
     $('#Main').glossar();

     $('.popup .print,.popup .close').css({'cursor':'pointer'});
     $('.popup .print').click(function(){
                    window.print();
                    return false;
              });
              $('.popup .close').click(function(){
                    self.close();
                    return false;
     });
     
     // /*
     if($('#GlossarEntries').size() !=0) {
        $('dd,dl,h3','#GlossarEntries').hide();
        var cLetter = 'A';
        var cKey = false;
        if(window.location.hash) {
            var tLetter = window.location.hash.substr(1,1);
            if(tLetter.match(/[a-zA-Z]/)) {cLetter = tLetter.toUpperCase();}
            if(window.location.hash.length > 2) {
                cKey = window.location.hash;
            }

        }
        $('#'+cLetter).show();
        if(cKey) {$(cKey).show();}
        $('#GlossarEntries p a').each(function() {
            var l = $(this).attr('href').split('#')[1];
            if(l==cLetter) {$(this).addClass('active');}
        });
        $('#GlossarEntries p a').click(function() {
            $('#GlossarEntries dl').hide();
            $('#GlossarEntries p a').removeClass('active');
            $(this).addClass('active');
            var l = $(this).attr('href').split('#')[1];
            $('#'+l).show();
            return false;
        });
        $('#GlossarEntries dt a').click(function(){
            $('#GlossarEntries dd').hide();
            var l = $(this).attr('href').split('#')[1];
            $('#'+l).slideDown('fast');
            return false;
        });
     }
		// */

});


jQuery.fn.extend({
    glossar: function() {
        return this.each(function() {
            new jQuery.Glossar(this);
        });
    }
});


jQuery.Glossar = function(obj) {

    var opts = {
        'linkUrl':'/scripts/pages/de/service/priorinreg_fachlexikon.php'
    }

    var _glossar = [];

    var _glossarEntries = [];

    dat = {'json':1,'getKeys':1};

    $.post('/scripts/include/modules/glossar.php',dat,function(json){
        try {
            eval('resp = ' + json);
            if(resp.glossar) {
                _glossar = resp.glossar;
                _doGlossar();

            }
        } catch(ex) {alert(ex);_doLink();}

    });

    _doGlossar = function() {
        var glossDat = _glossar.join('|')
            .replace(' ','\\s')
            .replace('(','\\(')
            .replace(')','\\)');
        rePattern = new RegExp("("+glossDat+")(?!([a-zA-Z0-9\\s+]+</a>))(?!</a>)(?![a-zA-Z0-9])","gi");
        var base =$(obj).find('*').not('script,a,embed,form,img,h3,h2,h5,h4');
        hits = 0;
        if(base && base.length) {
            for (var n=0; n<base.length; n++){
                var ctext='';
                var hasTextNode=false;
                var hasChildNode=false;
                var el=base[n];//current dom element
                if(!el || el.className.indexOf('glossar')!=-1){ continue; }
                if(el.nodeName.match(/(h2|h3|h4|h5)/)) {alert('headline!');}
                var e=$(el);
                var cont=el.firstChild;
                while(cont){
                    if(cont.nodeType==1){
                        hasChildNode=true;
                        break;
                    }
                    cont=cont.nextSibling;
                }
                if(!hasChildNode){
                    ctext=e.text();
                    if($.browser.msie) {
                        xtest = new RegExp("("+glossDat+")","gi");
                        xtest.exec(ctext);
                    }
                    rePattern.exec(ctext);
                    var m = RegExp.$1;
                    if(m!="") {
                        newtext = ctext.replace(
                            rePattern,
                            function($1){return '<a href="'+opts.linkUrl+'#'+_doAnchor($1)+'" class="glossar">'+$1+'<\/a>';}
                        );
                        e.html(newtext);
                        hits++;
                    }
                } else {
                    cont=el.firstChild;
                    while(cont){
                        if(cont.nodeType==3 && cont.nodeValue.match(/\S/)!==null){
                            if(cont.nodeValue.match(/<![ \r\n\t]*(--([^\-]|[\r\n]|-[^\-])*--[ \r\n\t]*)>/)!==null){
                                if(cont.nodeValue.match(/(\S+(?=.*<))|(>(?=.*\S+))/)!==null){
                                    hasTextNode=true;
                                    break;
                                }
                            } else {
                                hasTextNode=true;
                                break;
                            }
                        }
                        cont=cont.nextSibling;
                    }

                    if(hasTextNode){
                        ctext=e.html();
                        rePattern.exec(ctext);
                        var m = RegExp.$1;
                        if(m!="") {
                            newtext = ctext.replace(
                                rePattern,
                                function($1){return '<a href="'+opts.linkUrl+'#'+_doAnchor($1)+'" class="glossar">'+$1+'<\/a>';}
                            );
                            e.html(newtext);
                            hits++;
                        }

                    } else {
                        ctext='';
                    }
                }
                if(!ctext){ continue; }
            }
            $('h2 a.glossar, h3 a.glossar, h4 a.glossar, h5 a.glossar').each(function() {
                var atext = $(this.parentNode).text();
                $(this.parentNode).html(atext);
            });

            _doLink();
        }
    };

    _doAnchor= function(string) {
           string = string.replace(/([A-Z]+)([A-Z][a-z])/,'$1_$2')
                    .replace(/([a-z\d])([A-Z])/,'$1_$2')
                    .replace(/[^A-Z^a-z^0-9^\/]+/,'_')
                    .replace(/[áéíóúàèìòùäëïöüâêîôûñçþæðåÁÉÍÓÚÀÈÌÒÙÄËÏÖÜÂÊÎÔÛÑÇÞÆÐÅ+-\.,;\:&"\'\?\!\(\)]/g,'_');
           return string.toLowerCase();
    }

    _doLink = function() {
        if($('#glossarPop').size() ==0) {
            var pw = $('<div id="glossarPop"></div>')
                .css({'position':'absolute','z-Index':900})
                .appendTo('body');
            var c = $('<div id="CloseGPop"><span>x</span></div>')
                .css({'position':'absolute','right':0,'top':0,'z-Index':1,'cursor':'pointer'})
                .appendTo(pw);
            $(c).click(function(){$('#glossarPop').hide();});
            $('<div class="wincon"></div>').appendTo(pw);
            $('#glossarPop').hide();
        }
        $('a.glossar').click(function(e){
            var myKey = $(this).attr('href').split('#')[1];
            if(!_glossarEntries[myKey]) {
                var data = {'json':1,'getEntry':myKey};
                $.get('/scripts/include/modules/glossar.php',data,function(json){
                    try {
                        eval('resp = ' + json);
                        if(resp.data) {
                            _glossarEntries[myKey] = resp.data;
                            _showInfo(e,resp.data[0],resp.data[1]);

                        }
                    } catch(ex) {}

                });
            } else {
                _showInfo(e,_glossarEntries[myKey][0],_glossarEntries[myKey][1]);
            }
            return false;
        });
    };

    _showInfo = function(elm,title,msg) {
        $('#glossarPop .wincon').html('<h2>'+title+'</h2><div>'+msg+'</div>')
        $('#glossarPop').css({'left':elm.pageX-150,'top':elm.pageY+10}).show();

    };
};


