﻿(function () { 
    //Settings  
    var loggurl = "/shop/custom/proxy.ashx?"; //Change to proxy for this site
    var ajaxDataType = 'json'; // The data type to use when sending ajax request to log service. 'json' or 'jsonp'
    var requestTimeout = 7000; //Timeout in milliseconds
    var ImagePath = "http://imp.nowinteract.com/logserver/RollupKungen/"; 
    //domain for cookies is now automatically set later in script
    var setDomain = ""; //Must be defined if subdomains are used
    //Container for properties
    var siteProperties = new Array();

    // Jquery setting
    //var $j = jQuery.noConflict(); //Use  if other ajax library is used
    var $j = $; //Use if jquery is referenced with $ in the site
    //private const for system events
    var sysEventFollowLink = 1;
    var sysEventCloseBox = 2;
    var sysEventMinimize = 3;
    var sysEventRestore = 4;
    var sysEventKey = "sysevent";
    var sysEventLogidKey = "interactionlogid";

    //Private functions
    var getDomain, setCookie, getCookie, getUserKey, getSessionKey, getReferrer, createUUID,
    getRequest, create_frame, displayInfo, hide_IMPiframe, setNoDisplay,
    getDisplyAllowed, displayInfoWithCheck, getNumberCheck, displayTeaserData, displayTeaserHtml;

    //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;
    }
    //Set Current domain for cookies
    //    setDomain = getDomain(); //Uncomment if domain should be set automatically

    //Declarations
    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 = "";

    //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' : '');
    };

    /*
    * Get cookie value
    */
    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;
    };
    //Creates unique userid
    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 (var key in siteProperties) {
            request += '&KeyValue=' + escapeWrapper(key) + ':' + escapeWrapper(siteProperties[key]);
        }
        return loggurl + request;
    };
    //ReturnNumbersOnly
    getNumberCheck = function (checkValue) {
        if (isNaN(checkValue)) {
            return 0;
        } else {
            return checkValue;
        }
    }

    //
    var displayCookieKey = "IMPDispcookie";
    setNoDisplay = function () {
        setCookie(displayCookieKey, 1);
    };
    getDisplyAllowed = function () {
        var stopDisplay = getCookie(displayCookieKey);
        if (stopDisplay) {
            return false;
        } else {
            return true;
        }
    };


    //display functions
    displayInfo = function (url, width, height, position, top, left, interactionLogId, overrideClosedMessage, closeButtonStyle, dragCode, useDrag) {

        if (getDisplyAllowed() || overrideClosedMessage) {
            var body = document.getElementsByTagName("body")[0];
            var container = document.createElement('div');
            container.id = "imp_container";
            body.appendChild(container);
            create_frame(container, url, width, height, position, top, left, interactionLogId, closeButtonStyle, dragCode, useDrag);
     
        }
    };
    create_frame = function (container, url, width, height, position, top, left, interactionLogId, closeButtonStyle, dragCode, useDrag) {

        if (position == 'center') {
            // Center the div
            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 {
            // Center the div
            var leftPos = '50%';
            var topPos = '50%';
            var leftMargin = '-' + (width / 2) + 'px';
            var topMargin = '-' + (height / 2) + 'px';
        }

        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;';

        var style = "position: absolute; right: 0px; padding:10px; cursor: pointer;";

        if (closeButtonStyle) {
            style = closeButtonStyle;
        }
        //Dragarea
        if (useDrag) {
            container.innerHTML += dragCode;
        }
        //CloseButton
        container.innerHTML +=
			    '<div style="' + style + '"><img title="Stäng" src="' + ImagePath + 'close.png" alt="" ' +
			    'id="imp_close" onclick="IMP.hide_IMPiframe(' + interactionLogId + ')"></div>';


        var iframeHTML = '<iframe id="frame1" src="' + url + '" scrolling="no" frameborder="no"  style="background: transparent; height:' + height + 'px;  width: ' + width + 'px;  " ALLOWTRANSPARENCY="true"></iframe>';
        container.innerHTML += iframeHTML;
        if (useDrag) {
            $j("#imp_container").draggable();
        }


    };
    //Filter external data and remove unwanted data
    displayInfoWithCheck = function (externalData) {
        bitmapDrag = 2;
        var displayUrl, width, height, position, delaySek, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle, dragCode, useDrag;
        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;
        dragCode = "";
        useDrag = false;
        if (externalData.VisualEffect & bitmapDrag) {
            useDrag = true;
            dragCode = externalData.DragableTopHtml;
        }

        if (delaySek > 0) {
            setTimeout(function () { displayInfo(displayUrl, width, height, position, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle, dragCode, useDrag) }, delaySek * 1000);
        } else {
            displayInfo(displayUrl, width, height, position, topPos, leftPos, interactionLogId, overrideClosedMessage, closeButtonStyle, dragCode, useDrag);
        }
    };
    //Teaser displays
    displayTeaserData = function (externalData) {
        var _displayUrl, _width, _height, _position, _delaySek, _topPos, _leftPos, _contentHtml, _interactionLogId;
        _width = getNumberCheck(externalData.Width);
        _height = getNumberCheck(externalData.Height);
        _position = externalData.Position;
        _delaySek = externalData.DelaySek;
        _topPos = getNumberCheck(externalData.TopPos);
        _leftPos = getNumberCheck(externalData.LeftPos);
        _contentHtml = externalData.HtmlBody;
        _delaySek = externalData.DelaySek;
        _interactionLogId = externalData.InteractionLogId;
        if (_delaySek > 0) {
            setTimeout(function () { displayTeaserHtml(_contentHtml, _width, _height, _position, _topPos, _leftPos, _interactionLogId) }, _delaySek * 1000);
        } else {
            displayTeaserHtml(_contentHtml, _width, _height, _position, _topPos, _leftPos, _interactionLogId);
        }
    };
    displayTeaserHtml = function (contentHtml, width, height, position, top, left, interactionLogId) {
        if (position == 'center') {
            // Center the div
            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 {
            // Center the div
            var leftPos = '50%';
            var topPos = '50%';
            var leftMargin = '-' + (width / 2) + 'px';
            var topMargin = '-' + (height / 2) + 'px';
        }
        var body = document.getElementsByTagName("body")[0];
        var container = document.createElement('div');
        container.id = "imp_puff";
        container.style.cssText = "position: absolute; left: " + leftPos + "; margin-left: " + leftMargin + "; width: " + width + "px; top: " + topPos + "; margin-top: " + topMargin + "; height: " + height + "px; z-index:9998; background: transparent;";
        container.innerHTML = contentHtml;
        body.appendChild(container);
        $j("#imp_puff").click(function () {
            IMP.trackFollowLink(interactionLogId);
        });
    };

    return IMP = {
        //Public hide function
        hide_IMPiframe: function (interactionLogId) {
            var element = document.getElementById("imp_container");
            if (element) {
                element.parentNode.removeChild(element);
            }
            setNoDisplay(); //Dont show message more in this session
            IMP.trackCloseBox(interactionLogId); //Inform box closed
        },
        //Public functions
        initsite: function (siteId) {
            configTrackerSiteId = siteId;
        },
        clearSiteProp: function () {
            siteProperties = new Array();
        },
        appendSiteProp: function (key, value) {
            siteProperties[key] = value;
        },
        trackLogging: function () {
            $j.ajax({ url: getRequest(), dataType: ajaxDataType, timeout: requestTimeout, success: function (data) {
                if (data) {
                    if (data.HasNormalMessage) {
                        displayInfoWithCheck(data);
                    }
                    if (data.HasTeaserMessage) {
                        displayTeaserData(data.TeaserMessage);
                    }
                }
            }
            })
        },
        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) {

            }
            })
        },
        trackFollowLink: function (interactionLogId) {
            IMP.trackSystemEvent(sysEventFollowLink, interactionLogId);
        },
        trackCloseBox: function (interactionLogId) {
            IMP.trackSystemEvent(sysEventCloseBox, interactionLogId);
        }
    };
} ());

