// Copyright 2003-2010 Emergent Discovery LLC  All rights reserved.

/* PROMOTE.PY: STAND-ALONE */

/* Emergent Discovery Taste Probe 
    Load this script as:
        <script type="text/javascript" src="http://www.emergentdiscovery.com/static/live/emergentdiscovery/js/adserver/ed/probe.js" />
    The script passes the window top URL to the probe view.
*/
function EDPROBE_logMsg(message) {
    // Log messages to the console so we can see errors in browsers that support the console.
    try {
        if (navigator.userAgent.match(/safari/i)) {
            console.log(message);
        }
    } catch(err) {}
}

function EDPROBE_location() {
    // Detect the location data from the page.
    var location = {};
    try {
    	var hostpage = '';
    	var host     = '';
        var hostname = '';
        var pathname = '';
        var search   = '';
        try {
            var loc = window.top.location;
            hostpage = loc.toString();
            host = loc.host.toString();
            hostname = loc.hostname.toString();
            pathname = loc.pathname.toString();
            search = loc.search.toString();
        } catch (locErr) {
            hostpage = document.referrer;
            var parts = hostpage.split('//');
            host = parts[1].split('/', 1)[0];
            hostname = host.split(':')[0];
            parts = parts[1].substr(host.length).split('?');
            pathname = parts[0];
            search = parts.length > 1 ? parts[1] : null;
        }
        
        location = {
        		     hostpage: hostpage,
        		     host    : host,
                     hostname: hostname,
                     pathname: pathname,
                     search:   search
                   };
    } catch (err) {
        EDPROBE_logMsg("EDPROBE: Error finding location: " + err);
    }
    return location;
}

EDPROBE_mungeParamList = function (list) {
    // remove commas and slashes so that they don't interfere with the URL
    var re = /[,|\/]/g;
    var newList = [];
    var l = list.length;
    for (var i = 0; i < l; ++i) {
        var s = list[i];
        var newS = s.replace(re, '');
        newList.push(newS);
    }
    return newList;
};

function EDPROBE_loadProbe(location) {
	// Eliminate hosts that we don't want to deal with for now.
	if (location['hostname'].match('(blip.fm|partners.popmatters.com)')) {
		return;
	}
	// Gate - only allow a percentage of calls
	if (Math.random() > 1.5) {
		// EDPROBE_logMsg("Excluded by gate.");
		return;
	}
    var genres = typeof(EDPROBE_GENRES) == 'undefined' ? [] : typeof(EDPROBE_GENRES) == 'string' ? [EDPROBE_GENRES] : EDPROBE_GENRES;
    var artists = typeof(EDPROBE_ARTISTS) == 'undefined' ? [] : typeof(EDPROBE_ARTISTS) == 'string' ? [EDPROBE_ARTISTS] : EDPROBE_ARTISTS;
    var partnerID = typeof(EDPROBE_PARTNERID) != 'undefined' ? EDPROBE_PARTNERID : null;
    var userID = typeof(EDPROBE_USERID) != 'undefined' ? EDPROBE_USERID : null;

    var noAdAction = typeof(EDPROBE_NOADACTION) != 'undefined' ? EDPROBE_NOADACTION : (partnerID == '10' ? 'songzanoad' : 'defaultads');

    var addDivID = typeof(EDPROBE_ADDIV_ID) != 'undefined' ? EDPROBE_ADDIV_ID : null;
    var debugTargeting = typeof(EDPROBE_DEBUG_TARGETING) != 'undefined' ? EDPROBE_DEBUG_TARGETING : false;
    var cookieEnabled=(navigator.cookieEnabled)? true : false;
    
    var isProbe = (typeof(EDPROBE_PROBE) != 'undefined') && EDPROBE_PROBE;

    var localhost = false;
    var devdomain = false;
    var level = 'live';
    
    try {
        localhost = (location['hostname'].match('^localhost') == 'localhost');
        devdomain = (location['hostname'].match('^dev.*(flyfi|emergent)') == 'dev') || localhost;
        level = location['pathname'].match('^/dev/') ? 'dev' : (location['pathname'].match('^/live/') ? 'demo' : 'live');
    } catch (error) {}
    
    var a = [];
    a.push( '<iframe frameborder="0" scrolling="no" src="http://');
    if (localhost) {
        a.push( location['host']);
        a.push( '/');
    } else {
        if (devdomain) {
            a.push('dev');
        }
        a.push( 'partner.emergentdiscovery.com/');
    }
    a.push(     level);
    a.push(     '/tastetargetedad');
    if (isProbe) {
        a.push( 'probe');
    }
    a.push(     '/layout/300x250/');
    
    if (!isProbe) {
    	a.push( 'noadaction/');
    	a.push( noAdAction);
    	a.push( '/');
    }

    if (partnerID) {
        a.push( 'partnerid/');
        a.push( partnerID);
        a.push( '/');
    }
    if (userID) {
        a.push( 'userid/');
        a.push( userID);
        a.push( '/');
    }
    if (genres.length > 0) {
        a.push( 'genres/');
        a.push( escape(EDPROBE_mungeParamList(genres)));
        a.push( '/');
    }
    if (artists.length > 0) {
        a.push( 'artists/');
        a.push( escape(EDPROBE_mungeParamList(artists)));
        a.push( '/');
    }
    if (location['hostpage']) {
        a.push( 'hostpage/~~');
        a.push( encodeURIComponent(location['hostpage']).replace(/%2F/gi, "%252F"));
        a.push( '~~/');
    }
    var sep = '?';
    if (!cookieEnabled) {
        a.push( sep);
        sep = '&';
        a.push( 'nocookie=1');
    }
    a.push(         '" height="0" width="0">');
    a.push( '</iframe>');
    
    var html = a.join('');
    
    if (debugTargeting) {
        var debugHTML = ['<div style="background-color: yellow; font-family: sans-serif; font-size:10pt; height: 242px; padding: 4px; width: 292px;">Emergent Discovery Taste Targeted Debugging.'];
        debugHTML.push('EDPROBE_PARTNERID: ' + partnerID);
        debugHTML.push('EDPROBE_USERID: ' + userID);
        debugHTML.push('EDPROBE_GENRES: [' + genres.join(', ') + ']');
        debugHTML.push('EDPROBE_ARTISTS: [' + artists.join(', ') + ']');
        debugHTML.push('EDPROBE_ADDIV_ID: ' + addDivID);
        debugHTML.push('EDPROBE_DEBUG_TARGETING: ' + debugTargeting);
        debugHTML.push('Ad Request URL:');
        debugHTML.push( html.replace('<', '&lt;').replace('>', '&gt;') );
        debugHTML.push( '</div>' );
        html = debugHTML.join('<br />');
    }
    if (!addDivID) {
        var d = new Date();
        addDivID = "EDPROBE_ADDIV_ID" + d.getTime();
        var div = document.createElement("div");
        div.id = addDivID;
        document.body.appendChild(div);
    }
    document.getElementById(addDivID).innerHTML = html;
}

function EDPROBE_cleanUpNames(names) {
    var cleaned = [];
    for (var i = 0; i < names.length; i++) {
        cleaned[i] = names[i].replace(/(%20|%2520|-)/g, " ");
    }
    return cleaned;
}

function EDPROBE_sendProbe() {
    try {
    	EDPROBE_PROBE = true;
        var location = EDPROBE_location();
        EDPROBE_PARTNERID = "26"; // Simpli.fi
        EDPROBE_loadProbe(location);
        EDPROBE_PARTNERID = "25"; // Mog
        EDPROBE_loadProbe(location);
        EDPROBE_PARTNERID = "21"; // Emergent Discovery
        EDPROBE_loadProbe(location);
    } catch(err) {
        EDPROBE_logMsg("EDPROBE: Error sending probe: " + err);
    }
}
	
if (typeof(EDPROBE_HAS_RUN) == "undefined") {
	EDPROBE_HAS_RUN = true;
	EDPROBE_sendProbe();
}

