var rp_com = rp_com || {};

rp_com.is_msie = (navigator.userAgent.indexOf('MSIE') >= 0)

rp_com.add_widget = function (dom_id, url) {
  window.rp_frames = (window.rp_frames || 0) + 1
  var script = document.createElement('script')
  script.type ='text/javascript'
  script.src = url  + '&container_dom_id=' + dom_id

  if (rp_com.is_msie) {
    document.write('<script defer src="' + script.src + '"><\/script>')
  } else {
    document.body.appendChild(script)
  }
}

rp_com.widget = function(dom_id, url) {
  var kind = dom_id[dom_id.length-1];
  if ( 'n' == kind) {
    rp_com.widget_new(dom_id, url);
  } else {
    if ( 'r' == kind ) {
      var container = document.getElementById(dom_id);
      var anchor = document.createElement('a');
      anchor.name = 'rp_reviews_list';
      container.parentNode.insertBefore(anchor, container);
    } 

    rp_com.add_widget(dom_id, url + '&product_page_url=' + escape(document.location.href.replace(/#[^#]*$/,'')));
  }
}

// New widget requires explicit product id
// So we parse it from rpprodid url param
rp_com.widget_new = function(dom_id, url) {
  var context_url = window.location.toString();
  var pid = /rpprodid=([a-zA-Z0-9_-]+)/.exec(context_url)[1];

  if (!pid) return;

  url = url.replace(/\/partner_product_id\//, '/' + pid + '/');
  
  var review_id = /rprevid=(\d+)/.exec(context_url);
  var vote = /rpvote=(\w+)/.exec(context_url);

  var bid = /bid=(\d+)/.exec(context_url);
  var token = /token=(\w+)/.exec(context_url);

  if (vote && review_id && vote[1] && review_id[1]) { url +=  ("&vote=" + vote[1] + "&review_id=" + review_id[1]) }
  if (bid && token && bid[1] && token[1] ) { url +=  ("&bid=" + bid[1] + "&token=" + token[1]) }

  rp_com.add_widget(dom_id, url);
}

// alias for old generated widget code
rp_com.new_widget = rp_com.widget_new;

function rp_com_parse_document_domain(count) {
  var names = document.location.hostname.split('.')
  var base = []
  for (var i = 0; i< count; i++) {
    base.push(names.pop())
  }
  return base.reverse().join('.')
}

function rp_com_try_guess_document_domain(count){
  if (count > 10) return
  var docdom = rp_com_parse_document_domain(count)
  try {
    document.domain = docdom;
    window.rp_com_document_domain_set = 1
  } catch(e) {
    rp_com_try_guess_document_domain(count + 1)
  }
}

function rp_com_set_document_domain() { 
  if (!window.rp_with_helper) return
  if (window.rp_com_document_domain_set) return
  rp_com_try_guess_document_domain(2) 
}

function rp_com_set_document_domain_ie() {
  try {
    rp_com_set_document_domain()
  } catch(e) {
    window.rp_attempts_count = window.rp_attempts_count || 0
    if (window.rp_attempts_count > 10) return
    setTimeout('rp_com_set_document_domain_ie()', 1);
  }
}
function rp_com_set_docdom() {

  ((rp_com.is_msie) ?
   function() { } :
   rp_com_set_document_domain).call()
}
