function gaElementCleanup(e) {
    if ( e == null || e.match(/^ *$/) )
        return "";
    return e.replace(/[\/?&]/g, " ").replace(/ +/g, " ").replace(/(^[ \t\r\n]*|[ \t\r\n]*$)/g, "");
}

function gaCleanPath(e) {
    if ( e == null || e.match(/^ *$/) )
        return "";
    return e.replace(/^https?:\/\/[^\/]+/i, "").replace(/;jsessionid=[a-z0-9_-]+/i, "");
}

function hhAddParameter(u, n, v) {
    if (n == null || n == "" || v == null || v == "")
        return u;
    return u + (u.indexOf("?") == -1 ? "?" : "&") + encodeURIComponent(n) + "=" + encodeURIComponent(v);
}

function removeAccents(s) {
    if (! s)
        return "";
    var a = "åäöÅÄÖéÉüÜ";
    var b = "aaoAAOeEuU";
    var i;
    for (i=0; i<a.length; i++)
        s = s.replace(new RegExp(a.charAt(i), "g"), b.charAt(i));
    return s;
}

function gatc(){
    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    $.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
        
        try {
            // Page name
            if ( ga_pageName != null ) {
                var hhMatch = /^(.*)\[(.*)\] *\((.*)\) *$/.exec(ga_pageName);
                if ( hhMatch != null && hhMatch.length == 4 && gaElementCleanup(hhMatch[1]) != "" && hhMatch[2] != "" && hhMatch[3] != "" )
                    ga_pageName = gaElementCleanup(hhMatch[1]) + " [" + gaElementCleanup(hhMatch[2]) + "] (" + hhMatch[3] + ")";
            }
            // Path variables
            var i;
            if ( ga_hier1 != null ) {
                var hhElements = ga_hier1.split("/");
                if ( hhElements != null && hhElements.length > 0 ) {
                    ga_hier1 = "";
                    for (i=0; i<hhElements.length; i++) {
                        ga_hier1 += "/" + (i == hhElements.length - 1 ? ga_pageName : gaElementCleanup(hhElements[i]));
                        if ( i == 1 )
                            ga_channel = ga_hier1;
                    }
                }
            }
            // Real path
            var gaPath = gaCleanPath(document.location.href);
            // Add search info
            var searchElements = $("input.searchtext");
            if ( searchElements != null && searchElements.length > 0 && gaElementCleanup(searchElements[0].value) != "" ) {
                gaPath = hhAddParameter(gaPath, "search", gaElementCleanup(searchElements[0].value));
                if ( (searchElements = $("select.searchselect")) != null && searchElements.length > 0 && searchElements[0].selectedIndex != null && searchElements[0].options[searchElements[0].selectedIndex].text != null ) {
                    gaPath =  hhAddParameter(gaPath, "category", gaElementCleanup(searchElements[0].options[searchElements[0].selectedIndex].text));
                }
            }
            
            // Determine article type
            var articleType = "";
            if ( ga_prop13 ) {
                articleType = removeAccents(gaElementCleanup(ga_prop13));
                gaPath =  hhAddParameter(gaPath, "articletype", articleType);
            }
            
            // Click-area tagging
            var setupClickAreas = function () {
                return hhClickArea({ ref : articleType, a : [
                    { a : "Meny", i : "gaMainmenu" },
                    { a : "Underwebb", i : "gaUnderwebb" },
                    { a : "Genv", i : "gaGenvag" },
                    { a : "AO", i : "gaAOlista" },
                    { a : "Faktaruta", i : "gaFactBox" },
                    { a : "Relaterat", i : "mainRelated" },
                    { a : "Toppomr", i : "topContainer" },
                    { a : "BredSpalt", i : "mainWide" },
                    { a : "Huvudsp", i : "mainContent" },
                    { a : "BannerKol", i : "extraContainer" },
                    { a : "Sidfot", i : "footerContainer" }
                ]});
            };
            var clickArea = setupClickAreas();
            setTimeout(setupClickAreas, 1000);
            
            //if (console && console.log)
            //    console.log("Area: " + clickArea.area + " Rubrik: " + clickArea.heading + "\n" + document.cookie);
            
            // Initiate tracker
            var pageTracker = _gat._getTracker("UA-5982037-2");
            
            // Custom variable for article type
            if ( articleType )
                pageTracker._setCustomVar(1, "ArtTyp", articleType, 3);
            
            // Custom variables from meta tags
            var meta = document.getElementsByTagName("META");
            for(i=0; i<meta.length; i++) {
                if (meta[i].name == "published" && meta[i].content)
                    pageTracker._setCustomVar(2, "PubliceradManad", meta[i].content.replace(/-[0-9]{2}$/, ""), 3);
            }
            
            // Click areas
            var a, r;
            if ( clickArea && clickArea.area ) {
                if ( (a = /^([^\(\[]*)\[?[^\(\]]*\]? *\(([^\)]*)\) *$/.exec(ga_pageName)) != null && a.length > 2 ) {
                    i = 64 - (6 + clickArea.area.length + a[2].length);
                    pageTracker._setCustomVar(3, "RCA", clickArea.area + "-" + hhGaCut(removeAccents(gaElementCleanup(a[1])).replace(/[\t -]+/g, "_"), i) + "-" + (articleType == "Sektion" ? "S" : "A") + a[2], 3);
                }
                if ( articleType && clickArea.ref ) {
                    r = removeAccents(gaElementCleanup(clickArea.ref));
                    a = clickArea.area;
                    if ( a == "Relaterat" && clickArea.heading ) {
                        i = 64 - (8 + r.length);
                        a = "Rel_" + hhGaCut(removeAccents(gaElementCleanup(clickArea.heading.replace(/[\t -]+/g, "_"))), i);
                    }
                    pageTracker._setCustomVar(4, "TCA", r + "-" + a, 3);
                }
            }
            
            // Set title
            var t = document.title;
            document.title = ga_pageName;
            // Track page view
            pageTracker._trackPageview(gaPath);
            // Restore title
            document.title = t;
        } catch (err) {}
        
        var filetypes = /\.(zip|exe|pdf|doc|docx|xls|xlsx|ppt|pptx|pps|ppsx|eps|tif|mp3|download)$/i;
        
        $('a').each(function(){
            var href = $(this).attr('href');
            var title = $(this).attr('title');
            if (href !== undefined) {
                if ((href.match(/^https?\:/i)) && (!href.match(document.domain)) ){
                    $(this).click(function() {
                        var extLink = href.replace(/^https?\:\/\//i, '');
                        pageTracker._trackEvent('External', 'Click', extLink);
                    });
                }
                else if (href.match(/^mailto\:/i)){
                    $(this).click(function() {
                        var mailLink = href.replace(/^mailto\:/i, '');
                        pageTracker._trackEvent('Email', 'Click', mailLink);
                    });
                }        
                else if (href.match(filetypes)){
                    $(this).click(function() {
                        var extension = (/[.]/.exec(href)) ? /[^.]+$/.exec(href) : undefined;
                        var filePath = href.replace(/^https?\:\/\/www\.svensktnaringsliv\.se\//i, '');
                        var mediaID = href.match(/([0-9]+)a\.[a-z0-9]+$/i);
                        if (title ==''){
                            var trackTitle = filePath;
                        }
                        else{
                            var trackTitle = title + ' [' + mediaID[1] +']';
                        }
                        pageTracker._trackEvent('Downloads', ga_prop13, trackTitle);
                    });
                }
            }
        });
    });
};


function relHeadingFinder(e) {
    if (!e)
        var e = window.event;
    var f = null;
    if (e.target)
        f = e.target;
    else if (e.srcElement)
        f = e.srcElement;
    var a, g, h, i;
    while (f) {
        g = f;
        f = f.parentNode;
        h = null;
        for (i=0; f && i<f.childNodes.length; i++) {
            if (f.childNodes[i].tagName && f.childNodes[i].tagName.toUpperCase() == "H2" && f.childNodes[i].innerHTML)
                h = f.childNodes[i];
            else if (f.childNodes[i].getElementsByTagName && (a = f.childNodes[i].getElementsByTagName("H2")) != null && a.length > 0 && a[0].innerHTML)
                h = a[0];
            //if (console && console.log && f.nodeName)
            //    console.log(f.nodeName + "-" + i + ": " + f.childNodes[i].nodeName + (f.childNodes[i] == g ? " (clicked)" : "") + (h ? " *" : ""));
            if (h && f.childNodes[i] == g)
                return h.innerHTML.replace(/<[^>]*>/g, "");
        }
    }
    return "";
}

/*
 * Log click area
 */
function hhClickArea(c) {
    var a, p, r;
    r = new Object();
    if ( ! c || typeof c != "object" || ! (a = c.a) )
        return r;
    r.area = ((p = readCookie("hhclickarea")) ? p : "");
    r.ref = ((p = readCookie("hhclickref")) ? p : "");
    r.heading = ((p = readCookie("hhclickheading")) ? p : "");
    if ( c.ref )
        createCookie("hhclickref", c.ref, null);
    var t = "createCookie('hhclickarea', '###', 10); if (e && typeof hhClickHandler == 'function') hhClickHandler(e); if (e && typeof relHeadingFinder == 'function') createCookie('hhclickheading', relHeadingFinder(e), 10);";
    var d = t.replace(/###/g, "UntrackedLinkArea");
    var f = document.getElementsByTagName("A");
    var e, g, h, i, j, k, o;
    if ( f != null )
        for (i=0; i<f.length; i++)
            hhOnClick(f[i], d);
    for (j=0; j<a.length; j++) {
        if ( typeof(a[j]) == "object" && a[j].i != null && (e = document.getElementById(a[j].i)) != null ) {
            o = t.replace(/###/g, a[j].a.replace(/\\/g, "\\\\").replace(/\'/g, "\\'"));
            if ( a[j].c == null && (f = e.getElementsByTagName("A")) != null && f.length > 0 ) {
                for (i=0; i<f.length; i++)
                    hhReplaceOnClick(f[i], o, d);
            } else if ( a[j].c == null && e.nodeName == "A" ) {
                hhReplaceOnClick(e, o, d);
            } else if ( a[j].c == null && e.parentNode.nodeName == "A" ) {
                hhReplaceOnClick(e.parentNode, o, d);
            } else if ( a[j].c != null && (g = e.getElementsByTagName("DIV")) != null && g.length > 0 ) {
                for (k=0; k<g.length; k++) {
                    if ( g[k].className == a[j].c && (f = g[k].getElementsByTagName("A")) != null && f.length > 0 ) {
                        for (i=0; i<f.length; i++)
                            hhReplaceOnClick(f[i], o, d);
                    }
                }
            }
        }
    }
    return r;
}

/*
 * Add or replace an onclick event to an element
 * Version 2.0
 */
var hhExistingClickHandlers = new Object();
function hhOnClick(e, g) {
    hhReplaceOnClick(e, g, null);
}
function hhReplaceExistingOnClick(e, g) {
    var r;
    if ( ! (r = hhExistingClickHandlers[e]) )
        r = null;
    hhExistingClickHandlers[e] = g;
    hhReplaceOnClick(e, g, r);
}
function hhReplaceOnClick(e, g, r) {
    hhReplaceEvent(e, g, r, "click");
}
function hhReplaceEvent(e, g, r, n) {
    if ( typeof(e) != "object" || n == null )
        return;
    var f = (typeof(g) == "function" ? g : hhGetEventHandler(g));
    var q = (typeof(r) == "function" ? r : hhGetEventHandler(r));
    if ( typeof(e.addEventListener) == "function" || typeof(e.addEventListener) == "object" ) {
        if ( q != null ) {
            e.removeEventListener(n, q, false);
        }
        if ( f != null ) {
            e.removeEventListener(n, f, false);
            e.addEventListener(n, f, false);
        }
    } else if ( typeof(e.attachEvent) == "function" || typeof(e.attachEvent) == "object" ) {
        if ( q != null ) {
            e.detachEvent('on' + n, q);
        }
        if ( f != null ) {
            e.detachEvent('on' + n, f);
            e.attachEvent('on' + n, f);
        }
    }
}

/*
 * Create or get an event handler from a code string
 * Version 1.2
 */
var hhLiteralEventHandlers = new Object();
function hhGetEventHandler(t) {
    var f;
    if ( t == null )
        return null;
    if ( (f = hhLiteralEventHandlers[t]) != null )
        return f;
    f = hhLiteralEventHandlers[t] = new Function("e", t);
    return f;
}

/*
 * Plugin: hhByteCut
 * Version 1.0
 */
function hhByteCut(s, n) {
    if ( s == null )
        s = "";
    var t = s;
    var o = n;
    while ( hhLength(t) > n && o >= 0 ) {
        t = hhCut(s, o--);
    }
    return t;
}

function hhGaCut(s, n) {
    if ( s == null )
        s = "";
    var t = s;
    var o = n;
    while ( hhGaLength(t) > n && o >= 0 ) {
        t = hhCut(s, o--);
    }
    return t;
}

/*
 * Plugin: hhCut
 * Version 1.0
 */
function hhCut(s, n) {
    if ( s == null )
        s = "";
    if ( n < 1 )
        return "";
    if ( n < 4 )
        return "~";
    if ( s.length > n ) {
        var i = Math.ceil((n-3)*0.6);
        if ( s[i-1] == " " )
            i--;
        s = s.substring(0, i) + "..." + s.substring(s.length-(n-(i+3)));
    }
    return s;
}

/*
 * Plugin: hhLength
 * Version 1.0
 */
function hhLength(s) {
    if ( s == null )
        return 0;
    if ( typeof(encodeURI) == "function" ) {
        return encodeURI(s).replace(/%../g, "%").length;
    }
    return s.length + s.replace(/[ -~\t\r\n]/g, "").length;
}

function hhGaLength(s) {
    if ( s == null )
        return 0;
    if ( typeof(encodeURIComponent) == "function" ) {
        return encodeURIComponent(s).length;
    }
    return s.length + s.replace(/[ -~\t\r\n]/g, "").length;
}

/*
 * Other functions
 */
function createCookie(name, value, seconds) {
    if (seconds) {
        var date = new Date();
        date.setTime(date.getTime() + (seconds*1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        var expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var a = (new RegExp("(^|;) *" + name + "=([^;]*)", "")).exec(document.cookie);
    if (a != null && a.length > 2)
        return a[2];
    return null;
}
