
/* Merged Plone Javascript file
 * This file is dynamically assembled from separate parts.
 * Some of these parts have 3rd party licenses or copyright information attached
 * Such information is valid for that section,
 * not for the entire composite file
 * originating files are separated by - filename.js -
 */

/* - highlightsearchterms.js - */
function highlightTermInNode(node, word) {
    var contents = node.nodeValue;
    if (jq(node).parent().hasClass("highlightedSearchTerm")) return;
    
    // Internet Explorer cannot create simple <span> tags without content
    // otherwise it'd be jq('<span>').addClass(...).text(content)
    var highlight = function(content) {
        return jq('<span class="highlightedSearchTerm">' + 
                  content + '</span>');
    }
    
    while (contents && (index = contents.toLowerCase().indexOf(word)) > -1) {
        // replace the node with [before]<span>word</span>[after]
        jq(node)
            .before(document.createTextNode(contents.substr(0, index)))
            .before(highlight(contents.substr(index, word.length)))
            .before(document.createTextNode(contents.substr(index+word.length)));
        var next = node.previousSibling; // text after the span
        jq(node).remove(); 
        // wash, rinse and repeat
        node = next; contents = node.nodeValue;
    }
}

function highlightSearchTerms(terms, startnode) {
    if (!terms || !startnode) return;

    jq.each(terms, function(i, term) {
        term = term.toLowerCase();
        // don't highlight reserved catalog search terms
        if (!term || /(not|and|or)/.test(term)) return;
        jq(startnode).find('*').andSelf().contents().each(function() {
            if (this.nodeType == 3) highlightTermInNode(this, term);
        });
    });
}

function getSearchTermsFromURI(uri) {
    var query;
    if (typeof decodeURI != 'undefined') {
        query = decodeURI(uri);
    } else if (typeof unescape != 'undefined') {
        // _robert_ ie 5 does not have decodeURI 
        query = unescape(uri);
    } else {
        // we just try to be lucky, for single words this will still work
    }
    var result = new Array();
    if (window.decodeReferrer) {
        var referrerSearch = decodeReferrer();
        if (null != referrerSearch && referrerSearch.length > 0) {
            result = referrerSearch;
        }
    }
    var qfinder = new RegExp("(searchterm|SearchableText)=([^&]*)", "gi");
    var qq = qfinder.exec(query);
    if (qq && qq[2]) {
        var terms = qq[2].replace(/\+/g,' ').split(' ');
        result.push.apply(result, jq.grep(terms, function(a) { return a != ""}));
        return result;
    }
    return result.length == 0 ? false : result;
}

jq(function() {
    // search-term-highlighter function --  Geir Baekholt
    var terms = getSearchTermsFromURI(window.location.search);
    // make sure we start the right place so we don't higlight menuitems or breadcrumb
    highlightSearchTerms(terms, getContentArea());
});



/* - se-highlight.js - */
/* List of search engine matchers and the referrer search
 * code where carefully borrowed from the
 * "Search Engine Keyword Highlight" by Scott Yang,
 * see http://fucoder.com/code/se-hilite/ for further
 * details.
 */
var searchEngines = [
    ['^http://([^.]+\\.)?google.*', 'q='],              // Google
    ['^http://search\\.yahoo.*', 'p='],                // Yahoo
    ['^http://search\\.msn.*', 'q='],                  // MSN
    ['^http://search\\.aol.*', 'userQuery='],          // AOL
    ['^http://(www\\.)?altavista.*', 'q='],            // AltaVista
    ['^http://(www\\.)?feedster.*', 'q='],             // Feedster
    ['^http://search\\.lycos.*', 'query='],            // Lycos
    ['^http://(www\\.)?alltheweb.*', 'q='],             // AllTheWeb
    ['^http://(www\\.)?ask\\.com.*', 'q=']                   // Ask.com
]

function decodeReferrer(ref) {
    // checks if we are beeing searched by a search engine
    if (null == ref && document.referrer) {
        ref = document.referrer;
    }
    if (!ref) return null;

    var match = new RegExp('');
    var seQuery = '';
    for (var i = 0; i < searchEngines.length; i ++) {
        if (!match.compile) {
            // Safari doesn't support the non-standard compile method
            match = new RegExp(searchEngines[i][0], 'i');
        } else {
            match.compile(searchEngines[i][0], 'i');
        }
        if (ref.match(match)) {
            
            if (!match.compile) {
                match = new RegExp('^.*[?&]'+searchEngines[i][1]+'([^&]+)&?.*$', 'i');
            } else {
                match.compile('^.*[?&]'+searchEngines[i][1]+'([^&]+)&?.*$');
            }
            seQuery = ref.replace(match, '$1');
            if (seQuery) {
                seQuery = decodeURIComponent(seQuery);
                seQuery = seQuery.replace(/\'|"/, '');
                return seQuery.split(/[\s,\+\.]+/);
            }

        }
    }
    return null;
}


/* - first_input_focus.js - */
// Focus on error or first element in a form with class="enableAutoFocus"
jq(function() {
    if (jq("form div.error :input:first").focus().length) return;
    jq("form.enableAutoFocus :input:not(.formTabs):visible:first").focus();
});


/* - accessibility.js - */
// http://www.cctc.ca/portal_javascripts/accessibility.js?original=1
function setBaseFontSize(f,r){var b=jq('body');if(r){b.removeClass('smallText').removeClass('largeText');createCookie("fontsize",f,365)}b.addClass(f)};jq(function(){var f=readCookie("fontsize");if(f)setBaseFontSize(f,0)});

/* - styleswitcher.js - */
// StyleSwitcher functions written by Paul Sowden
function setActiveStyleSheet(title, reset) {
    jq('link[rel*=style][title]').attr('disabled', true)
        .find('[title=' + title + ']').attr('disabled', false);
    if (reset) createCookie("wstyle", title, 365);
};

jq(function() {
    var style = readCookie("wstyle");
    if (style != null) setActiveStyleSheet(style, 0);
});


/* - toc.js - */
// http://www.cctc.ca/portal_javascripts/toc.js?original=1
jq(function(){var dest=jq('dl.toc dd.portletItem');var content=getContentArea();if(!content||!dest.length) return;dest.empty();var location=window.location.href;if(window.location.hash)
location=location.substring(0,location.lastIndexOf(window.location.hash));var stack=[];jq(content).find('*').filter(function(){return/^h[1234]$/.test(this.tagName.toLowerCase())}).not('.documentFirstHeading').each(function(i){var level=this.nodeName.charAt(1)-1;while(stack.length<level){var ol=jq('<ol>');if(stack.length){var li=jq(stack[stack.length-1]).children('li:last');if(!li.length)
li=jq('<li>').appendTo(jq(stack[stack.length-1]));li.append(ol)}
stack.push(ol)}
while(stack.length>level) stack.pop();jq(this).before(jq('<a name="section-'+i+'" />'));jq('<li>').append(jq('<a />').text(jq(this).text()).attr('href',location+'#section-'+i)).appendTo(jq(stack[stack.length-1]))});if(stack.length){jq('dl.toc').show();oltoc=jq(stack[0]);numdigits=oltoc.children().length.toString().length;oltoc.addClass("TOC"+numdigits+"Digit");dest.append(oltoc)}});

