$(document).ready(function () {
    if ($('.std, .csBlock').length > 0) {
        $.getJSON('/glossary/json', function (data) {
            classes = ' glossary-popup iframe';
            if (getQuerystring('popup') == 'true') {
                classes = '';
            }
            $('.std, .csBlock').each(function () {
                html = $(this).html();
                
                $.each(data, function(i,item){
                    html = html.replace(new RegExp('([^a-z])(' + item.term + ')(?![^<]*>|[^<]*<\/a>)([^a-z])', "gi"), '$1<a href="/glossary/term/' + item.slug + '?popup=true" class="glossaryLink' + classes + '" title="Word Explained">' + item.term + '</a>$3');
                });

                $(this).html(html);

                defaultPopup = {
                    'frameWidth': 902,
                    'zoomSpeedIn': 600,
                    'hideOnContentClick': false,
                    'centerOnScroll': true,
                    'overlayOpacity': 0.9
                };
                
                // Add external link classes to external links - 
                $('a').filter(function(){
                    //Compare the anchor tag's host name with location's host name
                    return this.hostname && this.hostname !== location.hostname;
                }).attr('target', '_blank');

                if ($('a.external-popup').length > 0 && $('#menu').length > 0) {
                    $('a.external-popup').fancybox(defaultPopup);
                }

                if ($('a.glossary-popup').length > 0) {
                    $('a.glossary-popup').fancybox(defaultPopup);
                }
            });
        });
    }
});

function getQuerystring(key, default_)
{
    if (default_==null) default_="";
    key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if(qs == null)
        return default_;
    else
        return qs[1];
}
