var hiddenAds = new Array();
var ordHolder = "";
var sub = "";
var firstAd = true;

function writeAdTag(adW, adH, dartURL) {
    if (firstAd) {
        refreshAdInfo();
        firstAd = false;
    }
    var login = "n";
    try {
        if ( wwd.user.isLoggedIn() ) { login = "y"; }
    } catch (err) { }
    login = "login=" + login + ";";
    var sublink = "sub=" + sub + ";";
    var ord = "ord="+ ordHolder + "?";
    var iframe = '<iframe class="refreshable" allowtransparency="true" scrolling="no" width="' + adW + '" height="' + adH + '" frameborder="0" src="/ad-iframer/?adinfo=' + encodeURIComponent(dartURL + login + sublink + quantSegs + ord) + '"></iframe>';
    if(adW=='86' && adH=="15"){
        wwd.content.currentToolboxAd = iframe;
    }
    document.write(iframe);
}

function refreshAdInfo() {
    var tileCount = 0;
    ordHolder = parseInt(Math.random()*10000000000000000);
    sub = "free";
    if ( wwd && wwd.user ) {
        sub = wwd.user.getSubscriptionLevel();
    }
    sub = sub == "free" ? "" : sub;
}

function renderSlideshowAd(section, s2) {
    refreshAdInfo();
    var url = $("#wwd-url").html();
    var curOrd = ordHolder;
    var login = "n";
    if ( wwd.user.isLoggedIn() ) {
        login = "y";
    }
    var eyePath = document.location.pathname;
    var kw = $("#wwd-kw").html();
    var adinfoInter = "";
    var adinfo = "";

    //change DartSite to wwd.eye.fc if within Eye
    if (eyePath.indexOf("eye")!=-1) {
        //for interstitial ad
        if ($("#slideshow-ad-content").html().length == 0) {
            adinfoInter = 'wwd.eye.fc/slideshow/;s1=slideshow;s2=' + s2 + ';' + url + 'login=' + login + ';' + kw + 'fc=ad;pos=middle;tile=1;sz=300x250;ptype=slideshow;sub=archive;qcseg=D;qcseg=T;';
        }
        //for rich-media ad iframe on lower right side
        if ($("#slideshow-ad").html().length == 0) {
            adinfo = 'wwd.eye.fc/slideshow/;s1=slideshow;s2=' + s2 + ';' + url + 'login=' + login + ';' + kw + 'fc=ad;pos=right;tile=1;sz=300x250,300x600;ptype=slideshow;sub=archive;qcseg=D;qcseg=T;';
        }
    }
    else {
        //for interstitial ad
        if ($("#slideshow-ad-content").html().length == 0) {
            adinfoInter = 'wwd.fc/slideshow/;s1=slideshow;s2=' + s2 + ';' + url + 'login=' + login + ';' + kw + 'fc=ad;pos=middle;tile=1;sz=300x250;ptype=slideshow;sub=archive;qcseg=D;qcseg=T;';
        }
        /* else {                   (*implied*)
            adinfoInter = '';
        }*/
        //for rich-media ad iframe on lower right side
        if ($("#slideshow-ad").html().length == 0) {
            adinfo = 'wwd.fc/slideshow/;s1=slideshow;s2=' + s2 + ';' + url + 'login=' + login + ';' + kw + 'fc=ad;pos=right;tile=1;sz=300x250,300x600;ptype=slideshow;sub=archive;qcseg=D;qcseg=T;';
        }
    }
    callIframeInter("/ad-iframer/?adinfo=" + encodeURIComponent(adinfoInter));
    callIframe("/ad-iframer/?adinfo=" + encodeURIComponent(adinfo));
    return true;
}

function callIframeInter(url) {
    $("#slideshow-ad").html('<p>Advertisement</p><iframe id="static-ad-inter" class="refreshable" allowtransparency="true" scrolling="no" width="300" height="250" frameborder="0"></iframe>');
    $('iframe#static-ad-inter').attr('src', url);
}

function callIframe(url) {
    $("#slideshow-ad-content").html('<p>Advertisement</p><iframe id="static-ad" class="refreshable" allowtransparency="true" scrolling="no" width="300" height="600" frameborder="0"></iframe>');
    $('iframe#static-ad').attr('src', url);
}

function writeHiddenAd(hidden, tileNum, hiddenAdSrc, dartURL) {
    var login = "n";
    try {
        if ( wwd.user.isLoggedIn() ) { login = "y"; }
    } catch (err) { }
    var hiddenAd = {};
    hiddenAd.link = document.getElementById(hidden + 'HiddenAdLink' + tileNum);
    hiddenAd.img = document.getElementById(hidden + 'HiddenAdImg' + tileNum);
    hiddenAd.base = 'http://ad.doubleclick.net';
    hiddenAd.params = (dartURL + "login=" + login + ";");
    hiddenAd.href = '/jump/';
    hiddenAd.src = hiddenAdSrc;
    addHiddenAd(hidden, hiddenAd);
}

function addHiddenAd(type, ad) {
    var ads = hiddenAds[type];
    if (ads == null) {
        ads = new Array();
    }
    ads.push(ad);
    hiddenAds[type] = ads;
}

/**
 * showHiddenAds
 *
 * on page load, each 'hidden' ad registers an object with its important @see addHiddenAd()
 * information in a global variable.
 * this function runs through each of those ads, by 'type' and assigns the
 * src and href properties to the <img> and <a> respectively, essentially turning the ad on
 *
 * @param type - string representing a group name for a hidden ad
 * @param overrides - an object containing any name/value pairs that need
 *                    to replace any existing query string params
 *
 */
function showHiddenAds( type, overrides )
{
    var ads = hiddenAds[type];
    if ( !ads || ads.length == 0 ) {
        return;
    }

    /*
     * lil' inner function to quickly swap out/add name value params to the query string
     */
    var replaceParam = function( query, name, value ) {
        var found = false;
        if ( query.lastIndexOf( ";" ) == query.length - 1 ) {
            query = query.substr( 0,query.length-1 );
        }
        splits = query.split(";");
        for ( var i=0;i<splits.length;i++ ) {
            if ( splits[i].indexOf("=") > -1 && name == splits[i].substr(0,splits[i].indexOf("=") ) ) {
                splits[i] = name + "=" + value;
                found = true;
            }
        }
        unsplit = "" + splits;
        unsplit = unsplit.replace( /,/g , ";" );
        if ( !found ) {
            unsplit += ";"+name+"="+value;
        }
        return unsplit;
    }

    //    try {
        for ( var i=0;i<ads.length;i++ ) {
            for ( var o in overrides ) {
                ads[i].params = replaceParam( ads[i].params, o, overrides[o] );
            }
            ads[i].img.src = ads[i].base + ads[i].src + ads[i].params + "sub=" + sub + ";ord=" + ordHolder + "?";
            ads[i].link.href = ads[i].base + ads[i].href + ads[i].params + "sub=" + sub + ";ord=" + ordHolder + "?";
        }
        //    } catch(e) {
        //        // ad's info wasnt properly set?
        //    }
}


var popupAdFunctions = new Array();

function setPopupAdFunction(name, func) {
  popupAdFunctions[name] = func;
}

function getPopupAdFunction(name) {
    return popupAdFunctions[name];
}

function adReload(iframe)
{
    var curSrc = iframe.src;
    var re = new RegExp('ord%3D\\d+', 'g');
    var re2 = new RegExp('ord\\=\\d+', 'g');
    if (curSrc.match(re)) {
        //change the ord value to new value
        iframe.src = curSrc.replace(re, encodeURIComponent('ord=' + ordHolder));
        //set s2 value to 'news' for article pages loaded thru AJAX
        if (wwd.pageType == "article" || wwd.pageType == "roadblock") {
            iframe.src = iframe.src.replace('s2%3Dlanding', "s2%3Dnews");
            iframe.src = iframe.src.replace('%2Flanding', "%2Fnews");
        }
    } else {
        if (curSrc.match(re2)) {
            //change the ord value to new value
            iframe.src = curSrc.replace(re, 'ord=' + ordHolder);
        } else {
            //no match - refresh current url
            iframe.src = curSrc;
        }
    }
}

function adReloadAll()
{
    refreshAdInfo();
    $('iframe.refreshable').each(function(index) {
        adReload(this);
    });
}

function getIFrameDocument(iframe)
{
  var doc = (iframe.contentDocument // For NS6
      || iframe.contentWindow.document // For IE5.5 and IE6
      || iframe.document); // For IE5 et al
  return doc;
}

function adAutoResizeHeight(id){
    var iframe = document.getElementById(id);
    var iframeDocument = getIFrameDocument(iframe);
    var newheight = 0;
    try {
        newheight = iframeDocument.getElementById('bottom_div').offsetTop;
    }
    catch(e){ }
    iframe.height = (newheight) + "px";
}
