/* Attach Google Analytics */
if ( typeof $ == "function" ) {
    var _gaq = _gaq || [];
    $(document).ready(function () {
    	// Handling of local testing
    	if (_gaq.push == null && typeof _gaq.disabledpush == "function")
    		_gaq.push = _gaq.disabledpush;
    	// Make sure there is a global hhStatistics object and that we run only once
    	if (typeof hhStatistics != "object" || hhStatistics == null)
    		hhStatistics = new Object();
    	if (hhStatistics.runOnce)
    		return;
    	hhStatistics.runOnce = true;

    	// Basic settings
    	hhStatistics.gaAccount = "UA-6922175-1";
    	hhStatistics.siteDomains = "www.fabege.se,fabege.se";
    	hhStatistics.downloadExtensions = "avi,bmp,bz2,doc,docx,dwg,dxf,emf,eps,exe,gif,gz,jpg,mov,mp3,mpg,msi,odg,odp,ods,odt,pdf,png,pps,ppsx,ppt,pptx,rar,rss,rtf,svg,tar,tif,txt,wav,wmf,wmv,xls,xlsx,xml,zip";

    	// Specification of areas for click-area tracking
    	hhStatistics.areaSpecification = [];

    	// Verify the URL type
    	if (!document.URL.match(/^https?:\/\/[^\/?#]+\/+/i))
    		return;

    	// Determine language and normalize URL
    	var a, e, i, u, v;
    	u = null;
    	if ((e = $("#aspnetForm[action]")[0]) && (v = e.action.replace(/(^https?:\/\/[^\/]*|[?#].*$)/gi, "")).match(/^\/[a-z][a-z][\/]/i)) {
    		u = v;
    		hhStatistics.languageCode = v.substring(1, 3);
    	}
    	if (u == null) {
    		if (!hhStatistics.languageCode)
    			hhStatistics.languageCode = ((e = $("meta[http-equiv=content-language]")[0]) ? e.content : "").toLowerCase();
    		u = document.URL.replace(/(^https?:\/\/[^\/?#]+\/+|[?#].*$)/gi, "");
    		a = u.split(/\/+/);
    		for (i = 0; i < a.length; i++)
    			a[i] = a[i].toLowerCase();
    		if (a[0] != hhStatistics.languageCode)
    			a.splice(0, 0, hhStatistics.languageCode);
    		u = "/" + a.join("/");
    	}
    	hhStatistics.path = u;

    	// Add premise name and/or ID
    	if (/PremiseId=/i.test(document.URL)) {
            hhStatistics.premiseId = document.URL.replace(/^.*PremiseId=([^&#]*).*$/i, "$1");
    		hhStatistics.path = hhStatistics.path.replace(/\/?$/, "/" + hhCleanText($("h1").text().replace(/,.*$/, "")).replace(/[ \t\r\n]+/g, "-"));
        }
        if (! hhStatistics.premiseId && (a = $('a[href*="PremiseId="]')).length > 0) {
            hhStatistics.premiseId = a[0].href.replace(/^.*PremiseId=([^&#]*).*$/i, "$1");
        }

    	// Add search term
    	if ((v = /^[^#]*[?&]q=([^&#]+).*$/i.exec(document.URL)) != null && v.length >= 2)
            hhStatistics.path = hhAddParameter(hhStatistics.path, "q", decodeURIComponent(v[1]).toLowerCase());

    	// Main click handler
    	hhStatistics.clickHandler = function (e) {
    		// Normalize event info and target
    		if (!e)
    			return;
    		var t = (e.target ? e.target : (e.srcElement ? e.srcElement : null));
    		while (t && t.nodeName != "A" && t.nodeName != "INPUT")
    			t = t.parentNode;

    		// Set up lists for link-type matching
    		var b, c, d, e, f, h, i, j, r;
    		var domainList = this.siteDomains;
    		if ((b = /^https?:\/\/([^:\/]*)/i.exec(document.URL)) != null && b.length == 2)
    			domainList = "," + b[1].toLowerCase() + "," + (domainList != null ? domainList + "," : "");
    		var extensionList = ("," + this.downloadExtensions + ",").toLowerCase();

    		// Examine link type
    		d = e = r = null;
    		if (t.href != null) {
    			if (domainList != null && (b = /^(https?:\/\/)([^:\/]*)([^\/]*)[\/]*(|[\/?#].*)$/i.exec(t.href)) != null && b.length == 5 && b[2].length > 0 && domainList.indexOf("," + b[2].toLowerCase() + ",") < 0) {
    				d = "Exit: " + b[2].toLowerCase() + b[4];
    				e = "/exit/" + b[1].toLowerCase() + b[2].toLowerCase() + b[3] + b[4];
    			} else if ((b = /^mailto:([^?#]*).*$/i.exec(t.href)) != null && b.length == 2) {
    				d = "Mail: " + (b[1] == "" ? "Undefined recipient" : b[1].toLowerCase());
    				e = "/" + b[0].toLowerCase().replace(/:/, "/");
    			} else if ((b = /\/vCardHandler.ashx\?(|[^#]*&)email=([^&#]*)/i.exec(t.href)) != null && b.length == 3) {
    				d = "Vcard: " + (b[2] == "" ? "Undefined contact" : b[2].toLowerCase());
    				e = "/vcard/" + b[2].toLowerCase();
    			} else if ((b = /\/VCalendarHandler.ashx(|[?#].*)$/i.exec(t.href)) != null && b.length == 2) {
    				if ((c = $(t).parent().find("h2")).length > 0)
    					f = hhCleanText(c.text());
    				else
    					f = hhCleanText($(t).parent().contents().not(t).text());
    				d = "Vcalendar: " + f;
    				e = "/vcalendar/" + f.toLowerCase();
    			} else if ((b = /^https?:\/\/[^\/]+[\/]*(\/[^?#]*)(\.|\?output=)([^.?&#]*)([?&#].*|)$/i.exec(t.href)) != null && b.length == 5 && b[3].length > 0 && extensionList.indexOf("," + b[3].toLowerCase() + ",") >= 0) {
    				d = "File: " + b[1] + b[2] + b[3];
    				e = b[1] + b[2] + b[3];
    			}
    		}
    		if (d != null) {
    			if (r == null) {
                    var s = this;
                    var x = function () {
                        h = document.title;
                        document.title = d;
                        s.trackSubPage(e);
                        document.title = h;
                    };
                    if (t.target == "_blank" || /^(Exit|File):/i.test(d)) {
                        x();
                    } else {
                        setTimeout(function () { x(); }, 500);
                    }
    			}
    		}
    	};

    	// Click-event attacher
    	hhStatistics.setupClickEvents = function () {
    		var a, p;
    		if (!(a = this.areaSpecification) || typeof a != "object")
    			return;
    		if (this.path)
    			this.createCookie("hhclickref", this.path, null);
    		var t = "hhStatistics.createCookie('hhclickarea', '###', 10); if (e && typeof hhStatistics.clickHandler == 'function') hhStatistics.clickHandler(e);";
    		var d = t.replace(/###/g, "UntrackedLinkArea");
    		var f = $("a,input[type=submit]");
    		var e, g, h, i, j, k, o;
    		for (i = 0; i < f.length; i++)
    			hhReplaceExistingOnClick(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 = $("#" + a[j].i + " a,#" + a[j].i + " input[type=submit]")).length > 0) {
    					for (i = 0; i < f.length; i++)
    						hhReplaceExistingOnClick(f[i], o, d);
    				} else if (a[j].c == null && e.nodeName == "A") {
    					hhReplaceExistingOnClick(e, o, d);
    				} else if (a[j].c == null && e.parentNode.nodeName == "A") {
    					hhReplaceExistingOnClick(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++)
    								hhReplaceExistingOnClick(f[i], o, d);
    						}
    					}
    				}
    			}
    		}
            // Other functions
            if ((a = $("fieldset textarea").closest("fieldset").find('input[type="submit"]')).length > 0)
                if (/PremiseId=/i.test(document.URL))
                    hhReplaceExistingOnClick(a[0], "hhStatistics.trackSubPage('Submitted');", null);
                else
                    hhReplaceExistingOnClick(a[0], "hhStatistics.trackSubPage('ContactForm');", null);
    	};

    	// Statistics-cookie helpers
    	hhStatistics.createCookie = function (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=/";
    	}
    	hhStatistics.readCookie = function (name) {
    		var a = (new RegExp("(^|;) *" + name + "=([^;]*)", "")).exec(document.cookie);
    		if (a != null && a.length > 2)
    			return a[2];
    		return null;
    	}

    	// Standard page tracker
    	hhStatistics.trackPage = function (p) {
            // Add premise ID
            if (hhStatistics.premiseId)
                p = hhAddParameter(p, "PremiseId", hhStatistics.premiseId);
    		// Page view
    		_gaq.push(['_trackPageview', p]);
    	}

    	// Sub-page tracker
    	hhStatistics.trackSubPage = function (s) {
    		// Sub-page view
            hhStatistics.trackPage((hhStatistics.path + "/-/" + s).replace(/\/\/+/g, "/"));
    	}

    	// Other-action tracker
    	hhStatistics.trackOther = function (o) {
            var h = document.title;
            document.title = "Other: " + o;
    		_gaq.push(['_trackPageview', '/other/' + o]);
            document.title = h;
    	}

    	// Set up and perform page tracking
    	_gaq.push(['_setAccount', hhStatistics.gaAccount]);
    	hhStatistics.trackPage(hhStatistics.path);
    	(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';
    		(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
    	})();

    	// Attach click events (should also be run each time the DOM tree has changed)
    	hhStatistics.setupClickEvents();
    });
}

/*
 * Add or replace an onclick event to an element
 * Version 2.2
 */
var hhExistingClickHandlers = new Object();
function hhOnClick(e, g) {
    hhReplaceOnClick(e, g, null);
}
function hhReplaceExistingOnClick(e, g) {
    var f, i, r;
    var a = ["id", "href", "className", "type", "tagName", "name", "value"];
    var k = (e && e.textContent ? e.textContent : "");
    for (f=e; f && f.tagName!="BODY"; f=f.parentNode) {
        for (i=0; i<a.length; i++)
            if ( f[a[i]] )
                k += f[a[i]];
        if ( f.id )
            break;
    }
    if ( ! (r = hhExistingClickHandlers[k]) )
        r = null;
    //hhDebugLog("Handler for " + k + ": " + g);
    hhExistingClickHandlers[k] = 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" || e == null || 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;
}

/*
 * Plugin: hhCleanText
 * Version 1.2
 */
function hhCleanText(s) {
    var b = s.match(/\[[^\][]+\]/);
    var r = s.replace(/\'/g, "").replace(/&amp;/gi, "&").replace(/ *[!-%\'-,:-?\[-`{-~ \t\r\n\/][!-%\'-,:-?\[-`{-~ \t\r\n\/]* */g, " ").replace(/( *-  *|  *- *)/g, " ").replace(/(^[ \t\r\n]*|[ \t\r\n]*$)/g, "");
    return (b ? "[" + r + "]" : r);
}
function hhCleanTextAsterisk(s) {
    return s.replace(/\'/g, "").replace(/&amp;/gi, "&").replace(/ *[!-%\'-)+,:-?\[-`{-~ \t\r\n\/][!-%\'-)+,:-?\[-`{-~ \t\r\n\/]* */g, " ").replace(/( *-  *|  *- *)/g, " ").replace(/(^[ \t\r\n]*|[ \t\r\n]*$)/g, "");
}

/*
 * Add a query-string parameter
 * Version 1.1
 */
function hhAddParameter(u, n, v) {
    if (n == null || n == "" || v == null || v == "")
        return u;
    return u + (u.indexOf("?") == -1 ? "?" : "&") + encodeURIComponent(n) + "=" + encodeURIComponent(v);
}

/*
 * Write a line of debug info if supported
 */
function tryDump(m) {
    if ( typeof console == "object" && typeof console.log == "function" )
        console.log(m);
    else if ( typeof(dump) == "function" )
        dump(m + "\r\n");
}

