// Global Variables
var affil_scheme = "http:";
var affil_hostname = "www.foundry42.com";
var affil_path = "partnertest";
var affil_format = "json";
var affil_maxcount = "5";
var affil_page = "";
var affil_src = "";
var affil_lmsg = "<div style='padding:10px;font-family:Arial, Helvetica, sans-serif;color:#999999;font-size:9pt;'>Loading...</div>";
var affil_display_lmsg = "yes";
var affil_debugjs = "no";
var affil_feedcalled = "no";
var affil_startat = "1";
var affil_endat = (typeof f42_maxcount != "undefined" && f42_maxcount ? f42_maxcount : affil_maxcount);
var affil_gfeed;
var affil_ph = 0;
var affil_ft = "";
var affil_ssc = "1";
var affil_cspm = "0";
var affil_kwparam = "keywords";
var affil_atextparam = "atext";
var affil_els = new Array();
var affil_nwd = f42GetCookie('NWD');


// Element shortcut
function f42_$(x) { return document.getElementById(x); }

// Calls the partner ppc feed executes the resulting JSON object
function f42_showAds(start, end, elem) {

    if (f42_checkParams()) {
        if (!start) { //If the optional argument is not there, create a new variable with that name.
            var start = affil_startat;
        }

        if (!end) { //If the optional argument is not there, create a new variable with that name.
            var end = affil_endat;
        }

        document.write('<div id="ppc" name="ppc" style="display: block;" class="ppcsl-' + f42_ft_loc + '">' + '<span id="f42_place_' + affil_ph + '"></span></div>');

        // Add the element to an array	
        affil_els.push({ el: f42_$("f42_place_" + (affil_ph)).parentNode, s: (start ? start : 1), e: end });
        f42_showLoadingMsg(f42_$("f42_place_" + (affil_ph++)).parentNode);
        f42_callFeed();
    }
    return false;
}

// Builds a string given the start and end indices for element
// @param g The feed element
// @param s The start index
// @param e The end index
// @param u The url protocol
function f42_buildBlock(g, s, e, u) {
	
    var strB = new Array(); // Equivalent to a string builder in other languages
    if (g.ppcsl && g.ppcsl != "") {
        if (g.ppcsltext && g.ppcsltext == "false") {
            strB.push('<div id="ppcsl"><div id="wt">[<a href="javascript:affilwtpopup();">what&acute;s this?</a>]</div></div>');
        } else {
            strB.push('<div id="ppcsl">' +
            			'<div id="ppctext">' + f42_ft_text /*g.ppcsl*/ + 
            			((f42_display_kw=='yes') ? ' for <span class="kw">' + g.ppckeywords + '</span>' : '') + 
            			'</div>' +
            			((f42_display_wt=='yes') ? '<div id="wt">[<a href="javascript:affilwtpopup();">what&acute;s this?</a>]</div>' : '') +
            		'</div>');
        }
    }
    if (g.items.length > 0) {
        for (var i = s - 1; i < g.items.length && i < e; i++) {
            var ur = g.items[i].clickurl;
            if (ur.substring(4, 0) == 'http') { u = ''; }
            strB.push('<div class="ppclisting ad' + (i + 1) + '">');
            strB.push('<a class="ppctitle" href="' + u + ur + '" target="_blank">' + g.items[i].ppctitle + '</a>');
            strB.push('<a class="ppcdescription" href="' + u + ur + '" target="_blank">' + g.items[i].ppcdescription + '</a>');
            strB.push('<a class="ppchost" href="' + u + ur + '" target="_blank">' + g.items[i].ppchost + '</a>');
            strB.push('</div>');
        }
    } else {
        strB.push('<div id="noresults">There are no results for ' + g.ppckeywords + '.</div>');
    }
    return strB.join("");
}

function f42_renderAds(start, end) {
    a_debug("Render Ads");
    if (!start) var start = 1;
    if (!end) var end = affil_maxcount;

    try {
        if (typeof affil_gfeed != "undefined" && affil_gfeed != null) {
            u = f42_getUrlAndPath(false);
            for (var i = 0; i < affil_els.length; i++) {
                a_debug("\nAd Block Start: " + affil_els[i].s + " End: " + affil_els[i].e);
                affil_els[i].el.innerHTML = f42_buildBlock(affil_gfeed, affil_els[i].s, affil_els[i].e, u);
                a_debug(affil_els[i].el.innerHTML);
            }
        } else {
            // Handle no feed			
            return;
        }
    } catch (err) { }

    return;
}

function f42_callFeed() {
    a_debug("f42_callFeed - affil_feedcalled: " + affil_feedcalled);
    if (affil_feedcalled == 'no') {
        a_debug("f42_callFeed - calling feed now");
        var headID = document.getElementsByTagName("head")[0];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.src = affil_src;
        headID.appendChild(newScript);
        affil_feedcalled = "yes";
    } else {
        f42_renderAds();
    }

}

//Checks if the Loading message should be shown and display it before results are returned.
function f42_showLoadingMsg(el) {

    if (typeof f42_display_lmsg != "undefined" && f42_display_lmsg != null) {
        affil_display_lmsg = f42_display_lmsg;
    }
    if (affil_display_lmsg == 'yes') {
        if (typeof f42_lmsg != "undefined" && f42_lmsg != null) affil_lmsg = f42_lmsg;
        el.innerHTML = affil_lmsg;
    }
}
// Renders the feed from returned JSON object
function jsonPPCFeed(feed) {
    affil_gfeed = eval(feed);
    var headID = document.getElementsByTagName("head")[0];
    if (affil_gfeed.ppccss != '') {
        var newCss = document.createElement('link');
        newCss.rel = 'stylesheet';
        newCss.type = 'text/css';
        newCss.href = affil_gfeed.ppccss;
        headID.appendChild(newCss);
        a_debug("CSS Link added to Head: " + affil_gfeed.ppccss);
    }
    f42_renderAds();
    if ((affil_nwd == "undefined" || affil_nwd == null) && affil_gfeed.ppcses != '') {
        var nwdScr1 = document.createElement('script');
        nwdScr1.type = 'text/javascript';
        nwdScr1.text = 'var nwd_sesid = "' + affil_gfeed.ppcses + '"';
        headID.appendChild(nwdScr1);

        var nwdScr2 = document.createElement('script');
        nwdScr2.type = 'text/javascript';
        var nwdurl = affil_scheme + '//counter.surfcounters.com/nwdlib.js';
        nwdScr2.src = nwdurl;
        headID.appendChild(nwdScr2);
        a_debug("NWD added to head with ses: " + nwdScr1.text);
    }

}

function f42_getUrlAndPath(withpath) {
    var returl = "";
    var cur_scheme = document.location.protocol;
    if (cur_scheme == 'https:')
        affil_scheme = cur_scheme;

    if (typeof f42_host != "undefined" && f42_host != null) affil_hostname = f42_host;

    if (typeof f42_path != "undefined" && f42_path != null) affil_path = f42_path;

    returl = affil_scheme + '//';
    returl += affil_hostname;
    if (withpath) returl += '/' + affil_path;
    return returl;

}

function affilwtpopup() {
    wtpopupwin = window.open('http://media.foundry42.com/partner/inc/wt.html', 'wtpopup', 'toolbar=0,scrollbars=0,location=0,statusbar=0,menubar=0,resizable=0,width=400,height=250');
}

// getLocationParams returns an array of QS params
var cur_url = window.location.href;
function getLocationParams() {
    var url_params = new Object;
    var search_params = "";
    if (cur_url.indexOf('?') > 0) var search_params = cur_url.substr(cur_url.indexOf('?') + 1);
    if (search_params != "") {
        if (search_params.indexOf('&') > 0) var tmparr = search_params.split("&");
        else var tmparr = new Array(search_params);
        for (var i = 0; i < tmparr.length; i++) {
            var tmparr2 = tmparr[i].split("=");
            url_params[tmparr2[0].toLowerCase()] = tmparr2[1];
        }
    }
    return url_params;
}


function isLander() {
    var is_lander = false;
    if (cur_url.indexOf('referrer=') > 0 || cur_url.indexOf('keywords=') > 0 || cur_url.indexOf(affil_kwparam + '=') > 0) {
        is_lander = true;
    }
    return is_lander;
}


var add_params = "";
var necessary_keys = new Array("keywords", "referrer", "keyword", "camp", "group", "creativeid", "traffictype", "atext");
function f42_checkParams() {
    if (affil_feedcalled == "no") {
        var url_params = getLocationParams();
        var url_params2 = new Array();
        if (typeof f42_kwparam != "undefined" && f42_kwparam != null) affil_kwparam = f42_kwparam;
        if (typeof f42_atextparam != "undefined" && f42_atextparam != null) affil_atextparam = f42_atextparam;
        try {
            for (var i = 0; i < necessary_keys.length; i++) {
                a_debug('Parameter ' + necessary_keys[i] + ' = ' + url_params[necessary_keys[i]]);
                if (necessary_keys[i] == "keywords") {
                    a_debug('kwparam ' + affil_kwparam + ' = ' + url_params[affil_kwparam]);
                    if (url_params[affil_kwparam] != undefined)
                        url_params2.push(necessary_keys[i] + '=' + url_params[affil_kwparam]);
                    else {
                        if (f42_defaultkeywords == '') return false;
                        url_params2.push(necessary_keys[i] + '=' + encodeURIComponent(f42_defaultkeywords));
                    }
                } else if (necessary_keys[i] == "atext") {
                    if (url_params[affil_atextparam] != undefined)
                        url_params2.push(necessary_keys[i] + '=' + url_params[affil_atextparam]);
                } else {
                    if (url_params[necessary_keys[i]] != undefined) url_params2.push(necessary_keys[i] + '=' + url_params[necessary_keys[i]]);
                }
            }
            url_params2.push('format=' + affil_format);
            if (typeof f42_startat != "undefined" && f42_startat != null) affil_startat = f42_startat;
            if (typeof f42_endat != "undefined" && f42_endat != null) affil_endat = f42_endat;
            if (typeof f42_maxcount != "undefined" && f42_maxcount != null) affil_maxcount = f42_maxcount;
            if (typeof f42_cspm != "undefined" && f42_cspm != null) affil_cspm = f42_cspm;
            url_params2.push('maxcount=' + affil_maxcount);
            if (isLander()) {
                affil_ft = "PM";
                affil_ssc = "0";
            }
            if (affil_cspm == "1") affil_ft = "PM";
            a_debug('\naffil_ft: ' + affil_ft);
            a_debug('affil_ssc: ' + affil_ssc + '\n');
            if (typeof affil_ft != "undefined" && affil_ft != null && affil_ft != "") url_params2.push('feed=' + affil_ft);
            url_params2.push('ssc=' + affil_ssc);
            if (typeof f42_css != "undefined" && f42_css != null) url_params2.push('css=' + encodeURIComponent(f42_css));
            if (affil_nwd != "undefined" && affil_nwd != null) url_params2.push('nwd=' + affil_nwd);
            if (url_params["serveUrl"] != undefined) cur_url = url_params["serveUrl"];
            var serve_url = cur_url;
            if (cur_url.indexOf('?') > 0) serve_url = cur_url.substr(0, cur_url.indexOf('?'));
            url_params2.push('serveUrl=' + encodeURIComponent(serve_url));
           
            if(document && document.referrer) url_params2.push('userreferrer=' + encodeURIComponent(document.referrer));
            
            if (url_params2.length != undefined && url_params2.length > 0) add_params = url_params2.join("&");
            if (add_params != "") {
                affil_src = f42_getUrlAndPath(true) + '/';
                affil_src += affil_page + '?';
                affil_src += add_params;
                a_debug('Debug feed url: \n' + affil_src + '\n');
            }
        } catch (e) { return false; }
    } // end if havefeed = no
    return true;
}

function ctWinOpen(url) {
    var url = url;
    window.open(url);
}

// If JS Debug
if (affil_debugjs == 'yes') {
    document.write('<form id="f42_jsdebug"><textarea id="f42out" rows="10" cols="100"></textarea></form>');
    var f = document.forms["f42_jsdebug"];
}

function a_debug(str) {
    if (affil_debugjs == 'yes') f.elements["f42out"].value += str + "\n";
}

// Cookie libs
function f42GetCookie(name) {
    var start = document.cookie.indexOf(name + "=");
    var len = start + name.length + 1;
    if ((!start) && (name != document.cookie.substring(0, name.length))) {
        return null;
    }
    if (start == -1) return null;
    var end = document.cookie.indexOf(";", len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len, end));
}

function f42SetCookie(name, value, expires, path, domain, secure) {
    var today = new Date();
    today.setTime(today.getTime());
    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));
    document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");
}

function f42DeleteCookie(name, path, domain) {
    if (f42GetCookie(name)) document.cookie = name + "=" +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Call function to show Ads
f42_showAds();

