(function () {
 //////////////////////////////////////////////////////////////////////////////
 // Start config  
 //////////////////////////////////////////////////////////////////////////////
 
 // Protocol - do no change
    var protocol = (("https:" == document.location.protocol) ? "https:" : "http:");
 // Log server adress, do not change unless proxy is used (i.e. loggurl = "/ResponseService.ashx?";)
    var loggurl = protocol + "//imp.nowinteract.com/logserver/ResponseService.ashx?"; 
 // The data type to use - do not change unless proxy is used (in thcas change to json)
    var ajaxDataType = 'jsonp'; 
 // Max time - standard value - do not change
    var requestTimeout = 7000; 
 
 // Jquery setting
 //var $j = jQuery.noConflict(); //Use  if other ajax library is used
 var $j = $; //Use if jquery is referenced with $ in the site

 //////////////////////////////////////////////////////////////////////////////    
 // End config  
 //////////////////////////////////////////////////////////////////////////////


    // Private const for system events
    var sysEventFollowLink = 1;
    var sysEventCloseBox = 2;
    var sysEventMinimize = 3;
    var sysEventRestore = 4;
    var sysEventDisplay = 5;
    var sysEventKey = "sysevent";
    var sysEventLogidKey = "interactionlogid";

    // Private data and functions
    var imp_sitePropertiesKey = new Array();
    var imp_sitePropertiesValue = new Array();
    var imp_sitePropertiesLength = 0;
    var containerid="imp_container";

    var documentAlias = document,
        windowAlias = window,
        escapeWrapper = windowAlias.encodeURIComponent || escape,
       // decode or unescape - decodeURIComponent added in IE5.5
        unescapeWrapper = windowAlias.decodeURIComponent || unescape,
        configUrl = documentAlias.location.href;
    var configTrackerSiteId = "";

    var getDomain, setCookie, getCookie, getUserKey, getSessionKey, getReferrer, createUUID,
    getRequest, displayInfo, hide_IMPiframe, setNoDisplay,
    getDisplayAllowed, displayInfoWithCheck, getNumberCheck;

    //Get domain without subdomain part
    getDomain = function () {
        var hostname = document.location.hostname;
        var lastPos = hostname.lastIndexOf('.');
        if (lastPos > -1) {
            var secondLast = hostname.lastIndexOf('.', (lastPos - 1));
            if (secondLast > -1) {
                hostname = hostname.substr((secondLast + 1));
            }
        }
        return hostname;
    }

    // Domain with out without subdomain
    var setDomain = "";
    setDomain = getDomain(); // Comment if subdomain logging to be individual

    // Cookie functions
    setCookie = function (cookieName, value, daysToExpire, path, domain, secure) {
        var expiryDate;

        if (daysToExpire) {
            // time is in milliseconds
            expiryDate = new Date();
            // there are 1000 * 60 * 60 * 24 milliseconds in a day (i.e., 86400000 or 8.64e7)
            expiryDate.setTime(expiryDate.getTime() + daysToExpire * 8.64e7);
        }
        if (setDomain) {
            domain = setDomain;
        }
        documentAlias.cookie = cookieName + '=' + escapeWrapper(value) +
					                  (daysToExpire ? ';expires=' + expiryDate.toGMTString() : '') +
					                  ';path=' + (path ? path : '/') +
					                  (domain ? ';domain=' + domain : '') +
					                  (secure ? ';secure' : '');
    };

    getCookie = function (cookieName) {
        var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'),
			cookieMatch = cookiePattern.exec(documentAlias.cookie);

        return cookieMatch ? unescapeWrapper(cookieMatch[2]) : 0;
    };

    // User data functions
    getUserKey = function () {
        var cookieKey = "IMPloggcookie";
        var userKey = getCookie(cookieKey);
        if (userKey) {

        } else {
            userKey = createUUID();
        }
        setCookie(cookieKey, userKey, 300);
        return userKey;
    };
    getSessionKey = function () {
        var cookieKey = "IMPSession";
        var sessKey = getCookie(cookieKey);
        if (sessKey) {

        } else {
            sessKey = createUUID();
        }
        setCookie(cookieKey, sessKey);
        return sessKey;
    };
    getReferrer = function () {
        var referrer = '';
        try {
            referrer = top.document.referrer;
        } catch (e) {
            if (parent) {
                try {
                    referrer = parent.document.referrer;
                } catch (e2) {
                    referrer = '';
                }
            }
        }
        if (referrer === '') {
            referrer = documentAlias.referrer;
        }
        return referrer;
    };

    // Unique ID
    createUUID = function () {
        // http://www.ietf.org/rfc/rfc4122.txt 
        var s = [];
        var hexDigits = "0123456789ABCDEF";
        for (var i = 0; i < 32; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[12] = "4";  // bits 12-15 of the time_hi_and_version field to 0010 
        s[16] = hexDigits.substr((s[16] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01 

        var uuid = s.join("");
        return uuid;
    };

    // Build request with parameters
    getRequest = function () {
        var i, now, request;
        now = new Date();
        request = 'siteid=' + configTrackerSiteId +
				        '&url=' + escapeWrapper(configUrl) +
				        '&urlref=' + escapeWrapper(getReferrer()) +
                        '&userkey=' + escapeWrapper(getUserKey()) +
                        '&impsess=' + escapeWrapper(getSessionKey()) +
				        '&rand=' + Math.random();
        for (keyIndex=0;keyIndex<imp_sitePropertiesLength;keyIndex++) {
            request += '&KeyValue=' + escapeWrapper(imp_sitePropertiesKey[keyIndex]) + ':' + escapeWrapper(imp_sitePropertiesValue[keyIndex]);
        }
        return loggurl + request;
    };

    // Number check
    getNumberCheck = function (checkValue) {
        if (isNaN(checkValue)) {
            return 0;
        } else {
            return checkValue;
        }
    }

    // Display setting
    var displayCookieKey = "IMPDispcookie";
    setNoDisplay = function () {
        setCookie(displayCookieKey, 1);
    };
    getDisplayAllowed = function () {
        var stopDisplay = getCookie(displayCookieKey);
        if (stopDisplay) {
            return false;
        } else {
            return true;
        }
    };

    // Image path
    getImagePath = function (url) {
        var imagePath = "";
        var lastPos = url.lastIndexOf("/");
        if (lastPos > -1) {
                imagePath = url.substr(0,lastPos+1);
        } else {
          lastPos = loggurl.lastIndexOf("/");
          if (lastPos > -1) {
                  imagePath = loggurl.substr(0,lastPos+1);
          } else {
            imagePath = "";
          }
        }
        return imagePath;
    }

    // Display functions
    displayInfo = function (url, width, height, position, top, left, interactionLogId, overrideClosedMessage, closeButtonStyle) {
        if (getDisplayAllowed() || overrideClosedMessage) {
            // clear existing container of same kind
            var element = document.getElementById(containerid);
            if (element) {
                element.parentNode.removeChild(element);
            }

            // make a new container
            var container = document.createElement('div');
            container.id = containerid ;

            // attach container
            body = document.getElementsByTagName("body")[0];
            body.appendChild(container);

            // position container
            position_container(container, width, height, position, top, left);

            // fill container with content
            fill_container(containerid, container, url, width, height, interactionLogId, closeButtonStyle);

            IMP.trackDisplay(interactionLogId);
        }
    };

    position_container = function (container, width, height, position, top, left) {

        if (position == 'center') {
            var leftPos = '50%';
            var topPos = '50%';
            var leftMargin = '-' + (width / 2) + 'px';
            var topMargin = '-' + (height / 2) + 'px';
        } else if (position == 'absolute') {
            var leftPos = left + 'px';
            var topPos = top + 'px';
            var leftMargin = '0px';
            var topMargin = '0px';
        } else if (position == 'fixed') {
            var leftPos = left + 'px';
            var topPos = top + 'px';
            var leftMargin = '0px';
            var topMargin = '0px';
        } else if (position == 'absoluteright') {
            var leftPos = left + 'px';
            var topPos = top + 'px';
            var leftMargin = '0px';
            var topMargin = '0px';
        } else if (position == 'fixedright') {
            var leftPos = left + 'px';
            var topPos = top + 'px';
            var leftMargin = '0px';
            var topMargin = '0px';
        } else if (position == 'relative') {
            var leftPos = '50%';
            var topPos = top + 'px';
            var leftMargin = '-' + ((width / 2) - left) + 'px';
            if ( ((width / 2) - left) < 0 ) {
              leftMargin = left - (width / 2) + 'px';
            }
            var topMargin = '0px';
        } else if (position == 'fixedrelative') {
            var leftPos = '50%';
            var topPos = top + 'px';
            var leftMargin = '-' + ((width / 2) - left) + 'px';
            if ( ((width / 2) - left) < 0 ) {
              leftMargin = left - (width / 2) + 'px';
            }
            var topMargin = '0px';
        } else {
            // Center the div
            var leftPos = '50%';
            var topPos = '50%';
            var leftMargin = '-' + (width / 2) + 'px';
            var topMargin = '-' + (height / 2) + 'px';
        }


        if ( (position == 'fixed') || (position == 'fixedrelative') ) {
          container.style.cssText = 'position: fixed; left: ' + leftPos + '; margin-left: ' + leftMargin + '; width: ' + width + 'px; top: ' + topPos + '; margin-top: ' + topMargin + '; height: ' + height + 'px; z-index:9999; background:  transparent;';
        } else if (position == 'fixedright') {
          container.style.cssText = 'position: fixed; right: ' + leftPos + '; margin-right: ' + leftMargin + '; width: ' + width + 'px; top: ' + topPos + '; margin-top: ' + topMargin + '; height: ' + height + 'px; z-index:9999; background:  transparent;';
        } else if (position == 'absoluteright') {
          container.style.cssText = 'position: absolute; right: ' + leftPos + '; margin-right: ' + leftMargin + '; width: ' + width + 'px; top: ' + topPos + '; margin-top: ' + topMargin + '; height: ' + height + 'px; z-index:9999; background:  transparent;';
        } else {
          container.style.cssText = 'position: absolute; left: ' + leftPos + '; margin-left: ' + leftMargin + '; width: ' + width + 'px; top: ' + topPos + '; margin-top: ' + topMargin + '; height: ' + height + 'px; z-index:9999; background:  transparent;';
        }

    };

    fill_container = function (containerid, container, url, width, height, interactionLogId, closeButtonStyle) {

        // The actual content
        add_iframe_container(containerid, container, url, height, width)

        // The X button
        var closeButtonPath = getImagePath(url) + "close.png";
        if (closeButtonStyle) {
            closeButtonStyle = closeButtonStyle;
        } else {
            closeButtonStyle = "position: absolute; right: 0px; padding:10px; top:0px; cursor: pointer";
        }
        add_button_container(containerid, container, closeButtonPath, closeButtonStyle, "Stäng", "Stäng", "IMP.hide_IMPiframe", interactionLogId);

    };

    add_iframe_container = function(containerid, container, url, height, width) {
        var iframeId = containerid + "Frame";
        var iframeHTML = 
                '<iframe id="' + iframeId + '" ' +
                ' src="' + url + '" ' +
                ' scrolling="no" ' +
                ' frameborder="no" ' +
                ' style="background: transparent; ' + 'height:' + height + 'px; ' + 'width: ' + width + 'px; ' + '" ' +
                ' ALLOWTRANSPARENCY="true"' +
                '></iframe>';
        container.innerHTML += iframeHTML;
    }

    add_button_container = function (containerid, container, buttonPath, buttonStyle, buttonTitle, buttonClass, buttonOnClickMethod, interactionLogId) {

        var buttonId, buttonOnClick, buttonTitle;
        if (buttonStyle) {
           buttonId = containerid + "_" + buttonTitle;
           buttonOnClick = buttonOnClickMethod + "(" + interactionLogId + ")";

           container.innerHTML +=
			'<div style="' + buttonStyle + '">' + 
                  '<img id=' + '"' + buttonId + '"' +  
                     ' class=' + '"' + buttonClass + '"' +  
                     ' title=' + '"' + buttonTitle + '"' +
                     ' src=' + '"' + buttonPath + '"' +
                     ' alt=""' +
                     ' id=' + '"' + buttonId + '"' +
                     ' onclick=' + '"' + buttonOnClick + '"' + 
                  '>' + 
                  '</div>';

        } else {
          // do not place out button without style
        }
    }

    displayInfoWithCheck = function (externalData) {
        var displayUrl, width, height, position, delaySek, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle;

        displayUrl = externalData.DisplayUrl;
        width = getNumberCheck(externalData.Width);
        height = getNumberCheck(externalData.Height);
        position = externalData.Position;
        delaySek = externalData.DelaySek;
        topPos = getNumberCheck(externalData.TopPos);
        leftPos = getNumberCheck(externalData.LeftPos);
        closeButtonStyle = externalData.BgStyle
        interactionLogId = externalData.InteractionLogId;
        overrideClosedMessage = externalData.OverrideClosedMessage;
        if (delaySek > 0) {
            setTimeout(function () { 
              displayInfo(displayUrl, width, height, position, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle) 
            }, delaySek * 1000);
        } else {
            displayInfo(displayUrl, width, height, position, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle);
        }
     };
 
     return IMP = {
        hide_IMPiframe: function (interactionLogId) {
            var element = document.getElementById(containerid);
            if (element) {
                element.parentNode.removeChild(element);
            }
            setNoDisplay();
            IMP.trackCloseBox(interactionLogId);
        },

        initsite: function (siteId) {
            configTrackerSiteId = siteId;
        },

        clearSiteProp: function () {
            imp_sitePropertiesKey = new Array();
            imp_sitePropertiesValue = new Array();
            imp_sitePropertiesLength = 0;
        },

        appendSiteProp: function (key, value) {
            imp_sitePropertiesKey[imp_sitePropertiesLength] = key;
            imp_sitePropertiesValue[imp_sitePropertiesLength] = value;
            imp_sitePropertiesLength++;
        },

        trackInteract: function () {
            $j.ajax({ url: getRequest(), dataType: ajaxDataType, timeout: requestTimeout, success: function (data) {
                if (data) {
                    if (data.HasNormalMessage) {
                        displayInfoWithCheck(data);
                    }
                }
            }
            });
            IMP.clearSiteProp();
        },

        trackLogging: function () {
            $j.ajax({ url: getRequest(), dataType: ajaxDataType, timeout: requestTimeout, success: function (data) {

            }
            });
            IMP.clearSiteProp();
        },

        trackSystemEvent: function (eventCode, interactionLogId) {
            IMP.clearSiteProp();
            IMP.appendSiteProp(sysEventKey, eventCode);
            IMP.appendSiteProp(sysEventLogidKey, interactionLogId);
            $j.ajax({ url: getRequest(), dataType: ajaxDataType, timeout: requestTimeout, success: function (data) {

            }
            });
            IMP.clearSiteProp();
        },

        trackCloseBox: function (interactionLogId) {
            IMP.trackSystemEvent(sysEventCloseBox, interactionLogId);
        },

        trackDisplay: function (interactionLogId) {
            IMP.trackSystemEvent(sysEventDisplay, interactionLogId);
        }
    };
} ());

