var Rgm = {};
Rgm.config = {};
Rgm.controls = {};
var double_click_ads = {};
Rgm.sync_enabled = false; // set by rails in bottom JS

Rgm.addControl = function(pName,element)
{
  var c = this.controls;
  if (!c[pName]){
    c[pName] = element;
  }
  return element;
}
Rgm.getControl = function(pName)
{
  var c = this.controls;
  if (c[pName])
  {
    return c[pName];
  }
  return null;
}

Rgm.isLoggedIn = function()
{
  return Cookie.get('rgm_logged_in') != null;
}

Rgm.isLoggedInWithRPX = function()
{
  return RgmSocial.get_provider() != null;
}

/**
 * must be called when user logs out. Will call RPX social API to logout.
 * Also if sync_user is enabled, make synchronous Ajax request to do cross domain logout.
 */
Rgm.logout = function() {
  RgmSocial.logout();
}

Rgm.firstName = function()
{
  return Cookie.get('rgm_first_name');
}

Rgm.currentUserId = function()
{
  return Cookie.get('rgm_current_user_id');
}

Rgm.profileUrlUser = function()
{
  return Cookie.get('rgm_profile_url');
}

Rgm.photoUrlUser = function()
{
  return Cookie.get('rgm_photo_url_user');
}

Rgm.friendshipRequestsCount = function()
{
  return Cookie.get('rgm_friendship_requests_count');
}
// assemble sharded cookie into array - prefix must include trailing underscore
// TODO this is inefficient wrt lookup into these arrays
Rgm.readShardedCookie = function(prefix)
{
    var n = 0;
    var cookie_array = [];
    while (Cookie.get(prefix + n) != null) {
      cookie_array.push(Cookie.get(prefix + n));
      n++;
    }
    var ids = cookie_array.join("_");
    return (ids == null || ids.length == 0) ? [] : ids.split("_");
}
Rgm.pendingFriendshipIds= function()
{
  return Rgm.readShardedCookie('rgm_pending_friendship_ids_');
}
Rgm.setPendingFriendships = function(profile_user_id)
{
  new Ajax.Request('/favorite/ajax_is_pending_friendship/' + profile_user_id, {asynchronous:true, evalScripts:true,
    onSuccess: function(transport) {
      if (transport.responseText == "1") {
        $('add_friend_btn').hide();
        $('what_is_add_friend_link').hide();
        $('request_sent').show();
        $('what_is_request_sent_link').show();
      }
    }
  });
}
Rgm.friendshipRequestsIds= function()
{
  return Rgm.readShardedCookie('rgm_friendship_requests_ids_');
}
Rgm.setFriendshipRequests = function(profile_user_id)
{
  new Ajax.Request('/favorite/ajax_is_friendship_request/' + profile_user_id, {asynchronous:true, evalScripts:true,
    onSuccess: function(transport) {
      if (transport.responseText == "1") {
        $('add_friend_btn').hide();
        $('what_is_add_friend_link').hide();
        $('add_acceptFriend_btn').show();
        $('what_is_accept_friend_link').show();
      }
    }
  });
}
Rgm.userFriendsIds = function()
{
  return Rgm.readShardedCookie('rgm_user_friends_ids_');
}
Rgm.setUserFriends = function(profile_user_id)
{
  new Ajax.Request('/favorite/ajax_is_user_friend/' + profile_user_id, {asynchronous:true, evalScripts:true,
    onSuccess: function(transport) {
      if (transport.responseText == "1") {
        $('already_friends').style.display = '';
        $('add_friend').style.display = 'none';
      }
    }
  });
}
Rgm.showEmailSuspendedNotice = function()
{
  return Cookie.get('rgm_show_email_suspended_message') == 'true';
}
Rgm.isEditor = function()
{
  return Cookie.get('rgm_user_is_editor') != null;
}
Rgm.isStaff = function()
{
  return Cookie.get('rgm_user_is_staff') != null;
}
Rgm.unreadNotice = function()
{
  return Cookie.get('rgm_unread_message_count');
}
Rgm.likedArticleIds = function()
{
  return Rgm.readShardedCookie('rgm_liked_article_ids_');
}
// find if this user has set this article as one of their "like it" (used for IE <= 7)
Rgm.setLikedArticle = function(global_id)
{
  new Ajax.Request('/favorite/ajax_is_liked_content_resource/' + global_id, {asynchronous:true, evalScripts:true,
      onSuccess: function(transport) {
        if (transport.responseText == "1") {
          $('liked_it_link').hide();
          $('already_liked_it').show();
        } else {
          $('liked_it_link').hide();
          $('liked_it_link_logged_in').show();
        }
      },
      onFailure: function(transport) {
        $('liked_it_link').hide();
        $('liked_it_link_logged_in').show();
      }
  });
}
Rgm.votedAwardEntryIds = function()
{
  return Rgm.readShardedCookie('rgm_voted_award_entry_ids_');
}
// find if this user has voted for this award (used for IE <= 7)
Rgm.setAwardEntryVotes = function(nominee_id)
{
  new Ajax.Request('/favorite/ajax_is_award_entry_vote/' + nominee_id, {asynchronous:true, evalScripts:true,
      onSuccess: function(transport) {
        if (transport.responseText == "1") {
          if($('vote_button_'+nominee_id) != null)
          {
            $('vote_button_'+nominee_id).style.display = "none";
            $('already_voted_'+nominee_id).style.display = "";
          }
          if($('vote_button_detail_'+nominee_id) != null)
          {
            $('vote_button_detail_'+nominee_id).style.display = "none";
            $('already_voted_detail_'+nominee_id).style.display = "";
          }
        }
      }
  });
}

Rgm.renderPartial = function(partial, variables)
{
  if (variables)
  {
    for (var key in variables)
    {
      var variable_name = key;
      var value = eval(variables[key]);
      partial = partial.replace(variable_name, value);
    }
  }
  document.write(partial);
}

Rgm.onLoads = new Array();
Rgm.bodyOnLoad = function() {
  for ( var i = 0 ; i < Rgm.onLoads.length ; i++ ) {
    Rgm.onLoads[i]();
  }
  Rgm.runLoginHooks();
}

Rgm.loginHooks = new Array();
Rgm.addLoginHook = function(loginHook) {
  Rgm.loginHooks.push(loginHook);
}
Rgm.runLoginHooks = function() {
  if (Rgm.isLoggedIn()) {
    for ( var i = 0 ; i < Rgm.loginHooks.length ; i++ )
      Rgm.loginHooks[i]();
  }
}
Rgm.friendshipStatus =  function(profile_user_id){
    if(Rgm.isLoggedIn()){
        //  Current user profile
        if(profile_user_id == Rgm.currentUserId()){
            $('add_friend').style.display = 'none';
            $('my_profile').style.display = "";
        }
        // Pending Friendships
        var pending_freindship_ids = Rgm.pendingFriendshipIds();
        if(pending_freindship_ids.indexOf(profile_user_id) > -1){
            $('add_friend_btn').hide();
            $('what_is_add_friend_link').hide();
            $('request_sent').show();
            $('what_is_request_sent_link').show();
        } else if (Utils.supportAjaxSharding && Utils.checkForValueOnServer(pending_freindship_ids, profile_user_id)) {
            Rgm.setPendingFriendships(profile_user_id);
        }
        var friendship_request_ids = Rgm.friendshipRequestsIds();
        if(friendship_request_ids.indexOf(profile_user_id) > -1){
            $('add_friend_btn').hide();
            $('what_is_add_friend_link').hide();
            $('add_acceptFriend_btn').show();
            $('what_is_accept_friend_link').show();
        } else if (Utils.supportAjaxSharding && Utils.checkForValueOnServer(friendship_request_ids, profile_user_id)) {
            Rgm.setFriendshipRequests(profile_user_id);
        }
        // Already Friends
        var user_friends_ids = Rgm.userFriendsIds();
        if (user_friends_ids.indexOf(profile_user_id) > -1){
            $('already_friends').style.display = '';
            $('add_friend').style.display = 'none';
        } else if (Utils.supportAjaxSharding && Utils.checkForValueOnServer(user_friends_ids, profile_user_id)) {
            Rgm.setUserFriends(profile_user_id);
        }
    }else{
        //  Logout
        if(Rgm.currentUserId()== null){
            $('add_friend').style.display = "";
            $('my_profile').style.display = 'none';
        }
    }
}
Rgm.checkDiscussion = function() {
  if (Rgm.isLoggedIn()) {
    $("contribute_top").style.display = "";
    $("login_link_top").style.display = "none";
    if ($("contribute_bottom")) {
      $("contribute_bottom").style.display = "";
      $("login_link_bottom").style.display = "none";
    }
    new Ajax.Request('/ajax_add_discussion_rpx_options', {asynchronous:true, method:'get', evalJS:'force'});
  } else {
    $("contribute_top").style.display = "none";
    $("login_link_top").style.display = "";
    if ($("contribute_bottom")) {
      $("contribute_bottom").style.display = "none";
      $("login_link_bottom").style.display = "";
    }
  }
}

Rgm.checkLikedIt = function(global_id)
{
  if(Rgm.isLoggedIn())
  {
    // first check if there is a cookie representing this page
    liked_ids = Rgm.likedArticleIds();
    if (liked_ids.indexOf(global_id) > -1) {
      $('liked_it_link').hide();
      $('already_liked_it').show();
    }else{
      // if the cookie holds 'more' do ajax call to check for remaining IDs
      // Note that this hide and show code is duplicated in setLikedArticle
      if (Utils.supportAjaxSharding && Utils.checkForValueOnServer(liked_ids, global_id)) {
        Rgm.setLikedArticle(global_id);
      } else {
        $('liked_it_link').hide();
        $('liked_it_link_logged_in').show();
      }
    }
  }
}

Rgm.checkCommentsSocialLogin = function()
{
  if(Rgm.isLoggedIn())
  {
    if ($('comments_loginLink')) {
      $('comments_loginLink').hide();
    }
  }
}

Rgm.checkAwardEntryVotes = function(nominee_id_array)
{
  if(Rgm.isLoggedIn())
  {
    var voted_award_ids = Rgm.votedAwardEntryIds(); // IDs user has voted for in an array
    var nominee_ids = nominee_id_array.split("_"); // all nominees on this page
    for(var i=0;i<nominee_ids.length;i++)
    {
      if (nominee_ids[i].length == 0) {
          continue;
      }
      var determined_vote = false;
      for(var j=0;j<voted_award_ids.length;j++)
      {
        if(voted_award_ids[j] == nominee_ids[i])
        {
          determined_vote = true;
          if($('vote_button_'+voted_award_ids[j]) != null)
          {
            $('vote_button_'+voted_award_ids[j]).style.display = "none";
            $('already_voted_'+voted_award_ids[j]).style.display = "";
          }
          if($('vote_button_detail_'+voted_award_ids[j]) != null)
          {
            $('vote_button_detail_'+voted_award_ids[j]).style.display = "none";
            $('already_voted_detail_'+voted_award_ids[j]).style.display = "";
          }
        }
      }
      if (!determined_vote && Utils.supportAjaxSharding && Utils.checkForValueOnServer(voted_award_ids, nominee_ids[i])) {
        Rgm.setAwardEntryVotes(nominee_ids[i]);
      }
    } // eachg nominee
  }
}

Rgm.checkReferrer = function(ref)
{
  var DIGG_TAB_REFERERS = new Array('digg','reddit','stumbleupon','propeller','mixx');
  for(var i=0;i< DIGG_TAB_REFERERS.length; i++)
  {
    if (ref.match(DIGG_TAB_REFERERS[i]))
    {
      return true;
    }
  }
  return false;
}

Rgm.focusTab = function(ref)
{
  if (Rgm.checkReferrer(ref)) 
  {
    $('tab_on_1').style.display = 'none';
    $('tab_off_1').style.display = '';
    $('tab_on_3').style.display = '';
    $('tab_off_3').style.display = 'none';
    $('most_liked_container').style.display = 'none';
    $('digg_container').style.display = '';
  }
}
Rgm.setAboutSite = function()
{
  if (Rgm.isLoggedIn()) {
    $('about_site_logged_in').style.display = "";
    $('about_site_logged_out').style.display = "none";
  } else {
    $('about_site_logged_in').style.display = "none";
    $('about_site_logged_out').style.display = "";
  }
}
Rgm.setSitePromotion = function()
{
  if (Rgm.isLoggedIn()) {
    $("site_promotion_logged_in").style.display = "";
    $("site_promotion_logged_out").style.display = "none";
  } else {
    $("site_promotion_logged_in").style.display = "none";
    $("site_promotion_logged_out").style.display = "";
  }
}
Rgm.setVisibleLoggedInContext = function(logged_in_id, logged_out_id) {
  if (Rgm.isLoggedIn()) {
    $(logged_in_id).show();
    $(logged_out_id).hide();
  }
  else {
    $(logged_in_id).hide();
    $(logged_out_id).show();
  }
};
Rgm.setNewsletter = function()
{
  if (Rgm.isLoggedIn()) {
    // if were displaying the thank you page, just return
    if (!$("logged_out_newsletter")) { // implies showing thank-you
      $('newsstand_widget').show();
      return;
    }
    $("logged_out_newsletter").hide();

    // show all and hide authenticated and unauthenticated newsletters (those that require the user to be logged-in)
    $('all_newsletters').show();
    if ($('unauthenticated_newsletters')) {
      $('unauthenticated_newsletters').hide();
    }
    if ($('authenticated_newsletters')) {
      $('authenticated_newsletters').hide();
    }
    $("newsstand_submit").show(); // show submit button
    $("newsstand_submit").show(); // show submit button

    //  Disable newsletters that are currently subscribed.
    // We only care about the 'all_newsletter' set (of newsletters) because that is the set displayed when the user is logged in
    newsletter_ids = Rgm.get_subscribed_newsletters();
    for(i=0; i < newsletter_ids.length; i++) {
      if($('all_newsletter_' + newsletter_ids[i]) != null) {
        $('all_newsletter_' + newsletter_ids[i]).remove();
      }
    }
    //  If all the newsletters are subscribed, display the thank you page.
    if($$('.all_newsletter').length == 0) {
      $('newsstand_fully_subscribed').show();
      $('newsstand_form').hide();
      // if the 'hide' div exists and the user is fully subscribed, hide that div (thus hiding the entire newsstand widget)
      if($('newsstand_hide_if_fully_subscribed')) {
        $('newsstand_hide_if_fully_subscribed').hide();
      }
    }
  } else {
    if ($("logged_out_newsletter")) {
      $("logged_out_newsletter").show();
    }
    // dont display submit (it is only for logged-in state) (logged_out_newsletter has its own submit div)
    $("newsstand_submit").hide();
    // show unauthenticated and authenticated (in separate div sections) (but not all)
    $('all_newsletters').hide();
    if ($('unauthenticated_newsletters')) {
      $('unauthenticated_newsletters').show();
    }
    if ($('authenticated_newsletters')) {
      $('authenticated_newsletters').show();
    }
  }
  // Don't show checkboxes if there is only one newsletter and user is not subscribed
  if((typeof(newsletter_ids) == 'undefined' || newsletter_ids.length == 0) && $j('#all_newsletters input[type="checkbox"]').length == 1) {
    $j('#all_newsletters input[type="checkbox"]').attr('checked', 'checked');
    $j('#all_newsletters').hide();
  }
  if($j('#unauthenticated_newsletters input[type="checkbox"]').length == 1) {
    $j('#unauthenticated_newsletters input[type="checkbox"]').attr('checked', 'checked');
    $j('#unauthenticated_newsletters').hide();
  }
  // Hide newsstand_error if it is empty. If call is made to NewsletterSignupsController#render_error, it will set it visible
  if ($('newsstand_error').empty()) {
    $('newsstand_error').hide();
  } else {
    $('newsstand_error').show();
  }
  $('newsstand_widget').show();
}

Rgm.get_subscribed_newsletters = function() {
  //  If the cookie does not exist, use ajax to determine subscriptions.
  newsletters_cookie = Cookie.get('rgm_subscribed_newsletters');

  if(newsletters_cookie == null) {
    //  Get subscription info from server. This call is synchronous
    new Ajax.Request('/newsletter_signups/ajax_subscribed_newsletters/', {asynchronous:false, evalScripts:true,
      onSuccess: function(transport) {
        newsletters_cookie = transport.responseText;
      }
    });
  }

  if(newsletters_cookie == "") {
    newsletter_ids = []
  } else {
    newsletter_ids = newsletters_cookie.split("_");
  }

  //  If the cookie exists, go through it to figure out which ones to disable.
  return newsletter_ids;    
}

Rgm.jump_to = function(anchor) { 
  window.location.hash = anchor;
}

// TODO: should we hang these functions off of the Rgm Object?

function htmlClassAttribute() {
  return Utils.isIE ? 'className' : 'class';
}

function replaceTextAreaWithFckEditor(elementId, desiredHeight, toolbarSet)
{
  delete CKEDITOR.instances[elementId];
  $j('#' + elementId).ckeditor({ height: desiredHeight, 
                                 toolbar: toolbarSet, 
                                 customConfig: '/javascripts/ckeditor_config.js',
                                 filebrowserImageUploadUrl: '/member_workspace/photos/upload_photo_ckeditor?method=post'})
}

function generateSafeIdentifier(str)
{
  str = str.replace(/^\s+/g, "");
  str = str.replace(/\s+$/g, "");
  str = str.replace(/\s/g, "_");
  str = str.replace(/\&amp\;/g, "and");
  return str;
}

function switchLocation(newurl, timeoutMillis)
{
  setTimeout(function() {window.location.href = newurl;}, timeoutMillis);
}

function navMouseOver(topLevelNavLinkId, dropDownId, onHomeOrCategory) {
  $(dropDownId).style.display = 'block';
  $(topLevelNavLinkId).addClassName(onHomeOrCategory);
}

function navMouseOut(topLevelNavLinkId, dropDownId, onHomeOrCategory) {
  $(dropDownId).style.display = 'none';
  if(onHomeOrCategory) {
    $(topLevelNavLinkId).removeClassName(onHomeOrCategory);
  } else {
    $(topLevelNavLinkId).removeClassName('on_home');
  }
}

function showElement(elementId) {
  if ($(elementId)) {
    $(elementId).style.display='block';
  }
}

function hideElement(elementId) {
  if ($(elementId)) {
    $(elementId).style.display='none';
  }
}

function checkUncheckBoxes(element, check){
  var boxes = element.select('input.checkbox');
  if(check) {
    boxes.each(function(box) {box.checked = true; addHiddenField(box);});
  } else {
    boxes.each(function(box) {box.checked = false; removeHiddenField(box);});    
  }
}

function cloneElement(el) {
  var clone = el.cloneNode(true);
  $(el).insert({after: clone});
  return clone;
}

function setCloneAttr(clone) {
  var dropdowns = $('recat_form').select('.selectCategory'); 
  index = dropdowns.indexOf(clone);
  clone.id = 'category_ids_' + index;
  clone.name = 'category_ids[' + index + ']';
}

function uncheckBox(box1, box2){
  if(box1.checked && box2.checked) {
    box2.checked = false;
  }
}

function addHiddenField(el) {
  if (!$('recat_' + el.id)) {
    var hiddenField = $('recat_clone').cloneNode(true);
    hiddenField.id = 'recat_' + el.id;
    hiddenField.name = 'recat_this[]';
    hiddenField.value = el.value;
    $('recat_form_options').insert({after: hiddenField});
  }
}

function removeHiddenField(el) {
  if ($('recat_' + el.id)) Element.remove($('recat_' + el.id));
}

function checkRecatDropdown(event) {
  var dropdowns = $$('#dropDowns select');
  var selected = false;
  dropdowns.each(function(dd) {
    if (dd.selectedIndex != 0) {
      selected = true;
      return;
    }
  });
  if (selected) {
    return;
  } else {
    $('flash').innerHTML = '<div class="errorDiv">Please select a category.</div>';
    Event.stop(event);
  }
}

function togglePasswordUpdateDialog() {
  var up = $('update_password');
  (up.style.display == '') ? up.style.display = 'none' : up.style.display = '';
  // clear password input
  $('user_password').value = '';
  $('user_password_confirmation').value = '';
}

function toggleZipCodeDisplay(country_field) {
  $('zip_code').style.display = ((country_field.value=='United States') ? '' : 'none');
}

function onEndCrop( coords, dimensions ) {
    $( 'x1' ).value = coords.x1;
    $( 'y1' ).value = coords.y1;
    $( 'width' ).value = dimensions.width;
    $( 'height' ).value = dimensions.height;
}

function createCropper(){
  new Cropper.Img('image_to_be_cropped',
                  { minWidth: 100,
                    minHeight: 63,
                    ratioDim: { x: 456,
                                y: 286 },
                    displayOnInit: true,
                    onloadCoords: { x1: 0,
                                    y1: 0,
                                    x2: 456,
                                    y2: 286},
                    onEndCrop: onEndCrop});
}

function ativaOptionsDisabled(){
  if (Utils.isIE) {
    var sels = document.getElementsByTagName('select');
    for(var i=0; i < sels.length; i++){
      sels[i].onchange= function(){ //pra se mudar pro desabilitado
        if(this.options[this.selectedIndex].disabled){
          if(this.options.length<=1){
              this.selectedIndex = -1;
          }else if(this.selectedIndex < this.options.length - 1){
              this.selectedIndex++;
          }else{
              this.selectedIndex--;
          }
        }
      }
      if(sels[i].options[sels[i].selectedIndex].disabled){
        //se o selecionado atual desabilitado chamo o onchange
        sels[i].onchange();
      }
      for(var j=0; j < sels[i].options.length; j++){ //colocando o estilo
        if(sels[i].options[j].disabled){
          sels[i].options[j].style.color = '#CCC';
        }
      }
    }
  }
}

function cancelLink(element, form) {
  if (confirm('Would you like to cancel without saving?')) {
    $('flash_error_' + element).innerHTML = '';
    $(element).hide();
    $(form).reset();
  }
}

/* This is for slideshows and bigdaddy tracking only */
Rgm.triggerSlideshowAnalyticsTracking = function(page){
	Rgm.triggerSlideshowOmnitureTracking(page);
	Rgm.triggerGoogleTracking(page);
}

/* expect pageName to be alpha## and strips out the ## and replaces with the new page number sent in as the page parameter */
Rgm.triggerSlideshowOmnitureTracking = function(page) {
	if(typeof(s) != "undefined" && s.pageName){
		if (page != undefined) {
			var matchData = s.pageName.match(/(.*\D)\d+/);
			if (matchData) {
				var url = matchData[1] + page; /* strip page number from end and replace with page */
				s.pageName = s.eVar9 = url;
				s.t(); // invoke omniture tracking
			}
		} else {
			s.t();
		}
	}
}

Rgm.triggerGoogleTracking = function(page) {
  if(typeof(pageTracker) != "undefined") {
		if (page != undefined) {
			pageTracker._trackPageview(page); // invoke google tracking
		} else {
			pageTracker._trackPageview();
		}
  }
}

/* this currently pokes omniture only */
Rgm.trackAjaxCall = function(page_name_extension) {
	if(typeof(s) != "undefined" && s.pageName){
		var cloned_s = Object.clone(s);
		if (page_name_extension) {
			cloned_s.pageName = cloned_s.eVar9 = cloned_s.pageName + ":" + page_name_extension;
			cloned_s.t();
		}
	}
}

Rgm.ping_widget_ads = function() {
  Rgm.ord = Math.random()*100000000000000000;
  var selectors = $H(double_click_ads).keys();
  for(i = 0; i < selectors.length; ++i) {
    var selector = selectors[i];
    Rgm.pingAd(selector);
  }
};

Rgm.pingAd = function(selector) {
  try {
    var ad_area = $$(selector)[0];
    var ad_script = '<script src="'+Rgm.adUrlFor(selector)+'" onload="document.close();"></script>';
    if($(ad_area) != null) {
      var iframe_id = 'iframe.iframe_for_div_' + selector.sub(/^div[\.|#]/, '');
      var iframe = $(ad_area).down(iframe_id);
      if (iframe) {
        //  Clear contents of the parent div, as some rich ads live outside of that iframe.
        $(iframe).up().update(iframe);
      } else {
        // ad area does not have an iframe. Double-click ads call document.write(), so for javascript to cycle the double-click ad, it must be in an iframe, thus create one
        iframe = new Element('iframe', {'class': 'iframe_for_div_' + selector.sub(/^div[\.|#]/,''), 'scrolling': 'no', 'frameborder': '0', 'marginwidth': '0', 'marginheight': '0', 'onload': 'document.close();'});
        var width = '';
        var height = '';
        ad_script.scan(/sz=(\d+)x(\d+)/, function(match) { width = match[1]; height = match[2];});
        iframe.writeAttribute('width', width);
        iframe.writeAttribute('height', height);
        $(ad_area).update(iframe);
      }
      var doc;
      if(iframe.contentWindow) {
        doc = iframe.contentWindow.document;
      } else {
        doc = iframe.contentDocument;
      }
      doc.body.innerHTML = "";

      if(iframe.style.width == "0px") {
        //  Some ads shrink the original iframe to 0px.  These seem to be the rich ads, like above.
        iframe.style.width = "";
        iframe.style.height = "";
      }
      iframe.show();
      doc.write(ad_script);
    }
  } catch(e) {}
};

Rgm.iframesFor = function(selector) {
  var iframe_id = '.iframe_for_' + selector.replace(/\./, '_').replace(/#/, '_');
  var iframe = $$(iframe_id);
  return iframe;
};

Rgm.adUrlFor = function(selector) {
  var url = double_click_ads[selector];
  url = url.replace(/ord=/,'ord=' + Rgm.ord);
  return url;
};

Rgm.stacktrace = function() {
 re = /function\W+([\w-]+)/i;

 var f = arguments.callee;
 var s = "";
 while (f)
 {
  s += (re.exec(f))[1] + '(';

  for (i = 0; i < f.arguments.length - 1; i++)
  {
   s += "'" + f.arguments[i] + "', ";
  }

  if (arguments.length > 0)
  {
   s += "'" + f.arguments[i] + "'";
  }

  s += ")\n\n";

  f = f.arguments.callee.caller;
 }
 alert(s);
}

// When users upload photos, they may be required to crop the photo before they can submit the article
// these functions enable and disable the submit for publication button.
// Built explicitly for an image submit button with ID article_submit
Rgm.enableSubmitForPublication = function() {
  if ($('article_submit')) {
    $('article_submit').src="/images/buttons/submit_for_publication.png";
    $('article_submit').disabled=null;
  }
}
Rgm.disableSubmitForPublication = function() {
  if ($('article_submit')) {
    $('article_submit').src="/images/buttons/submit_for_publication_disabled.png";
    $('article_submit').disabled="true";
  }
}

