if (top.location != self.location) {
//top.location.href = self.location;
}

function epost()
{
if (arguments.length == 4) {
document.write('<a title="'+arguments[3]+'" href="mailto:'+arguments[0]+'@'+arguments[1]+'">'+arguments[2]+'</a>');
} else if (arguments.length == 3) {
document.write('<a href="mailto:'+arguments[0]+'@'+arguments[1]+'">'+arguments[2]+'</a>');
} else if (arguments.length == 2) {
document.write('<a href="mailto:'+arguments[0]+'@'+arguments[1]+'">'+arguments[0]+'@'+arguments[1]+'</a>');
} else if (arguments.length == 1) {
document.write('<a href="mailto:'+arguments[0]+'">'+arguments[0]+'</a>');
}
}


function pressed(xx) {location.href=xx}function pres(xx) {location.href=xx}function replaceall(ss,xx,yy) {var x=xx; var y=yy; var s=ss;if (x.length>0){found=s.indexOf(x);while (found>=0) {s=s.substring(0,found) + y + s.substring(found+x.length,s.length);found=s.indexOf(x,found+y.length);}}return s;}
function multipressed(xx,urlPattern,StartValue) {var url = urlPattern; var allow = StartValue; var test = false; var OK = true;if(arguments.length>3) {test=arguments[3].toLowerCase()=='test';}for(var i = 0; i < xx.elements.length; i++) {if(xx.elements[i].type == 'select-one') {if(OK) {OK=(xx.elements[i].selectedIndex>=allow);}url=replaceall(url,'$'+(i+1),xx.elements[i].options[xx.elements[i].selectedIndex].value);url=replaceall(url,'€'+(i+1),xx.elements[i].options[xx.elements[i].selectedIndex].value);}}url=url.toLowerCase();if(test) {str='Test giver denne URL: \n\n' + url;if(!OK) {str=str+'\n\nmen vil give besked om at vælge en værdi i alle felter';}alert(str);} else {if(OK) {location.href=url;}else { alert('Vælg en værdi i alle felter!');}}}


// Create (async) Google Analytics variable '_gaq' in the global namespace
var _gaq = _gaq || [],
	addthis_config = addthis_config || {};

var pingAnalytics = (function () {
    // Start loading gs.js:
    (function() {
          var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
          ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
          var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
    })();

    /*
     * Simple cookie utility, providing get, set and unset of cookies.
     * Taken from "JavaScript for Web Developers", pp. 620-621, by Nicholas C. Zakas.
     */
    var CookieUtil = {
        get: function (name) {
            var cookieName = encodeURIComponent(name) + "=",
                cookieStart  = document.cookie.indexOf(cookieName),
                cookieValue = null;

            if (cookieStart > -1) {
                var cookieEnd = document.cookie.indexOf(";", cookieStart);
                if (cookieEnd == -1) {
                    cookieEnd = document.cookie.length;
                }
                cookieValue = decodeURIComponent(document.cookie.substring(cookieStart + cookieName.length, cookieEnd));
            }
            return cookieValue;
        },

        set: function (name, value, expires, path, domain, secure) {
            var cookieText = encodeURIComponent(name) + "=" + encodeURIComponent(value);

            if (expires instanceof Date) {
                cookieText += "; expires=" + expires.toGMTString();
            }

            if (path) {
                cookieText += "; path=" + path;
            }

            if (domain) {
                cookieText += "; domain=" + domain;
            }

            if (secure) {
                cookieText += "; secure";
            }

            document.cookie = cookieText;
        },

        unset: function (name, path, domain, secure) {
            this.set(name, "", new Date(0), path, domain, secure);
        }
    };

    /*
     * Simple event utility, providing add- and remove event.
     * Taken from "JavaScript for Web Developers", pp. 374, by Nicholas C. Zakas.
     */
    var EventUtil = {
        addHandler: function (element, type, handler) {
            if (element.addEventListener) {
                element.addEventListener(type, handler, false);
            } else if (element.attachEvent) {
                element.attachEvent('on' + type, handler);
            } else {
                element['on' + type] = handler;
            }
        },
        removeHandler: function (element, type, handler) {
            if (element.removeEventListener) {
                element.removeEventListener(type, handler, false);
            } else if (element.detachEvent) {
                element.detachEvent('on' + type, handler);
            } else {
                element['on' + type] = null;
            }
        }
    }

    /*
     * Take as input a string, which might contain HTML entities.
     *
     * Returns a string where entities has been converted to their character equivalents (as defined by innerHTML)
     *
     * Credit: http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_21998152.html#a17571684
     */
    // TODO: Use this function (as part of email-tracking)
    function removeHTMLEntities (str) {
        var div = document.createElement('div');
        div.innerHTML = str;
        return div.innerHTML;
    }

    /*
     * Determines what the best possible domain we can set is, and stores it in a local variable.
     */
    var domainName = '.au.dk';
    /* We use feature detection (not browser-sniffing) to determine if we can set the cookie.
     * That is to say: We try to set a .au.dk domain cookie and take action accordingly.
     * Thus, if Internet Explorer (which is the browser that presently neccesitates this
     * comes around and starts behaving reasonably, then it will 'just work'; it also
     * allows for detecting IEs which allows us to set .au.dk domain cookies - thus we
     * will work as best as possible.
     * Anyways: Until au.dk is on this list, res://urlmon.dll/ietldlist.xml, we need this.
     * (You can see the list by pasting the URL into IEs address field).
     */
    CookieUtil.set('au_dk_domaincookie', 'yes', '', '', '.au.dk');
    var AuDkDomainCookie = CookieUtil.get('au_dk_domaincookie');
    if (AuDkDomainCookie !== 'yes') {
        /*
         * Here we take the "most general, but still allowed" domain will be allowed to.
         * For instance: It is better to use .chem.au.dk if on cmc.chem.au.dk, since that
         * will allow GA to track moving back and forth between chem.au.dk and cmc.au.dk
         * (so not 'perfect', but better that not doing this).
         */
        var regexp = /[^.]+\.au\.dk$/;
        var result = regexp.exec(document.domain);
        if (result !== null) {
            domainName = '.' + regexp.exec(document.domain)[0];
        } else {
            domainName = '.' + document.domain;
        }
    }
    // Tidy up, by removing the test cookie
    CookieUtil.unset('au_dk_domaincookie', '', '.au.dk');

    var be_typo_user = CookieUtil.get('be_typo_user');

    // Make Aarhus University default account accessible in global namespace
    var au_default_account = 'UA-2142081-1',
        gaAccounts = ['au_ga_account.'];


    // Add (i.e. 'push') the default account:
    _gaq.push([gaAccounts[0] + '_setAccount', au_default_account],
            [gaAccounts[0] + '_setDomainName', domainName],
            [gaAccounts[0] + '_setAllowHash', false],
            [gaAccounts[0] + '_setAllowLinker', true],
            [gaAccounts[0] + '_trackPageview']);

    var href = document.location.href;
    if (be_typo_user !== null) {
        _gaq.push([gaAccounts[0] + '_setCustomVar', 1, 'user-type', 'typo3_backend_user', 1]);
    }

    /*
     * AddThis configuration object. As default, link to AU Google Analytics account.
     * If an account is given to the function pingAnalytics(), the first argument to that
     * function will be set up as AddThis tracker account.
     * TODO: Consider writing a multi-account wrapper for AddThis so we can track to several GA accounts
     */
    _gaq.push(function() {
       addthis_config = {
          data_ga_tracker: _gat._getTrackerByName(gaAccounts[0]),
          data_track_clickback: true
       };
    });

    function bind (fn, context) {
        return function () {
            return fn.apply(context, arguments);
        }
    }

    function sleep(ms) {
        var dt = new Date();
        dt.setTime(dt.getTime() + ms);
        while (new Date().getTime() < dt.getTime());
    }

    /* AU Google Analytics multi pusher: Wraps the GA trackEvent() function and pushes events to all accounts */
    var trackEventMulti = function (category, action, opt_label, opt_value) {
        return function () {
            var length = gaAccounts.length;
            for (var i = 0; i < length; i += 1) {
                _gaq.push([gaAccounts[i] + '_trackEvent', category, action, opt_label, opt_value]);
            }
            // Allow _gaq.push to execute, but do no make people feel it.
            sleep(100);
        }
    };

    var _filetypes = /\.(zip|exe|pdf|doc|xls|ppt|pps|mp(3|4)|eps|docx|dotx|rar|csv|gz|dmg|xml|odt|odp|ods|odg|sxw|tex|rtf|tgz|tar|dvi)$/i;

    function extend_tracking() {
        var a = document.getElementsByTagName("a");
        for (var i = 0; i < a.length; i++) {
            var href = a[i].getAttribute("href");
            var page = location.pathname;

            if (href) {
                /* We test for mailto: written literally or as HTML entities; the latter is sometimes used as spam-bot protection */
                if (!href.match(/\.au\.dk/) && !href.match(/https?\:\/\/au\.dk/) && href.match(/^https?\:\/\//i)) {
                        var ext_link = href.replace(/^https?\:\/\//i, '');
                        EventUtil.addHandler(a[i], 'click', trackEventMulti('External links', 'Click', ext_link));
                } else if (href.match(/^(mailto\:|&#109;&#97;&#105;&#108;&#116;&#111;&#58;)/i)) {
                    var plainText = removeHTMLEntities(href);
                    var mail_link = plainText.replace(/^mailto\:/i, '');
                    mail_link = /^([^?]*)/.exec(mail_link);
                    EventUtil.addHandler(a[i], 'click', trackEventMulti('Email', 'Click', mail_link[1]));
                } else if (href.match(_filetypes)) {
                    var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                    EventUtil.addHandler(a[i], 'click', trackEventMulti('Download', extension[0], href));
                } else if (href.match(/linkTo_UnCryptMailto/i)) {
                    var mail_link = href.replace(/^javascript:linkTo_UnCryptMailto\(\'/i, '');
                    mail_link = mail_link.replace(/\'\);?$/i, '');
                    if (typeof(decryptString) == 'function') {
                        var mail_link = decryptString(mail_link, -1);
                    }
                    mail_link = mail_link.replace(/^mailto\:/i, '');
                    mail_link = /^([^?]*)/.exec(mail_link);
                    EventUtil.addHandler(a[i], 'click', trackEventMulti('Email', 'Click', mail_link[1]));
                }
            }
        }
    }

    function add_load_event(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function() {
                  if (oldonload) {
                    oldonload();
                  }
                  func();
            }
          }
    }

    function check_for_refresh() {
        if (document.referrer == document.location.href) {
            (trackEventMulti('Refresh', 'Action', document.location.href))();
        }
    }

    function doSearch(event) {
        var form = document.getElementById('au_searchform');
        if (form.au_searchquery.value == false) {
            if(event.preventDefault) {
                event.preventDefault();
            } else {
                event.returnValue = false; // IE, sigh...
            }
        } else if (form.au_searchquery_chkbx.checked) {
            form.Find.value = form.au_searchquery.value;
            (trackEventMulti('person-search', 'Click', form.Find.value))();
            form.method = "post";
            form.action = "http://www.person.au.dk?inputSearchAttribute=any&inputSearch="+form.Find.value;
//            form.action = "http://person.au.dk/navnfind.cfm";
        } else {
            form.Find.value=document.domain;
        }
    }

    /*
     * Accepts an unspecified number of arguments. Each argument must be string denoting
     * a fully qualified Google Analytics tracker ID, e.g. 'UA-705488-34'.
     * The first argument given will be the default tracker (i.e. no name). This allows
     * local implementations that might expect the default tracker to be their own to work.
     */
    return function () {
        var i = 0; // Start at 1 since zero'th place is used by default tracker.

        /*
         * Build (i.e. 'push') all the arguments onto the _gaq. (depending on execution time _gaq is an array or an object).
         *
         * Due to legacy constraints, the following special rules apply:
         *     - An empty string as argument indicates we should use default account. We can just discard empty
         *     - The default account might be set as argument, so we need to check for that.
         * Bottom line is that we can just discard them.
         *
         * Note: We do not check, nor attempt to handle, if the same account is added twice or more.
         */
        for (i = 0; i < arguments.length; i++) {
            switch (arguments[i]) {
            case '':
            case au_default_account:
            case null:
                // Do nothing: These values just signify that the default account should be used, which we always do.
                break;
            default:
                // According to http://code.google.com/intl/da/apis/analytics/docs/gaJS/gaJSApi_gaq.html#_gaq.push
                // Note: For brevity we use just 'au_t' for 'AU tracker'
                var tracker = '';
                if (i != 0) {
                    tracker = 'au_t' + i + '.';
                }
                gaAccounts.push(tracker);
                _gaq.push([tracker + '_setAccount', arguments[i]]);
                // TODO: Do we know what domain name to set?
                _gaq.push([tracker + '_setDomainName', domainName]);
                _gaq.push([tracker + '_setAllowHash', false]);
                _gaq.push([tracker + '_setAllowLinker', true]);
                _gaq.push([tracker + '_trackPageview']);
                if (be_typo_user !== null) {
                    _gaq.push([tracker + '_setCustomVar', 1, 'user-type', 'typo3_backend_user', 1]);
                }

                // The order is important here: This must be pushed after setAccount and trackPageview.
                if (i == 0) {
                    // Note: If the first argument to pingAnalytics is equal to the default GA-account, then this has no effect.
                    // Replace tracker in AddThis config to log to the 'local' GA account
                    _gaq.push(function() {
                           addthis_config.data_ga_tracker = _gat._getTrackerByName();
                    });
                }
                break;
            }
        }

        add_load_event(function() {
            try {
                if (typeof(_gaq) != "undefined") {
                    extend_tracking();
                    check_for_refresh();
                    var searchForm = document.getElementById('au_searchform');
                    EventUtil.addHandler(searchForm, 'submit', doSearch);
                } else {
                    //console.info("_gaq was not defined");
                }
            } catch (err) {
                //console.info("Error [" + err.name + "]: " + err.message);
            }
        });
    };
})();

