// extract a id e.g. zlo_394034 from a classname
function getClassIdWithPrefix(className, prefix) {
    var classNames = String(className).split(" ");
    for (i = 0; i < classNames.length; i++) {
        var className = classNames[i];

        if (className.indexOf(prefix, 0) == 0) {
            return className.substring(4, className.length);
        }
    }
    return null;
}

// returns DMS ID of block (parent .contentblock)
function getBlockId(object) {
    var contentBlock = $(object).closest('.contentblock, .metabarcomponent');

    return contentBlock ? getClassIdWithPrefix(contentBlock.attr('class'), 'dms_') : 0;
}

// send actions
function sanoma_action(label, obj, ATItype) {
    var ATIlabel = String(label).replace(/\s/g, '_');
    if ((typeof obj == "undefined") || (obj == null)) {
        obj = this;
    }

    if (typeof ATItype == "undefined") {
        ATItype = 'A';
    }

    as.action(label);
    xt_click(obj, 'C', xtn2, ATIlabel, ATItype);
}

// open a link in a new window/tab using 'this' object
function o(a, override) {
    if (typeof override != 'undefined') {
        var url = override;
    } else {
        var url = a.href;
    }

    var className = a.className;
    var dmsId = getClassIdWithPrefix(className, 'dms_');
    var zlostatId = getClassIdWithPrefix(className, 'zlo_');

    return n(dmsId, zlostatId, getBlockId(a), url, a.target, a);
}

// open a form in a new window/tab using 'this' object
function f(form, override) {
    if (typeof override != 'undefined') {
        var url = override;
    } else {
        var url = form.getAttribute('action');
    }

    var className = form.className;
    var dmsId = getClassIdWithPrefix(className, 'dms_');
    var zlostatId = getClassIdWithPrefix(className, 'zlo_');

    return n(dmsId, zlostatId, getBlockId(form), url, form.target, form);
}

// track a click, object param will only used if set
function n(dmsId, zlostatId, blockId, url, target, object) {

    // See if we're fired by the ClickHandler - tab clicks shouldn't open new window
    var isTabClick = false;
    if (typeof window.cHandler != 'undefined') {
        isTabClick =  window.cHandler.isTabClick();
    }
    
    // Tab clicks should always open in new tab.
    if (isTabClick && target == '_self') {
        target = '_blank';
    }

    // If this is a 'special' click, and we're here for the click event, abort!
    // Reason being that we've already handled the functionality through the mousedown
    // event by manually calling this method.
    var e = window.event || [];
    if (e.type == 'click' && isTabClick) {
        return false;
    }

    if (typeof target == "string") {
        target = target.replace(/\s+/, '');
    }

    if (
        (typeof target == 'undefined') ||
        (target == null) ||
        (target == false) ||
        (target.length == 0) ||
        (target.match(/^\d+$/))
    ) {
        target = getTimestamp();
    }

    if (object != null) {
        object.target = target;
    }

    // order of tracking calls: zlostat, ATI, arnostat
    if (zlostatId != null) {
        zlostat(zlostatId);
    }

    if (dmsId !== null && object != null) {
        // at internet
        aiClick(dmsId, blockId, object, url);
    }

    // arnostat
    if (dmsId != null && zlostatId != null) {
        as.click(url, {
            lms: dmsId,
            zlo: zlostatId
        });
    } else {
        as.click(url);
    }

    if ((target != "_self") && (target != "_blank") && !isTabClick) {

        //check window cookie
        var wi = getCookie("ws");

        if (wi == null || wi == 0) {
            target = window.open("", target, "toolbar=yes,location=yes,resizable=yes,status=yes,scrollbars=yes,menubar=yes,width=" + ((screen.width / 100) * 80) + ",height=" + (((screen.height / 100) * 85) - 200) + ",left=" + ((screen.width / 100) * 9) + ",top=" + ((screen.height / 100) * 14));
            target.focus();
        } else if (wi == 1) {
            if (object != null) {
                // same window
                object.target = '_top';
            }
            target = window.top;
        } else if (wi == 2) {
            // fullscreen
            target = window.open("", target, "toolbar=yes,location=yes,resizable=yes,status=yes,scrollbars=yes,menubar=yes,width=" + ((screen.width / 100) * 99) + ",height=" + (((screen.height / 100) * 107) - 200) + ",left=0,top=0");
            target.focus();
        } else if (wi == 3) {
            target = window.open("", target);
            target.focus();
        }
    }

    return target;
}

function getCookie(name) {
    var d = document;
    var arg = name + "=";
    var i = 0;

    while (i < d.cookie.length)
     {
        j = i + arg.length;

        if (d.cookie.substring(i, j) == arg)
        {
            endstr = d.cookie.indexOf(";", j);

            if (endstr == -1)
            endstr = d.cookie.length;

            return unescape(d.cookie.substring(j, endstr));
        }

        i = d.cookie.indexOf(" ", i) + 1;

        if (i == 0)
        break;
    }

    return null;
}

function zlostat(id) {
    if (id != '') {
        var url = "http://dispatch.ilsemedia.nl/?a=" + id + "&b=1&uni=" + getTimestamp();
        if (document.images) {
            var ici = new Image(1, 1);
            ici.src = url;
            ici.onload = function () {
                zlostat_void();
            }
        } else {
            document.write('<img width="1" height="1" src="' + url + '" alt="" />');
        }
    }
}

function zlostat_void() {
    return true;
}

function aiClick(dmsId, blockId, object, url) {
    url = encodeURIComponent(String(url));
    xt_adc(object, 'PUB-[' + dmsId + ']-' + blockId + '-[' + url + ']&pvs='+xt_page_version);
}

function aiImpression(impressions /* list in format [[dmsid,blockid],[dmsid,blockid],...]*/) {
    var imprList = [];
    for (i in impressions) {
        imprList.push('PUB-[' + impressions[i][0]+ ']-' + impressions[i][1]);
    }

    if (imprList.length > 0) {
        xt_ParseUrl3(Xt_id+xt8b+'&p='+xtp+'&s2='+xw.xtn2+'&pvs='+xt_page_version+'&type=AT','&ati='+imprList.join(','),1,1,'&ati=',',');
    }
}

function lc_getUriParam(name) {
    var uri = document.location.href;
    var uri2 = uri.split("?");
    if (uri2[1]) {
        var uri3 = uri2[1].split("&");
        for (i = 0; i < uri3.length; i++) {
            uri4 = uri3[i].split("=");
            if (uri4[0] == name) {
                return uri4[1];
            }
        }
    } else {
        return "";
    }
}

function stir(sitegroup, segment, webdir, adpackage) {
    if (document.cookie.indexOf("ns_Cfilter") != -1) {
        var url = "http://nl.sitestat.com/ilsemedia/" + sitegroup + "/s?teller&ns_channel=" + segment + "&ns_webdir=" + webdir;
        if ((adpackage != null) && (adpackage != "")) {
            url = url + "&ns_stir4=" + adpackage;
        }
        sitestat(url);
    }
}

function sitestat(ns_url) {
    ns_url += '&ns__t=' + (new Date()).getTime();
    ns_pixelUrl = ns_url;
    ns_0 = document.referrer;
    ns_0 = (ns_0.lastIndexOf('/') == ns_0.length - 1) ? ns_0.substring(ns_0.lastIndexOf('/'), 0) : ns_0;
    if (ns_0.length > 0) {
        ns_url += '&ns_referrer=' + escape(ns_0);
    }
    if (document.images) {
        ns_1 = new Image();
        ns_1.src = ns_url;
    } else {
        document.write('<img src="' + ns_url + '" width="1" height="1" alt="">');
    }
}

function getTimestamp() {
    uni = new Date();
    uni = uni.getTime();
    return uni;
}

// global click handler to provide cross browser tab-click support
var ClickHandler = function() {

    var tabClick = false;

    var isSpecialKeyPress = false;
    var isShiftKeyPress = false;
    var isCtrlKeyPress = false;
    var isMetaKeyPress = false;

    function isTrackedObject(obj) {
        var obj = $(obj);

        if (obj.closest('a').length <= 0) {
            return false;
        }

        return obj.closest('a').attr('class').match(/dms_/);
    };

    function isIE()
    {
        return $.browser.msie;
    };

    function isIE6()
    {
        // no middle click
        return ($.browser.msie) && ($.browser.version == '6.0');
    };

    return {
        init: function() {
            var handler = this;
            $(document).mousedown(function(e){
                handler.isTabClick(false);

                if (!isTrackedObject(e.target)) {
                    handler.clear();
                    return;
                }

                // ((ctrl/shift/meta) && (left/right button))
                if (isSpecialKeyPress && ((e.which == 1) || (e.which == 3))) {
                    handler.isTabClick(true);

                    // doesn't click, fire manually
                    if (isIE() && isCtrlKeyPress) {
                        $(e.target).closest('a').trigger('click');
                    }

                    return false;
                }

                // middle button
                if ((e.which == 2) && !isIE6()) {
                    handler.isTabClick(true);
                    $(e.target).closest('a').trigger('click');
                }
            });

            $(document).keydown(function(e) {
                isSpecialKeyPress = e.ctrlKey || e.shiftKey || e.metaKey;
                isCtrlKeyPress = e.ctrlKey;
            });

            $(document).keyup(function(e) {
                isCtrlKeyPress = isSpecialKeyPress = false;
            });
        },

        isTabClick: function(flag) {
            if (typeof flag == 'boolean') {
                tabClick = flag;
            }

            return tabClick;
        },

        clear: function() {
            tabClick = isCtrlKeyPress = isSpecialKeyPress = false;
        }
    };
}

window.cHandler = new ClickHandler();
window.cHandler.init();

var StatsGALinks = function() {
    return {
        init: function() {
            // ***** Configuratie *****

            // Uitgaande links naar deze domeinen negeren: ("domein1.nl www.domein2.nl")
            var ignore_urls      = DMSpage + ".overzicht.nl";

            var prefix_clickouts = "/clickout/";
            var prefix_mailto    = "/mailto/";

            // ***** Configuratie *****

            function addEvent(element, type, handler)
            {
              if (element.addEventListener)
              {
                element.addEventListener(type, handler, false);
              } else {
                if (!handler.$$guid) handler.$$guid = addEvent.guid++;
                if (!element.events) element.events = {};
                var handlers = element.events[type];
                if (!handlers)
                {
                  handlers = element.events[type] = {};
                  if (element["on" + type])
                  {
                    handlers[0] = element["on" + type];
                  }
                }
                handlers[handler.$$guid] = handler;
                element["on" + type] = handleEvent;
              }
            }
            addEvent.guid = 1;

            function handleEvent(event)
            {
              var returnValue = true;
              event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);
              var handlers = this.events[event.type];
              for (var i in handlers)
              {
                this.$$handleEvent = handlers[i];
                if (this.$$handleEvent(event) === false)
                {
                  returnValue = false;
                }
              }
              return returnValue;
            }

            function fixEvent(event)
            {
              event.preventDefault = fixEvent.preventDefault;
              event.stopPropagation = fixEvent.stopPropagation;
              return event;
            }

            fixEvent.preventDefault = function()
            {
              this.returnValue = false;
            }

            fixEvent.stopPropagation = function()
            {
              this.cancelBubble = true;
            }

            ignore_urls = document.domain + " " + ignore_urls;
            ignore_urls = ignore_urls.replace(/^\s+/,'').replace(/\s+$/,'');
            ignore_urls = ignore_urls.split(" ");

            function checkLinkToOwnDomains(txt)
            {
              for (var i = 0; i <= ignore_urls.length; i++)
              {
                if (txt.indexOf(ignore_urls[i]) > -1) { return false; }
              }
              return true;
            }

            elm = document.getElementsByTagName("a");
            for (var i = 0; i < elm.length; i++)
            {
              var path = elm[i].href + "";

              // Downloads
              if (path.match(/\.(doc|eps|jpg|png|svg|xls|ppt|pdf|xls|zip|txt|vsd|vxd|js|css|rar|exe|wma|mov|avi|wmv|mp3)/) != null)
              {
                if ((path.indexOf("http://" + location.host) > -1) || (checkLinkToOwnDomains(path) == false))
                {
                  addEvent(elm[i], "click", function() { pageTracker._trackPageview(this.href) } );
                }
              }

              // Mailto's
              if (path.indexOf("mailto:") > -1)
              {
                addEvent(elm[i], "click", function() { pageTracker._trackPageview(prefix_mailto + (this.href).substr(7)) } );
              }

              // Uitgaande links
              if ((checkLinkToOwnDomains(path)) && (path.indexOf("mailto:") == -1))
              {
                addEvent(elm[i], "click", function() { pageTracker._trackPageview(prefix_clickouts + (this.href).substr(7)) } );
              }
            }
        }
    }
};
