var YEDDA = {}
YEDDA.Utils = {}
YEDDA.Utils.isElementVisible = {
    /* Get the TOP position of a given element. */
    getPositionTop: function(element) {
        var offset = 0;
        while (element) {
            offset += element["offsetTop"];
            element = element.offsetParent;
        }
        return offset;
    },

    getViewportScrollY: function() {
        var scrollY = 0;
        if (document.documentElement && document.documentElement.scrollTop) {
            scrollY = document.documentElement.scrollTop;
        }
        else if (document.body && document.body.scrollTop) {
            scrollY = document.body.scrollTop;
        }
        else if (window.pageYOffset) {
            scrollY = window.pageYOffset;
        }
        else if (window.scrollY) {
            scrollY = window.scrollY;
        }
        return scrollY;
    },

    getViewportHeight: function() {
        var height = 0;
        if (document.documentElement && document.documentElement.clientHeight) {
            height = document.documentElement.clientHeight;
        }
        else if (document.body && document.body.clientHeight) {
            height = document.body.clientHeight;
        }
        else if (window.innerHeight) {
            height = window.innerHeight - 18;
        }
        return height;
    },

    /* Is a given element is visible or not? */
    isVisible: function(eltId, pxTop) {
        if (!pxTop)
            pxTop = 0;
        var elt = document.getElementById(eltId);
        if (!elt) {
            // Element not found.
            return false;
        }
        // Get the top and bottom position of the given element.
        var visibleTop = this.getViewportHeight() + this.getViewportScrollY() - elt.offsetHeight;

        var posTop = this.getPositionTop(elt) - pxTop;
        var posBottom = visibleTop - posTop + elt.offsetHeight;

        // Get the top and bottom position of the *visible* part of the window. 
        if (pxTop == 0)
            return (posTop <= visibleTop && posBottom <= this.getViewportHeight());
        else {
            return (posTop <= visibleTop);
        }
    }
}

YeddaInterval = function() {
    this.interval = "";

    this.set = function(code, delay) {
        this.interval = setInterval(code, delay);
    }

    this.clear = function() {
        clearInterval(this.interval);
    }
}

YeddaTracker = function() {
    this.render = function(url) {
        var img = document.createElement("img");
        img.src = url;
        img.setAttribute("visiblity", "hidden");
        img.setAttribute("display", "none");
        img.setAttribute("width", 0);
        img.setAttribute("height", 0);

        document.getElementsByTagName("body")[0].appendChild(img);
    }
}
YeddaWidget = function(v, locale) {

    /* Browser detection function - http://www.quirksmode.org/js/detect.html */

    var BrowserDetect = {
        init: function() {
            this.browser = this.searchString(this.dataBrowser) || "Unknown-Browser";
            this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion);
        },
        searchString: function(data) {
            for (var i = 0; i < data.length; i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function(dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
        },
        dataBrowser: [
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Chrome",
		    identity: "Chrome"
		}
	]
    };

    this.render = function() {

        BrowserDetect.init(); // init the object
        var _st = new String(BrowserDetect.version); // get the full string ( e.g - Firefox 3.0.3 )
        var _brwsver = BrowserDetect.browser + "-" + _st.split(".")[0]; // get the browser string and only the major version ( e.g - Firefox 3 )
        var _r = Math.floor(Math.random() * 10 + 1); // random variable for the cdn        
        var _clean = new Array(); // the cleaned array that will be passed to our widget backend
        var _d = false;

        /* Check for firebug and for the debug variable */
        if (window.console && window.console.log && typeof (this.debug) != "undefined") {
            _d = true;
            this.logger = function(line) {
                console.log(line);
            }
        }
        else {
            _d = false;
            this.logger = function(line) {
                // Do nothing                
            }
        }

        var host = "aolanswers.com"; // default

        if (locale) {
            switch (locale) {
                case "es": host = "esyedda.com"; break;
                case "it": host = "genio.virgilio.it"; break;
                default:
                    host = "aolanswers.com";
            }
        }

        this.logger("Yedda Widget Debug Console");
        this.logger("===========================");
        this.logger("Browser: " + _brwsver);
        this.logger("Widget Base URL: http://widgets." + host + "/api/widgets/");
        /* Note that all values are escaped */

        if (v) {
            v = parseInt(v);
            _clean.push("v=" + v);
            this.logger("Widget Version: " + v);
        }

        this.logger("===========================");
        this.logger("Checking and escaping input...");

        if (typeof (this.widgetId) != 'undefined') {
            var st = new String(this.widgetId);
            var len = st.length - 1;
            if (len > 1) {
                if (st[len] == "s" || st[len] == "S")
                    _r = 0;
            }
            _clean.push("d=" + parseInt(this.widgetId));
        }
        if (this.widgetId == 666 || this.widgetId == 670 || this.widgetId == 526) {
            _r = 0;
        }

        if (typeof (this.ctxUrl) != 'undefined') {
            _clean.push("ctxu=" + encodeURIComponent(this.ctxUrl));
        }
        if (typeof (this.ctxText) != 'undefined') {
            _clean.push("ctxt=" + encodeURIComponent(this.ctxText));
        }
        if (typeof (this.previewMode) != 'undefined') {
            _clean.push("pm=" + this.previewMode);
        }
        if (typeof (this.useCustomStyling) != 'undefined') {
            _clean.push("usecustomstyling=" + this.useCustomStyling);
        }
        if (typeof (this.hrefTarget) != 'undefined') {
            _clean.push("ht=" + encodeURIComponent(this.hrefTarget));
        }
        if (typeof (this.preSeltags) != 'undefined') {
            _clean.push("pstags=" + encodeURIComponent(this.preSeltags));
        }
        if (typeof (this.maxTextLen) != 'undefined') {
            _clean.push("textLength=" + this.maxTextLen);
        }
        if (typeof (this.maxAnswers) != 'undefined') {
            _clean.push("max=" + this.maxAnswers);
        }
        if (typeof (this.qid) != 'undefined') {
            _clean.push("qid=" + this.qid);
        }
        if (typeof (this.msgTemplate) != 'undefined') {
            _clean.push("mt=" + encodeURIComponent(this.msgTemplate));
        }
        if (typeof (this.msgTemplate_captionText) != 'undefined') {
            _clean.push("mt.ct=" + encodeURIComponent(this.msgTemplate_captionText));
        }
        if (typeof (this.msgTemplate_questionHelpText) != 'undefined') {
            _clean.push("mt.qht=" + encodeURIComponent(this.msgTemplate_questionHelpText));
        }
        if (typeof (this.tags) != 'undefined') {
            _clean.push("tags=" + encodeURIComponent(this.tags));
        }
        if (typeof (this.category) != 'undefined') {
            _clean.push("category=" + encodeURIComponent(this.category));
        }
        if (typeof (this.elementId) != 'undefined') {
            _clean.push("elementid=" + this.elementId);
        }
        if (typeof (this.anchorId) != 'undefined') {
            _clean.push("id=" + this.anchorId);
        }
        if (typeof (this.singleLine) != 'undefined') {
            _clean.push("sl=" + this.singleLine);
        }
        if (typeof (this.widgetTitle) != 'undefined') {
            _clean.push("title=" + encodeURIComponent(this.widgetTitle));
        }
        if (typeof (this.layout) != 'undefined') {
            _clean.push("layout=" + this.layout);
        }
        if (typeof (this.askButtonTitle) != 'undefined') {
            _clean.push("askBT=" + encodeURIComponent(this.askButtonTitle));
        }
        if (typeof (this.defaultQuestionText) != 'undefined') {
            _clean.push("dqt=" + encodeURIComponent(this.defaultQuestionText));
        }
        if (typeof (this.topicsTitle) != 'undefined') {
            _clean.push("topicsTitle=" + encodeURIComponent(this.topicsTitle));
        }
        if (typeof (this.showLogo) != 'undefined') {
            _clean.push("showLogo=" + this.showLogo);
        }
        if (typeof (this.showTitleText) != 'undefined') {
            _clean.push("stt=" + this.showTitleText);
        }
        if (typeof (this.showHelpText) != 'undefined') {
            _clean.push("sht=" + this.showHelpText);
        }
        if (typeof (this.blogName) != 'undefined') {
            _clean.push("bn=" + this.blogName);
        }
        if (typeof (this.blogUrl) != 'undefined') {
            _clean.push("bu=" + encodeURIComponent(this.blogUrl));
        }
        if (typeof (this.exludedCtxUrl) != 'undefined') {
            _clean.push("xctxtu=" + encodeURIComponent(this.exludedCtxUrl));
        }
        if (typeof (this.showAnswers) != 'undefined') {
            _clean.push("aa=" + this.showAnswers);
        }
        if (typeof (this.enableAskLink) != 'undefined') {
            _clean.push("ea=" + this.enableAskLink);
        }
        if (typeof (this.mode) != 'undefined') {
            _clean.push("mode=" + this.mode);
        }
        if (typeof (this.ropid) != 'undefined') {
            _clean.push("ropid=" + this.ropid);
        }
        if (typeof (this.minAge) != 'undefined') {
            _clean.push("minAge=" + this.minAge);
        }
        if (typeof (this.maxAge) != 'undefined') {
            _clean.push("maxAge=" + this.maxAge);
        }
        if (typeof (this.userId) != 'undefined') {
            _clean.push("userId=" + this.userId);
        }
        if (typeof (this.CIR) != 'undefined') {
            _clean.push("CIR=" + encodeURIComponent(this.customImageRootDir));
        }
        if (typeof (this.userIconText) != 'undefined') {
            _clean.push("UIT=" + encodeURIComponent(this.userIconText));
        }
        if (typeof (this.answerButtonText) != 'undefined') {
            _clean.push("ABT=" + encodeURIComponent(this.answerButtonText));
        }
        if (typeof (this.replyButtonText) != 'undefined') {
            _clean.push("RBT=" + encodeURIComponent(this.replyButtonText));
        }
        if (typeof (this.answerTitle) != 'undefined') {
            _clean.push("answerTitle=" + encodeURIComponent(this.answerTitle));
        }
        if (typeof (this.askTitle) != 'undefined') {
            _clean.push("askTitle=" + encodeURIComponent(this.askTitle));
        }
        if (typeof (this.heightControl) != 'undefined') {
            _clean.push("X.HC=" + this.heightControl);
        }
        if (typeof (this.galleryId) != 'undefined') {
            _clean.push("galleryId=" + this.galleryId);
        }
        if (typeof (this.cssPrefix) != 'undefined') {
            _clean.push("miniGalleryCssPrefix=" + encodeURIComponent(this.cssPrefix));
        }

        this.logger("Done!");

        _clean.push("rand=" + _r);

        var passedActx = true; // for debugging

        switch (typeof (this.autoCtx)) {
            case "number": this.autoCtx == 1 ? this.autoCtx = true : this.autoCtx = false; break;
            case "string": this.autoCtx.toLowerCase() == "true" ? this.autoCtx = true : this.autoCtx = false; break;
            case "undefined": var passedActx = false; this.autoCtx = true;
            case "boolean": break; // if its boolean.. we're ok!
            default:
                this.autoCtx = true;
        }

        /* autoCtx Logic:
        If ctxUrl / ctxText were passed they were already filled in the _clean array
        Fill these values ONLY if they are "undefined" and the autoCtx is set to TRUE
        */

        if (this.autoCtx && typeof (this.ctxUrl) == "undefined")
            _clean.push("ctxu=" + encodeURIComponent(document.location));

        if (this.autoCtx && typeof (this.ctxText) == "undefined") {
            var ctxt = (document.title) ? document.title : "";

            _clean.push("ctxt=" + encodeURIComponent(ctxt).replace(/'/g, "%27"));
        }

        if (_d) {
            this.logger("===========================");
            this.logger("Dumping input variables:");
            for (k in this) {
                if (k == 'autoCtx' && !passedActx) continue;
                if (k == 'logger' || k == 'render') continue;
                this.logger(k + " = " + this[k]);
            }
            this.logger("===========================");
            this.logger("Dumping cleaned variables:");
            for (v in _clean) {
                this.logger(_clean[v]);
            }
            this.logger("===========================");
        }

        _clean.push("brwsver=" + _brwsver);

        var _joinedClean = _clean.join("&");

        var scriptUrl = "http://widgets." + host + "/api/widgets/?" + _joinedClean;

        this.logger("Rendering image tracking...");
        if (this.widgetId != '6054s' && this.widgetId != '6055s') {
            document.write('<img src="http://' + host + '/wtrack/?' + _joinedClean + '&domain=http://widgets.' + host + '/api/widgets/' + '&wtrand=' + Math.random() + '" style="visiblity: hidden; display: none;"/>');
        }
        this.logger("Done!");

        this.logger("Rendering widget... ( " + scriptUrl + " )");
        if (this.widgetId != 666 && this.widgetId != 4035 && this.widgetId != 526) {
            if (this.widgetId == 4023) {
                document.write('<link href=\"http://s1.anscdn.net/Styles/Partners/AOL/Switched/SwitchedAskHelpOthers.css\" rel=\"stylesheet\" type=\"text/css\"></link>');
            }
            document.write('<div id="YeddaWidget' + this.widgetId + '">');
            document.write('<scr' + 'ipt type=\"text/javascript\" src=\"' + scriptUrl + '\"></scr' + 'ipt>');
            if (this.widgetId != '6054s' && this.widgetId != '6055s') {
                YEDDA.trackerVar = new YeddaInterval();
                YEDDA.trackerVar.set('if (YEDDA.Utils.isElementVisible.isVisible("YeddaWidget' + this.widgetId + '")) { YEDDA.trackerVar.clear(); var tracker = new YeddaTracker(); tracker.render("http://' + host + '/wtrack/?domain=http://widgets.' + host + '/api/widgets/&widgetId=' + this.widgetId + '&type=visibilityWidget"); }', 500);
            }
            document.write('</div>');
        } else {
            if (host == "aolanswers.com") {
                YEDDA.trackerVar = new YeddaInterval();
                YEDDA.belowTheFold = new YeddaInterval();
                if (this.widgetId == 666) {
                    document.write('<iframe id="yedda-aol-news-mini-gallery" width="460" height="370" frameborder="0" scrolling="no" src="http://s1.anscdn.net/partners/aol/news?miniGalleryTitle=What\'s%20Your%20Take%20On%20The%20News%3F&' + _joinedClean + '"></iframe><style type="text/css">.center1_4 .yeddawyt { border:0 !important;padding:0 !important}</style>');
                    YEDDA.trackerVar.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-aol-news-mini-gallery")) { var tracker = new YeddaTracker(); tracker.render("http://aolanswers.com/wtrack/?domain=http://widgets.aolanswers.com/api/widgets/&widgetId=666&type=visibilityWidget"); YEDDA.trackerVar.clear(); }', 500);
                    YEDDA.belowTheFold.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-aol-news-mini-gallery",400)) { document.getElementById("yedda-aol-news-mini-gallery").src += "#yeddacnt"; YEDDA.belowTheFold.clear(); }', 500);
                } else if (this.widgetId == 4035) {
                document.write('<iframe id="yedda-aim-mini-gallery" width="625" height="370" frameborder="0" scrolling="no" src="http://s1.anscdn.net/partners/aol/aim/?' + _joinedClean + '"></iframe>');
                    YEDDA.trackerVar.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-aim-mini-gallery")) { var tracker = new YeddaTracker(); tracker.render("http://aolanswers.com/wtrack/?domain=http://widgets.aolanswers.com/api/widgets/&widgetId=4035&type=visibilityWidget"); YEDDA.trackerVar.clear(); }', 500);
                    YEDDA.belowTheFold.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-aim-mini-gallery",400)) { document.getElementById("yedda-aim-mini-gallery").src += "#yeddacnt"; YEDDA.belowTheFold.clear(); }', 500);
                } else if (this.widgetId == 526) {
                    document.write('<iframe id="yedda-stylelist-mini-gallery" width="460" height="400" frameborder="0" scrolling="no" src="http://s1.anscdn.net/partners/aol/stylelist/?' + _joinedClean + '"></iframe>');
                    YEDDA.trackerVar.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-stylelist-mini-gallery")) { var tracker = new YeddaTracker(); tracker.render("http://aolanswers.com/wtrack/?domain=http://widgets.aolanswers.com/api/widgets/&widgetId=526&type=visibilityWidget"); YEDDA.trackerVar.clear(); }', 500);
                    YEDDA.belowTheFold.set('if (YEDDA.Utils.isElementVisible.isVisible("yedda-stylelist-mini-gallery",400)) { document.getElementById("yedda-stylelist-mini-gallery").src += "#yeddacnt"; YEDDA.belowTheFold.clear(); }', 500);
                }
            }
        }

        this.logger("Done!");
    }
}

yedda_render_widget = function(url) {
    if (url) {
        var urlParts = url.split("?");
        if (urlParts.length >= 2) {
            var args = new Object();
            var pairs = urlParts[1].split("&");

            for (var i = 0; i < pairs.length; i++) {
                var pos = pairs[i].indexOf('=');
                if (pos == -1) continue;
                var argname = pairs[i].substring(0, pos).toLowerCase();
                var value = pairs[i].substring(pos + 1);
                args[argname] = unescape(value);
            }
            args["v"] = (typeof (args["v"]) == 'undefined') ? 0 : args["v"];

            var w = new YeddaWidget(args["v"]);

            for (key in args) {
                switch (key) {
                    case 'actx': w.autoCtx = args[key]; break;
                    case 'ctxu': w.ctxUrl = args[key]; break;
                    case 'ctxt': w.ctxText = args[key]; break;
                    case 'pm': w.previewMode = args[key]; break;
                    case 'ht': w.hrefTarget = args[key]; break;
                    case 'pstags': w.preSeltags = args[key]; break;
                    case 'textLength': w.maxTextLen = args[key]; break;
                    case 'd': w.widgetId = args[key]; break;
                    case 'mt': w.msgTemplate = args[key]; break;
                    case 'mt.ct': w.msgTemplate_captionText = args[key]; break;
                    case 'mt.qht': w.msgTemplate_questionHelpText = args[key]; break;
                    case 'usecustomstyling': w.useCustomStyling = args[key]; break;
                    case 'max': w.maxAnswers = args[key]; break;
                    case 'qid': w.qid = args[key]; break;
                    case 'tags': w.tags = args[key]; break;
                    case 'category': w.category = args[key]; break;
                    case 'elementid': w.elementId = args[key]; break;
                    case 'id': w.anchorId = args[key]; break;
                    case 'sl': w.singleLine = args[key]; break;
                    case 'title': w.widgetTitle = args[key]; break;
                    case 'debug': w.debug = args[key]; break;
                    case 'layout': w.layout = args[key]; break;

                    case 'askBT': w.askButtonTitle = args[key]; break;
                    case 'dqt': w.defaultQuestionText = args[key]; break;
                    case 'topicsTitle': w.topicsTitle = args[key]; break;
                    case 'showLogo': w.showLogo = args[key]; break;
                    case 'stt': w.showTitleText = args[key]; break;
                    case 'sht': w.showHelpText = args[key]; break;
                    case 'bn': w.blogName = args[key]; break;
                    case 'bu': w.blogUrl = args[key]; break;
                    case 'xctxtu': w.exludedCtxUrl = args[key]; break;
                    case 'aa': w.showAnswers = args[key]; break;
                    case 'ea': w.enableAskLink = args[key]; break;
                    case 'mode': w.mode = args[key]; break;
                    case 'ropid': w.ropid = args[key]; break;
                    case 'minAge': w.minAge = args[key]; break;
                    case 'maxAge': w.maxAge = args[key]; break;
                    case 'userId': w.userId = args[key]; break;
                    case 'CIR': w.customImageRootDir = args[key]; break;
                    case 'UIT': w.userIconText = args[key]; break;
                    case 'ABT': w.answerButtonText = args[key]; break;
                    case 'RBT': w.replyButtonText = args[key]; break;
                    case 'X.HC': w.heightControl = args[key]; break;
                    case 'miniGalleryCssPrefix': w.cssPrefix = args[key]; break;
                }
            }

            w.render();
        }
    }
}

