function PostRankWidget(options) {
  this.options = options;

  if(!PostRankWidget.instances) PostRankWidget.instances = [];
  this.id = PostRankWidget.instances.length;
  PostRankWidget.instances[this.id] = this;

  this.makeFrame();

  if(this.options['theme'] != 'diy')
    this.loadCSS(this.doc,'http://api.postrank.com/static/widget-v2.css');
  this.loadCSS(document,'http://api.postrank.com/static/widget-v2.css');

  if(this.options['theme'] != 'diy')
  {
    var widget = this;
    this.addOnResize(function(){ widget.changeHeight(); });
  }

  this.display();
   
}//end PostRankWidget

PostRankWidget.prototype.display = function()
{

  var html = '\n<div id="prwidget-' + this.id + '" class="postrank-widget' + (this.options['theme'] == 'diy' ? '-diy' : '') + ' ' + this.options['theme'] + (this.options['getWidget'] ? ' showGetWidget' : '') + '">\n';
  if(this.options['theme'] != 'diy')
    html += '  <div class="pr_widget-roundedTop"><div class="pr_clearTopLeft"></div><div class="pr_solidMiddle"></div><div class="pr_clearTopRight"></div></div>\n';
  html += '  <div class="pr_widget-innerContainer">';
  html += '    <div id="prwidget-' + this.id + '-posts-wrapper" class="postrank-posts-wrapper">\n';
  if(this.options['theme'] != 'diy')
    html += '      <div class="pr_widget-corners"><div class="pr_widget-topLeft"></div><div class="pr_widget-topRight"></div><div class="pr_widget-bottomLeft"></div><div class="pr_widget-bottomRight"></div></div>';
  html += '      <ul id="prwidget-' + this.id + '-posts" class="postrank-posts"></ul>';
  html += '    </div>\n';
  html += '    <table class="none"><tr><th></th><td class="none"><input id="prwidget-' + this.id + '-topic" type="none" /></td><td class="postrank-customrss"><a id="prwidget-' + this.id + '-rss" href="#" title="" class="postrank-customize"><span></span></a></td></tr></table>\n';
  html += '  </div>';
  if(this.options['theme'] != 'diy')
    html += '  <div class="pr_widget-roundedBottom"><div class="pr_clearBottomLeft"></div><div class="pr_solidSpecialMiddle"></div><div class="pr_clearBottomRight"></div></div>';
  if(this.options['getWidget'])
  {
    html += '<div class="pr_getthiswidgetContainer">';
    html += '  <div class="pr_getthiswidget">';
    html += '  <div class="pr_clearTopLeft"></div>';
    html += '  <a href="/publishers/customize?url=' + this.options['getWidget'] + '" target="_top">Get this Widget</a>';
    html += '  <div class="pr_bottomCornerSet"><div class="pr_clearBottomLeft"></div><div class="pr_solidSpecialMiddle"></div><div class="pr_clearBottomRight"></div></div>';
    html += '  </div>';
    html += '  </div>';
  }
  html += '</div>\n';
  html += '<!--[if lte IE 6]>';
  html += '<style type="text/css">'
  html += '      .postrank-posts-wrapper {  height: 0;  he\ight: auto;  zoom: 1;}';
  html += '      .postrank-widget .postrank-posts li a.postrank-value{ background: #fff url( http://api.postrank.com/static/widgetSprite.gif ) no-repeat 0 0; float: left; margin-left: -15px;}';
  html += '</style>';
  html += '<![endif]-->';
  this.wrapper.innerHTML = (html);

  var topic_box =  this.doc.getElementById('prwidget-' + this.id + '-topic')
  var widget = this;
  topic_box.onkeyup = function()
  {
    clearTimeout(PostRankWidget.timeout_id);
    PostRankWidget.timeout_id = setTimeout(function()
    {
      var filter = topic_box.value;
      widget.getTopPosts(filter);
    } ,500);//wait .5 seconds before applying filter
  };
  this.doc.getElementById('prwidget-' + this.id + '-rss').onclick = function()
  {
    widget.customize(widget.doc.getElementById('prwidget-' + widget.id + '-topic').value);
    return false;
  };

  var filter = topic_box.value;
  widget.setLoading();
  widget.getTopPosts(filter);
}

PostRankWidget.prototype.render = function(data) {
  var html = '';
  for(var i = 0; i < data['items'].length; i++) {
    var item = data['items'][i];
    item.title = PostRankWidget.escapeXSS(item.title);

    if(!item.postrank) continue;
    html += '      <li>\n';
    html += ''
    html += '        <a class="postrank-title" href="'+item.link+'"';
    html += ' title="'+item.title+'" target="_top">'+item.title+'</a>\n';
    html += '      </li>\n';
  }
  if(data['items'].length == 0)
  {
    html += '      <li>Nenhuma postagem encontrada.</li>\n';
  }
  var posts = this.doc.getElementById('prwidget-' + this.id + '-posts')
  posts.innerHTML = html;
  if(this.options['theme'] != 'diy')
  {
    var wrapper = this.doc.getElementById('prwidget-' + this.id);
    wrapper.style.minWidth = document.getElementById('prwidget-' + this.id + '-wrapper').offsetWidth + 'px';
    this.changeHeight();
    if(!this.minHeight)
    {
      this.minHeight = posts.offsetHeight;
      posts.style.minHeight = posts.offsetHeight + 'px';
    }
    setTimeout(function()
    {
      wrapper.style.minWidth = '';
    },0);
  }
}//end function aiderss_top_posts_widget_step2

PostRankWidget.prototype.changeHeight = function()
{
    var widget = this;
    setTimeout(function(){
      widget.frame.style.height = widget.doc.getElementById('prwidget-body').offsetHeight + 10 +  'px';
    },navigator.userAgent.indexOf('MSIE') != -1 ? 200 : 0);//IE Race condition
}

PostRankWidget.prototype.getTopPosts = function(query)
{
  this.setLoading();
  this.getJSON('http://api.postrank.com/v2/feed/' + this.options['feed_hash'] + '/topposts?appkey=postrank.com/widget&format=json&num=' + this.options['num'] + '&q=' + query + '&callback=PostRankWidget.instances[' + this.id + '].render');
}

PostRankWidget.prototype.getPosts = function()
{
  this.setCustomizeLoading();
  this.getJSON('http://api.postrank.com/v2/feed/' + this.options['feed_hash'] + '?format=json&appkey=postrank.com/widget&level=' + this.customizeLevel + '&q=' + this.customizeFilter + '&num=8&start=0&callback=PostRankWidget.instances[' + this.id + '].renderCustomize');
}

PostRankWidget.prototype.setLoading = function()
{
  var html = '<li>Carregando...</li>\n';
  this.doc.getElementById('prwidget-' + this.id + '-posts').innerHTML = html;
}

PostRankWidget.prototype.setCustomizeLoading = function()
{
  var html = '<li>Carregando...</li>';
  document.getElementById('prwidget-customize-posts').innerHTML = html;
}

PostRankWidget.prototype.customize = function(query)
{
  var height = this.getHeight() * 0.9 - 280;

  var html = '\n';
  html += '  <div class="pr_customize-roundedTop"><div class="pr_clearTopLeft"></div><div class="pr_solidMiddle"></div><div class="pr_clearTopRight"></div></div>';
  html += '  <div class="pr_innerCustomContainer">';
  html += '    <h2>&nbsp;<a href="#" id="prwidget-close" class="pr_customize-close"><small> - Fechar</small></a></h2>\n';
  html += '    <div class="pr_customize-content">\n';
  html += '      <div class="pr_customize-corners"><div class="pr_customize-topLeft"></div><div class="pr_customize-topRight"></div><div class="pr_customize-bottomLeft"></div><div class="pr_customize-bottomRight"></div></div>';
//  html += '      <p class="pr_customize-engagement pr_customize-up">687%<span></span></p>';
  html += '      <h3 id="prwidget-customize-title">Title</h3>\n';
  html += '      <div class="pr_customize-utilityBar">\n';

  html += '      </div>\n';
 
  html += '      <ul id="prwidget-customize-posts" class="pr_customize-posts" style="height:' + height + 'px;">\n';
  html += '        <li></li>\n';
  html += '      </ul>\n';

  html += '      <div class="pr_customize-subscribeBar">\n';
  html += '        <div class="pr_customize-sbContent">\n';
  html += '          <table class="pr_customize-rawFeed"><tr><td><input id="prwidget-customize-feed-url" type="text" readonly="readonly" value="" /></td><td class="pr_subscribeRaw"><a id="prwidget-customize-feed-link" href="#"></a></td></tr></table>\n';
  html += '          <table id="prwidget-customize-badges" class="pr_customize-badges"></table>\n';
  html += '        </div>\n';
  html += '      </div>\n';
  html += '    </div>\n';
  html += '    <p class="poweredByPostRank"><a href="http://www.postrank.com/publishers"><span>Powered by Postrank</span></a></p>\n';
  html += '    <div class="pr_clear"></div>';
  html += '  </div>';
  html += '  <div class="pr_customize-roundedBottom"><div class="pr_clearBottomLeft"></div><div class="pr_solidMiddle"></div><div class="pr_clearBottomRight"></div></div>';

  var customize = document.createElement('div');
  customize.id = 'prwidget-customize';
  customize.className = 'pr_customize ' + this.options['theme'];
  customize.innerHTML = html;
  document.getElementsByTagName('body')[0].appendChild(customize);

  /* IE6 Hack */
  if(navigator)
  {
    var browser = navigator.appName;
    var version = navigator.appVersion;
    if(browser == 'Microsoft Internet Explorer' && version.match('MSIE 6.0'))
    {
      customize.style.position = 'absolute';
      css = '';
      css += '      .pr_customize-posts li a.postrank-value{ background: #fff url( http://api.postrank.com/static/widgetSprite.gif ) no-repeat 0 0; float: left; margin-left: -20px; }';
      css += '      .pr_customize-content {  height: 0;  he\ight: auto;  zoom: 1; }';
      css += '      .pr_background { display:none; }';
      var style = document.createElement('style');
      style.type = "text/css";
      style.styleSheet.cssText = css;

      document.getElementsByTagName('head')[0].appendChild(style);
      window.location = '#';
    }
  }

  var badgeTable = document.getElementById('prwidget-customize-badges');
  var badges = [];

  var badgeNames = ['Google','NewsGator','Bloglines','NetVibes','Yahoo'];
  var badgeTitles = ['Google Reader or Google Homepage','NewsGator Online','Bloglines','NetVibes','My Yahoo!'];

  var row = document.createElement('tr');
  var tbody = document.createElement('tbody');
  for(var i = 0; i < 5; i++)
  {
    var cell = document.createElement('td');
    badges[i] = document.createElement('a');
    badges[i].title = badgeTitles[i];
    badges[i].href = "";
    badges[i].className = 'pr_customize-serviceBadge pr_customize-addTo_' + badgeNames[i];
    cell.appendChild(badges[i]);
    row.appendChild(cell);
  }
  tbody.appendChild(row);
  badgeTable.appendChild(tbody);

  var background = document.createElement('div');
  background.className = 'pr_background ' + this.options['theme'];

  background.onclick = function()
  {
    customize.parentNode.removeChild(customize);
    background.parentNode.removeChild(background);
    return false;
  }

  document.getElementsByTagName('body')[0].appendChild(background);

  document.getElementById('prwidget-close').onclick = function()
  {
    customize.parentNode.removeChild(customize);
    background.parentNode.removeChild(background);
    return false;
  };

  document.onkeydown = function( e )
  {
    if ((e && e.which == 27) || (window.event && window.event.keyCode == 27))
    {
      customize.parentNode.removeChild(customize);
      background.parentNode.removeChild(background);
    } 
  };

  var topic_box =  document.getElementById('prwidget-customize-topic')
  var widget = this;
  topic_box.onkeyup = function()
  {
    clearTimeout(PostRankWidget.timeout_id);
    PostRankWidget.timeout_id = setTimeout(function()
    {
      widget.customizeFilter = topic_box.value;
      widget.updateBadges(badges);
      widget.getPosts();
    } ,500);//wait .5 seconds before applying filter
  };

  topic_box.onfocus = function()
  {
    if(topic_box.value == 'Topic search...')
      topic_box.value = '';
  };

  topic_box.onblur = function()
  {
    if(topic_box.value == '')
      topic_box.value = 'Topic search...';
  };

  var postrank_box = document.getElementById('prwidget-customize-postrank');

  postrank_box.onchange = function()
  {
    widget.customizeLevel = this.value;
    widget.updateBadges(badges);
    widget.getPosts();
  }

  postrank_box.focus();

  this.customizeFilter = query;
  document.getElementById('prwidget-customize-topic').value = query ? query : 'Topic search...';
  this.updateBadges(badges);

  this.getPosts();
}

PostRankWidget.prototype.updateBadges = function(badges)
{
  var badgeUrls = ['http://fusion.google.com/add?feedurl=%s','http://www.newsgator.com/ngs/subscriber/subext.aspx?url=%s','http://www.bloglines.com/sub/%s','http://www.netvibes.com/subscribe.php?url=%s','http://add.my.yahoo.com/rss?url=%s'];
  var feed = 'http://feeds.postrank.com/' + this.options['feed_hash']
  if(this.customizeLevel || this.customizeFilter)
    feed += '?';
  if(this.customizeLevel)
    feed += 'level=' + this.customizeLevel
  if(this.customizeLevel && this.customizeFilter)
    feed += '&';
  if(this.customizeFilter)
    feed += 'q=' + this.customizeFilter;

  setTimeout(function(){
    document.getElementById('prwidget-customize-feed-url').value = feed;
    document.getElementById('prwidget-customize-feed-link').href = feed;
  },0);//Odd IE race conditon, where the prwidget-customize-feed-url gets expanded.
    

  for(var i = 0; i < badges.length; i++)
  {
    badges[i].href = badgeUrls[i].replace(/%s/,encodeURIComponent(feed));
  }
}

PostRankWidget.prototype.renderCustomize = function(data)
{
  var html = '\n';
  if(data['items'].length > 0)
  {
    for(var i = 0; i < data['items'].length; i++)
    {
      var item = data['items'][i];
      item.title = PostRankWidget.escapeXSS(item.title);
      item.description = this.trimDesc(item.description);
      html += '      <li>\n';
      html += '        <a class="postrank-value" style="background-color:'+item.postrank_color+';" href="http://www.postrank.com/feed/'+this.options['feed_hash']+'" title="PostRank">';
      html += item.postrank.toFixed(1);
      html += '</a>\n';
      html += '        <a class="link" href="'+item.link+'"';
      html += ' title="'+item.title+'">'+item.title+'</a>\n';
      html += '<p class="postrank-postDate">' + this.getDate(item.pubdate) + '</p>';
      html += '        <p>';
      html += item.description
      html += '</p>\n';
      html += '      </li>\n';
    }
    html += '    ' //format </ul>

    document.getElementById('prwidget-customize-title').innerHTML = data['items'][0].feed_title;
  }
  else
  {
    html += '<li>No posts found.</li>\n';
  }
  document.getElementById('prwidget-customize-posts').innerHTML = html;
}


PostRankWidget.prototype.loadCSS = function(doc,url)
{
  var css = doc.createElement('link');
  css.rel = 'stylesheet';
  css.type = 'text/css';
  css.media = 'screen';
  css.href = url;
  doc.getElementsByTagName('head')[0].appendChild(css);
}

PostRankWidget.prototype.getJSON = function(url,id)
{
  var s = document.createElement('script');
  s.src = url;
  s.type = 'text/javascript';
  if (id) s.id = id
  document.getElementsByTagName('head')[0].appendChild(s);
}

PostRankWidget.prototype.getHeight = function()
{
  /* http://www.howtocreate.co.uk/tutorials/javascript/browserwindow */
  var height = 0;
  if( typeof( window.innerHeight ) == 'number' ) {
    //Non-IE
    height = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    height = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientHeight ) ) {
    //IE 4 compatible
    height = document.body.clientHeight;
  }
  return height;
}

PostRankWidget.prototype.makeFrame = function()
{
  document.write('<div id="prwidget-' + this.id + '-wrapper" class="postrank-wrapper"></div>');
  var wrapper = document.getElementById('prwidget-' + this.id + '-wrapper');
  if(this.options['theme'] == 'diy')
  {
    this.frame = window;
    this.doc = document;
    this.wrapper = wrapper;
  }
  else
  {
    wrapper.innerHTML = '<iframe id="prwidget-' + this.id + '-iframe" class="postrank-iframe" name="prwidget-' + this.id + '-iframe" frameborder="0" style="border-width: 0px; width: 100%; overflow: hidden;" allowtransparency="true" ></iframe>';
    var frame = document.getElementById('prwidget-' + this.id + '-iframe');
    this.frame =  frame;
    this.doc = this.getDocument(frame);
    this.doc.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html><head><title>PostRankWidget</title></head><body id="prwidget-body"></body></html>');
    this.wrapper = this.doc.body;
    this.doc.close();
  }
}

PostRankWidget.prototype.getDocument = function(frame)
{
  var doc = null;
  if (frame.contentDocument)
    doc = frame.contentDocument;
  else if(frame.contentWindow)
    doc = frame.contentWindow.document;
  else if(frame.document)
    doc = frame.document;
  else
    throw "Document not initialized";
  return doc;
}

PostRankWidget.prototype.trimDesc = function(text)
{
  return PostRankWidget.escapeXSS(text.split(' ',20).join(' ')) + ' [...]';
}

PostRankWidget.prototype.getDate = function(unixtime)
{
  var d = new Date(unixtime * 1000);
  var months = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Agost','Set','Out','Nov','Dzc'];
  return months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
}

PostRankWidget.prototype.addOnResize = function(func)
{
  var orig = window.onresize;
  window.onresize = function()
  {
    if(typeof orig == 'function')
      orig();
    func();
  }
}

PostRankWidget.escapeXSS = function(text)
{
   text = text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
   return text;
}