//function rockyouad () {
//}

if (typeof(rockyouad) == 'undefined') {
var rockyouad = function() {};

rockyouad.configs = [];
rockyouad.ryads = [];
rockyouad.AdNetworkID_FaceBook=1;
rockyouad.AdNetworkID_MySpace=2;
rockyouad.AdNetworkID_Hi5=3;
rockyouad.AdNetworkID_OrKut=4;

rockyouad.prototype.width=646;
rockyouad.prototype.height=60;
rockyouad.prototype.style='border:0px;';

rockyouad.prototype.userid = "";
rockyouad.prototype.networkid = 0;
rockyouad.prototype.debugOn=0;


rockyouad.prototype.gup = function(name)
{  
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
  var regexS = "[\\?&]"+name+"=([^&#]*)";  
  var regex = new RegExp( regexS );  
  this.debug("In gup:" + window.location.href);
  this.debug("In gup: referer = " + document.referrer);
  var results = regex.exec( window.location.href );
  if( results != null ) {
    return results[1];
  }
  else
  {
    results = regex.exec( document.referrer );
    if ( results != null ) return results[1];
    else return "";
  }
};

rockyouad.prototype.detectRyf = function() 
{
    try {
        var h = window.location.hostname.toLowerCase().split('.');
        var c = h.length;
        if (c >=2 && h[c-1] == 'com' && h[c-2] == 'rockyou' && window.location.pathname.indexOf('/ams') >= 0) {
            this.config.ryf = 1;
        }
    } catch (e) {
        this.debug("detectRyf failed");
    }
}


rockyouad.prototype.create = function(config) 
{
  
  this.config = config;
};

rockyouad.prototype.run = function()
{
  this.initAdSize();
  this.detectNetwork();
  this.detectRyf();
  this.detectUserId();
  this.getAd();
};

rockyouad.prototype.detectNetwork = function() 
{
  try {
    var l = window.location.href;
    var lr = document.referrer;
    this.debug('window.location.href = ' + l);  
    this.debug('document.referrer = ' + lr);                                                                                 
    if (l.indexOf('http://api.msappspace.com') == 0 || lr.indexOf('http://api.msappspace.com') == 0)
    {
      this.networkid=rockyouad.AdNetworkID_MySpace;
    }
  }
  catch (e) { 
    this.debug('Failed to get window.location.href');
  } 
  this.debug("Network is " + this.networkid);
};

rockyouad.prototype.detectUserId = function()
{
  var uid = this.gup('viewerId');
  if (!uid) {
    uid = this.gup('opensocial_viewer_id');
  }
  this.userid = uid;
  this.debug("user id is " + this.userid);
};

/**
 * Initialize the size of the Ad Unit (width and height)
 */
rockyouad.prototype.initAdSize = function() {
  var config = this.config;
  if (config.type == 'Banner') {
    this.width = 646;
    this.height = 60;
  } else if (config.type == 'CrossSell') {
    this.width = 646;
    this.height = 250;
  } else if (config.type == 'Leaderboard') {
    this.width = 728;
    this.height = 90;
  } else if (config.type == 'MediumRectangle') {
    this.width = 300;
    this.height = 250;
  } else if (config.type == 'WideSkyscraper') {
    this.width = 160;
    this.height = 600;
  }
};

/**
 * Render the Ad
 */
rockyouad.prototype.getAd = function()                            
{
  var url = this.getAdUrl();
  var e = document.getElementById(this.config.id);
  if (!e) {
    return;
  }
  e.innerHTML = '';
  var scriptDiv = document.createElement('div');
  scriptDiv.id = e.id + "_s";
  e.appendChild(scriptDiv);
  var contentDiv = document.createElement('div');
  contentDiv.id = e.id + "_c";
  e.appendChild(contentDiv);
  
  if (this.config.synchronous) {
    document.write("<scr" + "ipt type='text/javascript' src='"+ url +"'></scr" + "ipt>");
  } else {
    this.loadScriptUrl(url);
  }
};

rockyouad.prototype.displayAd = function(response) 
{
    var pageType = response['pageType'];
    var width = response['width'];
    var height = response['height'];
    var content = response['content'];
    
    this.debug(this.config.id + " width = " + width + " height = " + height);
    if (pageType == 'dom') {
        var e = document.getElementById(this.config.id + '_c');
		e.style.width = width;
        e.style.height = height;
        
        content = content.replace(/\$divId/g, this.config.id);
    
        // Evaluate any javascript in 'content'
        var jsFragmentRegExp = '<script([^>]*)>([\u0001-\uFFFF]*?)</script>';
        var matchAll = new RegExp(jsFragmentRegExp, 'img');
        this.matchOne = new RegExp(jsFragmentRegExp, 'im');
        this.matchSrc = new RegExp('src="([^"]*)"', 'im')
        var jsFragments = (content.match(matchAll) || []);

        this.debug("jsFragments");
        this.debug(jsFragments);

        content = content.replace(matchAll, '');
        this.debug("content is ");
        this.debug(content);

        e.innerHTML = content;
         
        var isIE = window.ActiveXObject ? true : false;
        if (isIE) {
            this.scriptQueue = [];
        }
    
        for (var i=0; i<jsFragments.length; i++) {
            if (isIE) {
                this.scriptQueue.push(jsFragments[i]);
            } else {
                this.loadScriptTag(jsFragments[i]);
            }
        }
        if (isIE) this._runNextScriptElement();
        
    } else if (pageType == 'iframe') {
        var e = document.getElementById(this.config.id + '_c');
        e.innerHTML = 
            "<iframe id='" +  this.config.id + "_f" + "'" +
            (width? " width='"+ width+"' " : "") +
            (height? " height='"+ height+"' " : "") +
            " style='"+this.style+"' " +
            //" src=''" + 
            " scrolling='no' frameborder='0' allowtransparency='true'></iframe>"; /* hspace='0' vspace='0' marginheight='0' marginwidth='0'> */
    
        var f = document.getElementById(this.config.id + "_f");
        var d = null;
        if (f.contentDocument) {
            d = f.contentDocument;
        } else if (f.contentWindow) {
            d = f.contentWindow.document;
        }
        d.open();
        d.write(content);
        d.close();
    }
};

rockyouad.prototype._runNextScriptElement = function() {
    if (this.scriptQueue.length == 0) return;
    
    var tag = this.scriptQueue.shift();
    var s = this.loadScriptTag(tag);
    
    if (s.src && s.src.length > 0) {
        // We're getting an external script, make sure we wait till the
        // script finishes before executing the next one
        var that = this;
        s.onreadystatechange = function () {
            if (s.readyState == 'complete' || s.readyState == 'loaded') {
                that._runNextScriptElement();
            }
        }
    } else {
        this._runNextScriptElement();
    }
}

rockyouad.prototype.loadScriptTag = function(jsFragment) {
    var jsFragment = (jsFragment.match(this.matchOne) || ['', '', '']);
    var url = jsFragment[1].match(this.matchSrc);
    // Inline JS script
    if (jsFragment[2].length > 0) return this.loadScript(jsFragment[2]);
    // External JS script
    if (url) return this.loadScriptUrl(url[1]);
};

rockyouad.prototype.loadScriptUrl = function(url) {
    
    var s_tag = document.createElement("script");
    s_tag.type ="text/javascript";
    s_tag.charset ="utf-8";
    s_tag.src = url;
    document.getElementById(this.config.id + '_s').appendChild(s_tag);
    return s_tag;
};

rockyouad.prototype.loadScript = function(script) {
    var s_tag = document.createElement("script");
    s_tag.type ="text/javascript";
    s_tag.charset ="utf-8";
    s_tag.text = 'rockyouad.configId="'+this.config.id + '";' + script;
    document.getElementById(this.config.id + '_s').appendChild(s_tag);
    return s_tag;
};

/**
 * Generate the Ad serving URL
 */
rockyouad.prototype.getAdUrl = function() 
{
    this.debug('rockyouad.getAd');

    var ryAdConfig = this.config;
    if (this.networkid) {
        ryAdConfig.nid = this.networkid;
    }
    if (this.userid) {
        ryAdConfig.userid = this.userid;
    }

    this.debug('typeof(ryAdConfig)=' + typeof(ryAdConfig));
    ryAdConfig.v=9;
    //ryAdConfig.nocache = (new Date()).getTime();
    var url = "http://rya.rockyou.com/ams/ad_os.php";         
    var param_str = this.encodeParam(ryAdConfig);

    this.debug(param_str);
    if (url.indexOf("?") >=0) 
        url = url + "&" + param_str;
    else
        url = url + "?" + param_str;
        
    return url;
};

// Use an array to queue up script elements. Should consider making it private.
rockyouad.prototype.scriptQueue = [];


rockyouad.prototype.encodeParam = function(param) {
    var str = "";
    for (var name in param) {
        if (typeof(param[name]) != 'function') {
            str = str + name + '=' + encodeURIComponent(param[name]) + '&';
        }
    }
    return str;
};

rockyouad.prototype.debug = function(message) {
   if (this.debugOn && typeof(console) != 'undefined' && typeof(console.log) == 'function') {
       console.log(message);
   }
};

// Global array to keep all ad units
var __ryads = [];

function _ryad(config) {
    if (typeof(config) == 'string') {
        var cid = config;
        config = rockyouad.configs[cid];
        rockyouad.configs[cid] = null;
        if (!config) {
            return;
        }
    }
    var hasBody = false;
    try {
        hasBody = (document.getElementsByTagName('body').length > 0);
    } catch (e) {
        // ignore
    }
    if (!hasBody) {
        var cid = "d_" + Math.floor(Math.random() * 100000);
        rockyouad.configs[cid] = config;
        window.setTimeout("_ryad('" + cid + "');", 10);
        return;
    }

    var ryad = new rockyouad();
    var id = null;
    /*if (typeof(config.TEST) != 'undefined') alert(config.placeguid); */
    if (typeof(config.id) == 'string') {
        id = config.id;
    } else if (typeof(config.placeguid) == 'string') {
        var eid = '_ryad_' + config.placeguid;
        var ele = document.getElementById(eid);
        if (ele) {
            //if (typeof(config.TEST) != 'undefined') alert('Found ele');
            // Change the element id so we can include the same Ad tag twice
            id = eid + "_" + Math.floor(Math.random() * 100000);
            ele.id = id;
            //alert(id + ',' + ele.id);
        }
    }
    if (id == null) {
        // Generate a unique id for each ad tag because
        // publishers can show multiple Ads on the same HTML page
        id = '_ryad_' + Math.floor(Math.random() * 100000);
        document.write("<div id='" + id + "'></div>");
    }
    config.id = id;
    rockyouad.ryads[id] = ryad;
    ryad.create(config);
    ryad.run();
}

}


if (typeof(_ryadConfig) != 'undefined') {
    _ryad(_ryadConfig);
}
