var VisionCritical = function() {
    /* private members */
    var _jQuery = false;
    var _apiKey = "";
    var _popupId = "";
    var _cookieName = "";
    var _uid = "";
    var _jsonCallback = new Object();
    var _container = null;

    var _twoYears = 365 * 2;

    var Settings = {
        host: "http://popup.custompanelsolutions.com",
        debug: false,
        forceAlert: true
    };

    function debug(msg) {

        if (!Settings.debug)
            return;

        if (window.console !== undefined && !Settings.forceAlert) {
            console.log(msg);
        }
        else {
            alert(msg);
        }
    }




    /** cookie utils */
    function createCookie(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
            var expires = "; expires=" + date.toGMTString();
        }
        else {
            var expires = "";
        }
        document.cookie = name + "=" + value + expires + "; path=/";
    }
    function readCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }
    function eraseCookie(name) {
        createCookie(name, "", -1);
    }


    function includeScript(url) {
        var script = document.createElement('script');
        script.type = "text/javascript";
        script.src = url;

//        console.log(_container);
        _container.appendChild(script);

        //document.body.appendChild(script);
        //document.write(unescape("%3Cscript src='" + url + "' type='text/javascript'%3E%3C/script%3E"));
    }
    function initjQuery() {
        if (window.jQuery == undefined) {
            includeScript("http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js");
        }
        jQueryReady();

        function jQueryReady() {
            if (window.jQuery === undefined) {
                window.setTimeout(jQueryReady, 50);
                return;
            }
            debug('jquery ready');
            _jQuery = true;
        }
    }

    function cookieSupport() {
        var name = "vccookiesupport";
        var value = "enabled";
        createCookie(name, value, 1);
        var readValue = readCookie(name);
        eraseCookie(name);
        return readValue == value;
    }


    function waitForJQuery() {
        //wait for jQuery.
        if (!_jQuery) {
            window.setTimeout(waitForJQuery, 50);
            return;
        }
        start(false);
    }

    function start(failOnNull) {
        var uid = readCookie(_cookieName);
        if (uid == null) {
            if (failOnNull) {
                debug("uid was null. failOnNull set.  bailling");
                return;
            }
            requestIdentifier();
            return;
        }

        //check for cookie support
        if (!cookieSupport()) {
            debug("cookies not supported.  bailing.");
            return;
        }
        else {
            debug("cookies supported.");
        }
        _uid = uid;
        loadPopupRequest();
    }

    function loadPopupRequest() {
        var requestUrl = Settings.host + "/js/popupinfo/" + _apiKey + "/" + _popupId + "/" + _uid + "?callback=VisionCritical.PopupInfoCallback";
        debug(requestUrl);
        includeScript(requestUrl);
    }



    function requestIdentifier() {
        var uidUrl = Settings.host + "/js/guid?callback=VisionCritical.PopupGuidCallback";
        includeScript(uidUrl);
    }
    function guidResponse(guid) {
        createCookie(_cookieName, guid, _twoYears);
        start(true);
    }


    function makeAbsolute(attrName, obj, baseUrl) {
        var href = $(obj).attr(attrName).substring(0, 4);
        if (href == "mail" || href == "http" || href == "#")
            return;
        var url = baseUrl + $(obj).attr(attrName);
        $(obj).attr(attrName, url);
    }


    function hookPopup(popupInfo) {
        var mask = $('<div/>');
        var box = $('<div/>');

        var popupText = popupInfo.Html;
        box.html(popupText);

        function setMaskSize() {
            //Get the screen height and width
            var maskHeight = $(window).height();
            var maskWidth = $(window).width();
            //Set height and width to mask to fill up the whole screen
            mask.css({ 'height': maskHeight, 'width': maskWidth });
        }
        function closePopup() {
            box.hide();
            var url = Settings.host + "/pixel/nocancel/" + popupInfo.HitId;
            var showPixel = $("<img/>").attr('src', url).css({ 'width': '1px', 'height': '1px' });
            $('body').append(showPixel);
            debug('appending close pixel');
        }


        //update urls
        box.find("a").each(function() {
            makeAbsolute('href', $(this), popupInfo.AssetRoot);
        });
        box.find("img").each(function() {
            makeAbsolute('src', $(this), popupInfo.AssetRoot);
        });


        /* add mask */

        mask = $("<div/>").css({
            'position': 'absolute',
            'top': '0',
            'left': ' 0',
            'z-index': '9000',
            'background-color': '#000',
            'display': 'none'
        });
        //        mask.click(function() {
        //            closePopup();
        //        });
        box.find('.vc-invite-close').click(function() {
            closePopup();
        });


        box.find('a.vc-invite-link').each(function() {
            debug('found a.vc-invite-link');
            $(this).click(function() {
                //open in a new window if 'target' specified
                var bounceUrl = Settings.host + "/bounce/" + popupInfo.HitId + "?url=" + escape($(this).attr('href'));
                var newWindow = $(this).attr('target').length != 0;
                if (newWindow) {
                    closePopup();
                    window.open(bounceUrl);
                }
                else {
                    window.location = bounceUrl;
                }
                return false;  
            });
        });
        box.find("div.vc-invite-window").each(function() {
            $(this).css({
                "position": "absolute",
                "left": "50%",
                "top": "50%",
                //                "width": "100%",
                //                "height": "1px",
                "overflow": "visible",
                "display": "none",
                "z-index": "9999",
                "padding": "0px"
            });
            var popupWidth = parseInt($(this).css("width").replace('px', ''));
            $(this).css("margin-left", -popupWidth / 2);
            var popupHeight = parseInt($(this).css("height").replace('px', ''));
            $(this).css("margin-top", -popupHeight / 2);
        });

        box.find('.vc-invite-window .language').click(function(e) {
            $(".vc-invite-window").toggle();
            return false;
        });



        setMaskSize();
        $(window).resize(function() {
            setMaskSize();
        });

        return { box: box, mask: mask };

    }






    function showPopup(popupInfo) {
        debug(popupInfo);
        if (popupInfo.Show == false) {
            debug("show not set.");
            return;
        }
        else {
            var f = function() {
                var url = Settings.host + "/pixel/show/" + popupInfo.HitId;
                var showPixel = $("<img/>").attr('src', url).css({ 'width': '1px', 'height': '1px' });
                var divs = hookPopup(popupInfo);

                //jQuery("body").append(popup);
                jQuery("body").append(showPixel);

                divs.box.append(divs.mask);

                jQuery("body").append(divs.box);
                divs.box.find("div.vc-invite-window:first").toggle();


                //transition effect		
                divs.mask.fadeIn(250);
                divs.mask.fadeTo("slow", 0.8);

                //transition effect
                $(divs.box).fadeIn(1000);



                return;

            };
            if (popupInfo.Delay > 0) {
                debug("showing in " + popupInfo.Delay + " ms");
                window.setTimeout(f, popupInfo.Delay);
            }
            else {
                debug("showing now!");
                f();
            }
        }
    }




    function addEvent(obj, evType, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(evType, fn, false);
            return true;
        } else if (obj.attachEvent) {
            var r = obj.attachEvent("on" + evType, fn);
            return r;
        } else {
            return false;
        }
    }
    /* public functions */
    return {
        //sets initial variables.
        Init: function(apiKey, popupId, containerId) {
		
		// one in 3 chance
		var rand = Math.floor(Math.random() * 3);
		if (rand != 0){
			return;
		}

		
            _apiKey = apiKey;
            _popupId = popupId;
            _cookieName = apiKey + "|" + popupId;
            _container = document.body;

            if (containerId != undefined) {
                var f = function() {
                    var item = document.getElementById(containerId);
                    if (item != null) {
                        _container = item;
                        initjQuery();
                        waitForJQuery();
                    }
                };
                addEvent(window, 'load', f);
            }
            else {
                initjQuery();
                waitForJQuery();
            }

        },
        PopupGuidCallback: function(guid) {
            guidResponse(guid);
        },
        PopupInfoCallback: function(popupInfo) {
            showPopup(popupInfo);
        }
    };
} ();
