// Global Variables
var apqi_scheme = "http:";
var apqi_hostname = "dev.ads.adproquo.com";
var apqi_path = "ads";
var apqi_publisherid = "1";
var apqi_categoryhint = "0";
var apqi_domain = "www.moxymedia.com";
var apqi_format = "json";
var apqi_maxcount = "5";
var apqi_page = "";
var apqi_src = "";
var apqi_lmsg = "<div style='padding:10px;font-family:Arial, Helvetica, sans-serif;color:#999999;font-size:9pt;'>Loading...</div>";
var apqi_display_lmsg = "yes";
var apqi_debugjs = "no";
var apqi_feedcalled = "no";
var apqi_startat = "1";
var apqi_endat = (typeof apq_maxcount != "undefined" && apq_maxcount ? apq_maxcount : apqi_maxcount);
var apqi_gfeed;
var apqi_ph = 0;
var apqi_kwparam = "keywords";
var apqi_preview = "";
var apqi_els = new Array();

// Element shortcut
function apq_$(x) { return document.getElementById(x); }

// Calls the partner ads feed executes the resulting JSON object
function apq_showAds(start, end, elem) {
    if (apq_checkParams()) {
        if (!start) { //If the optional argument is not there, create a new variable with that name.
            var start = apqi_startat;
        }

        if (!end) { //If the optional argument is not there, create a new variable with that name.
            var end = apqi_endat;
        }
        document.write('<div id="apqads" name="apqads" style="display: block;"><span id="apq_place_' + apqi_ph + '"></span></div>');

        // Add the element to an array	
        apqi_els.push({ el: apq_$("apq_place_" + (apqi_ph)).parentNode, s: (start ? start : 1), e: end });
        apq_showLoadingMsg(apq_$("apq_place_" + (apqi_ph++)).parentNode);

        apq_adFeed();
    }
    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 apq_buildBlock(g, s, e, u) {

    var strB = new Array(); // Equivalent to a string builder in other languages
    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="adslisting ad' + (i + 1) + '">');
            strB.push('<a class="adstitle" href="' + u + ur + '" target="_blank">' + g.items[i].adstitle + '</a>');
            strB.push('<a class="adsdescription" href="' + u + ur + '" target="_blank">' + g.items[i].adsdescription + '</a>');
            strB.push('<a class="adshost" href="' + u + ur + '" target="_blank">' + g.items[i].adshost + '</a>');
            strB.push('</div>');
        }
    } else {
        strB.push('<div id="noresults">There are no results.</div>');
    }
    return strB.join("");
}

function apq_renderAds(start, end) {
    a_debug("Render Ads");
    if (!start) var start = 1;
    if (!end) var end = apqi_maxcount;

    try {
        if (typeof apqi_gfeed != "undefined" && apqi_gfeed != null) {
            u = apq_getUrlAndPath(false);
            for (var i = 0; i < apqi_els.length; i++) {
                a_debug("\nAd Block Start: " + apqi_els[i].s + " End: " + apqi_els[i].e);
                apqi_els[i].el.innerHTML = apq_buildBlock(apqi_gfeed, apqi_els[i].s, apqi_els[i].e, u);
                a_debug(apqi_els[i].el.innerHTML);
            }
        } else {
            // Handle no feed			
            return;
        }
    } catch (err) { }

    return;
}

function apq_adFeed() {
    a_debug("apq_adFeed - apqi_feedcalled: " + apqi_feedcalled);
    if (apqi_feedcalled == 'no') {
        a_debug("apqi_adFeed - calling feed now");
        var headID = document.getElementsByTagName("head")[0];
        var newScript = document.createElement('script');
        newScript.type = 'text/javascript';
        newScript.src = apqi_src;
        if (headID.firstChild) {	// insert at top of head		
            headID.insertBefore(newScript, headID.firstChild);
        } else {
            headID.appendChild(newScript);
        }
        apqi_feedcalled = "yes";
    } else {
        apqi_renderAds();
    }

}

//Checks if the Loading message should be shown and display it before results are returned.
function apq_showLoadingMsg(el) {

    if (typeof apq_display_lmsg != "undefined" && apq_display_lmsg != null) {
        apqi_display_lmsg = apq_display_lmsg;
    }
    if (apqi_display_lmsg == 'yes') {
        if (typeof apq_lmsg != "undefined" && apq_lmsg != null) apqi_lmsg = apq_lmsg;
        el.innerHTML = apqi_lmsg;
    }
}

// Renders the feed from returned JSON object
function jsonAdsFeed(feed) {
    apqi_gfeed = eval(feed);
    if (apqi_gfeed.adscss != '') {
        var headID = document.getElementsByTagName("head")[0];
        var newCss = document.createElement('link');
        newCss.rel = 'stylesheet';
        newCss.type = 'text/css';
        newCss.href = apqi_gfeed.adscss;
        if (headID.firstChild) { // insert at top of head
            headID.insertBefore(newCss, headID.firstChild);
        } else {
            headID.appendChild(newCss);
        }
        a_debug("CSS Link added to Head: " + apqi_gfeed.adscss);
    }
    apq_renderAds();
}


function apq_getUrlAndPath(withpath) {
    var returl = "";
    var cur_scheme = document.location.protocol;
    if (cur_scheme == 'https:')
        apqi_scheme = cur_scheme;

    if (typeof apq_host != "undefined" && apq_host != null) apqi_hostname = apq_host;

    if (typeof apq_path != "undefined" && apq_path != null) apqi_path = apq_path;

    returl = apqi_scheme + '//';
    returl += apqi_hostname;
    if (withpath) returl += '/' + apqi_path;
    return returl;

}

// 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]] = tmparr2[1];
        }
    }
    return url_params;
}


var add_params = "";
var necessary_keys = new Array("keywords", "referrer", "keyword", "camp", "group", "creativeid", "traffictype");
function apq_checkParams() {
    if (apqi_feedcalled == "no") {
        var url_params = getLocationParams();
        var url_params2 = new Array();

        if (typeof apq_kwparam != "undefined" && apq_kwparam != null) apqi_kwparam = apq_kwparam;
        try {

            url_params2.push('format=' + apqi_format);
            if (typeof apq_publisherid != "undefined" && apq_publisherid != null) apqi_publisherid = apq_publisherid;
            if (typeof apq_categoryhint != "undefinded" && apq_categoryhint != null) apqi_categoryhint = apq_categoryhint;
            if (typeof apq_startat != "undefined" && apq_startat != null) apqi_startat = apq_startat;
            if (typeof apq_endat != "undefined" && apq_endat != null) apqi_endat = apq_endat;
            if (typeof apq_maxcount != "undefined" && apq_maxcount != null) apqi_maxcount = apq_maxcount;
            if (typeof apq_preview != "undefined" && apq_preview != null) apqi_preview = apq_preview;
            
            url_params2.push('publisherid=' + apqi_publisherid);
            url_params2.push('categoryhint=' + apqi_categoryhint);
            url_params2.push('maxcount=' + apqi_maxcount);
            if (apqi_preview != null && apqi_preview != "") url_params2.push('preview=' + apqi_preview);
            if (typeof apq_css != "undefined" && apq_css != null) url_params2.push('css=' + encodeURIComponent(apq_css));
            if (url_params["serveUrl"] != undefined)
            { 
                cur_url = url_params["serveUrl"];
            }
            else if (typeof apq_domain != "undefined" && apq_domain != null)
            {
                 apqi_domain = apq_domain;
                 cur_url = apqi_domain;
            }
            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 (url_params2.length != undefined && url_params2.length > 0) add_params = url_params2.join("&");
            if (add_params != "") {
                apqi_src = apq_getUrlAndPath(true) + '/';
                apqi_src += apqi_page + '?';
                apqi_src += add_params;
                a_debug('Debug feed url: \n' + apqi_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 (apqi_debugjs == 'yes') {
    document.write('<form id="apq_jsdebug"><textarea id="adproquoout" rows="10" cols="100"></textarea></form>');
    var f = document.forms["apq_jsdebug"];
}

function a_debug(str) {
    if (apqi_debugjs == 'yes') f.elements["adproquoout"].value += str + "\n";
}


// Call function to show Ads
apq_showAds();

