var floatParams = new Object;
floatParams.elementId = 'dontfollowlink';
floatParams.padding = 10;
floatParams.bottomElementId = 'riverBottom';

function fixedPanelFix() {
    Event.observe(window, 'load', function() {
        var el = document.getElementById('float_nofollow');
        if(el) {
            if((typeof noFloat!="undefined") && noFloat) {
                el.style.display='none';
            }
            else {
                el.style.display='inline';
                Event.observe(window, 'scroll', makeWidgetSticky.bind(floatParams));
            }
        }
    });
}

var SUGAR = SUGAR || {};

SUGAR.dispatcher = [];

SUGAR.ads = function () {
    var ord = Math.floor(Math.random() * 92599);
    var tile = 1;
    var maxSponsors = 6;
    var sponsorIds = [];
    var sponsorsRendered = false;
    var tjmaxxLocatorVisible = false;
    var queue = {};
    var queue_count = 0;
    var adRotationInterval = null;

    var rotateIndividualAd = function(ad, replacements) {
        var src = ad.src;

        // ord will always be replaced
        src = src.replace(/ord=\d+/, 'ord=' + replacements['rand']);

        ad.src = src;
    };

    var makeSponsor = function(link, text, imageUrl) {
        var image = "<span class=\"sponsor-image\" style=\"background-image: url(" + imageUrl + ")\"></span>";
        var text = "<span class=\"sponsor-text\">" + text + "</span>";
        var link = "<a href=\"" + link + "\" target=\"_blank\" class=\"sponsor-link\">" + image + text + "</a>";
        var container = "<div class=\"sponsor-container\">" + link + "</div>";

        return container;
    };

    return {
        startTimedAdRotation: function(elements, time) {
            adRotationInterval = setInterval(function() {
                SUGAR.ads.rotatePageAds(elements);
            }, time * 1000)
        },
        stopTimedAdRotation: function() {
            clearInterval(adRotationInterval);
        },
        rotatePageAds: function(elements, replacements) {
            if (replacements == undefined) {
                replacements = {};
            }

            var rand = Math.floor(Math.random() * 99999999999);
            replacements['rand'] = rand;

            for (var key in elements) {
                if (elements.hasOwnProperty(key)) {
                    rotateIndividualAd(elements[key], replacements);
                }
            }
        },
        fetchGeoAdvertorial: function(channel, dma, state, country) {
            var url = '/sugar-ads/geo-advertorial-ajax/?channel=' + channel + '&dma=' + dma + '&state=' + state + '&country=' + country + '&fastcache=1';
            new Ajax.Updater('geo-adv-container', url, {});
        },
        getAdUrl: function(queryString, isIframe) {
            var url = "http://ad.doubleclick.net/" + (isIframe ? "adi" : "adj") + "/sugar." + queryString + ";tile=" + tile +
                     ((document.cookie.indexOf('sugarTestGroup=turbo;') >= 0) ? ';turbo=true': '') +
                     ";ord=" + ord + ";";

            tile++;
            return url;
        },
        getAdIFrame: function(url, width, height) {
            return '<ifr' + 'ame src="' + url +'" width="' + width + '" height="' + height + '" class="ad-frame" marginwidth="0" marginheight="0" hspace="0" vspace="0" frameborder="0" scrolling="no" bordercolor="#000000"><\/ifr' + 'ame>';
        },
        displayAd: function(queryString, isIframe, width, height, async) {
            var url = SUGAR.ads.getAdUrl(queryString, isIframe);
            var output = '';

            if (!async) {
                if (isIframe) {
                    output += SUGAR.ads.getAdIFrame(url, width, height);
                } else {
                    output += '<scr' + 'ipt language="javascript" type="text/javascript" src="' + url + '"><\/scr' + 'ipt>';
                }
            }
            else {
                var id = 'sugar-async-ad-' + queue_count++;
                output += '<div width="' + width + '" height="' + height + '" id="' + id + '"></div>';
                queue[id] = SUGAR.ads.getAdIFrame(url, width, height);
            }

            document.write(output);
        },
        queueSponsor: function(sponsorId) {
            // if we've already rendered sponsors on this page, ignore calls to queue additional sponsors
            if (!sponsorsRendered) {
                sponsorIds.push(sponsorId);

                if (sponsorIds.length == 1) {
                    // if this is the first sponsor we're queueing, start the timer for the rendering call. we will wait
                    // up to 1.5 seconds for additional sponsors to be queued before we render them all
                    setTimeout(function() {
                        SUGAR.dispatcher.push(['SUGAR.ads.renderSponsors']);
                    }, 1500);
                } else if (sponsorIds.length == maxSponsors) {
                    // all sponsors have been queued, so go ahead and render them
                    SUGAR.dispatcher.push(['SUGAR.ads.renderSponsors']);
                }
            }
        },
        renderSponsors: function() {
            if (!sponsorsRendered) {
                sponsorsRendered = true;

                $.ajax({
                    'url': '/sponsor/get_sponsor_links_ajax',
                    'data': {sponsorIds: JSON.stringify(sponsorIds)},
                    'success': function(data) {
                        var response = $.parseJSON(data);

                        if(response.length > 0) {
                            $('#sponsored-links-container').removeClass('hide');

                            for (var i = 0; i < response.length; i++) {
                                $('#sponsored-links').append(makeSponsor(response[i].link, response[i].text, response[i].imageUrl));
                            }
                        }
                    }
                });
            }
        },
        tjmaxxLocator: function(show) {
        },
        showTagPageSponsorLogo: function(divId, adParams) {
        },
        processQueue: function() {
            for (id in queue) {
                document.getElementById(id).innerHTML = queue[id];
            }
        }
    }
}();

SUGAR.ads.skins = function() {
    var millisBetweenAttempts = 500;
    var maxAttempts = 50;
    var attempts = 0;
    var _skinId;
    var _transparent = false;
    var clickHandler;

    var setSkin = function(skinId, transparent) {
        // remove existing skin class, if any
        if (_skinId) {
            $(document.body).removeClass(_skinId);
        }

        // add new skin class
        $(document.body).addClass(skinId);

        // record skinId for later reference
        _skinId = skinId;

        // set the marquee transparency state for the new skin
        if (_transparent && !transparent) {
            // if the last skin was transparent and the new one isn't, remove the transparency class
            $('body').removeClass('transparent-marquee');
            _transparent = false;
        }
        else if (transparent && !_transparent) {
            // if the new skin is transparent and the old skin wasn't, add the transparency class
            $('body').addClass('transparent-marquee');
            _transparent = true;
        }
    };

    var setImpressionPixel = function(impUrl) {
        var e = '';

        if (impUrl) {
            e = '<img src="' + impUrl + '" border="0" width="1" height="1" />';
        }

        document.getElementById('sugar-skin-tracker').innerHTML = e;
    };

    var setClickThru = function(clickUrl) {
        // remove any existing click handler from background
        if (clickHandler) {
            $(document.body).off('click', clickHandler);
        }

        clickHandler = function(e) {
            var t = e.target;
            if (t == this) {
                window.open(clickUrl);
            }
        };

        $(document.body).on('click', clickHandler);
    };

    return {
        setSkin: function(skinId, impUrl, clickUrl, transparent) {
            if (document.body && document.getElementById('sugar-skin-tracker')) {
                // all the dom elements we need have loaded, so we can get to work
                setSkin(skinId, transparent);
                setImpressionPixel(impUrl);
                setClickThru(clickUrl);
            } else {
                // the dom isn't ready for us, so try again in a few millis
                attempts++;

                if (attempts < maxAttempts) {
                    setTimeout(
                        function() {
                            SUGAR.ads.skins.setSkin(skinId, impUrl, clickUrl, transparent);
                        },
                        millisBetweenAttempts
                    );
                }
            }
        }
    }
}();

/* TODO move this code out of sugar-ads */
SUGAR.Timer = SUGAR.Timer || function () {
    var REPORT_EVERY = 100;
    var domLoaded = 0;
    var windowLoaded = 0;
    var myId = null;
    var doReport = false;
    var randomId = 0;

    var timems = function() { return (new Date()).getTime(); }
    var charsum = function(string) {
        var sum = 0;
        for (var i=0; i < string.length; i++) {
            sum += string.charCodeAt(i);
        }
        return sum;
    }

    return {
        startTime: (new Date()).getTime(),
        pageType: null,
        start: function() {
            myId = ONSUGAR.Util.getCookie('PHPSESSID');
            randomId = Math.floor(Math.random() * 999999);

            var randomKey = Math.floor(Math.random() * 999999);
            doReport = (window.self == window.top) && (randomKey % REPORT_EVERY == 0);

            SUGAR.Timer.report({
                'i': myId,
                'e': 'start',
                'p': this.pageType,
                't': 0,
                'r': randomId
            }, false);
        },
        domLoaded: function () {
            domLoaded = timems() - SUGAR.Timer.startTime;

            SUGAR.Timer.report({
                'i': myId,
                'e': 'domloaded',
                'p': this.pageType,
                't': domLoaded,
                'r': randomId
            }, true);
        },
        windowLoaded: function() {
            windowLoaded = timems() - SUGAR.Timer.startTime;

            SUGAR.Timer.report({
                'i': myId,
                'e': 'loaded',
                'p': this.pageType,
                't': windowLoaded,
                'r': randomId
            }, true);
        },
        report: function(params, append) {
            if (!doReport || params.t == null) {
                return;
            }
            var url = '/docload.php?' + ONSUGAR.Util.buildQueryString(params);

            if (append) {
                var newimage = document.createElement('img');
                newimage.src = url;
                newimage.style.position = 'absolute';
                document.body.appendChild(newimage);
            }
            else {
                var img = '<img src="' + url + '" width="0" height="0" style="position: absolute;" />';
                document.write(img);
            }
        }
    };
}();


/**
 * pass-through for existing skin creatives in dfp.
 *
 * @deprecated see SUGAR.ads.skins.setSkin()
 */
function sugarAdsLoadSkin(skinId, impUrl, clickUrl, transparent) {
    SUGAR.dispatcher.push(['SUGAR.ads.skins.setSkin', skinId, impUrl, clickUrl, transparent]);
}

/* BEGIN: Required functions for Doubleclick PushDownAds */
function pushDownOpen(divId, animDuration, expandedHeight, collapsedHeight) {
    setDivHeight(divId, expandedHeight);
}

function pushDownClose(divId, animDuration, expandedHeight, collapsedHeight) {
    setTimeout(function() {
        setDivHeight(divId, collapsedHeight);
    }, animDuration*1200);
}

function setDivHeight(divId, expandedHeight) {
    var el = document.getElementById(divId);
    if (el) {
        el.style.height = expandedHeight + 'px';
    }
}
/* End: Required functions for Doubleclick PushDownAds */

var galleryCarousel = {};
galleryCarousel.enableInterstitials = function() {
    SUGAR.dispatcher.push(['SUGAR.Gallery.enableInterstitials']);
};

