var Rgm = {};
Rgm.config = {};
Rgm.controls = {};
var double_click_ads = {};
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;
}

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_article/' + 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.setNewsletter = function()
{
  if (Rgm.isLoggedIn()) {
    $("logged_in_newsletter").style.display = "";
    $("logged_out_newsletter").style.display = "none";
  } else {
    $("logged_in_newsletter").style.display = "none";
    $("logged_out_newsletter").style.display = "";
  }
}
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)
{
  var fckEditor = new FCKeditor(elementId) ;
  fckEditor.Height        = desiredHeight;
  fckEditor.ToolbarSet    = toolbarSet;
  fckEditor.BasePath      = "/javascripts/third-party/fck_editor/" ;
  fckEditor.Config["CustomConfigurationsPath"] = "/javascripts/fck_editor_config.js"  ;
  fckEditor.Config["disableFontAndStyleDefinitions"] = !(Rgm.isEditor() || Rgm.isStaff());
  fckEditor.CheckBrowser  = true ;
  fckEditor.ReplaceTextarea() ;
}

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).setAttribute(htmlClassAttribute(), 'top_level_nav_link ' + onHomeOrCategory);
}

function navMouseOut(topLevelNavLinkId, dropDownId) {
  $(dropDownId).style.display = 'none';
  $(topLevelNavLinkId).setAttribute(htmlClassAttribute(), 'top_level_nav_link');
}

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

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

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();
  }
}

Rgm.triggerOmnitureTracking = 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;
				s.pageName = s.eVar9 = url;
				s.t(); // invoke omniture tracking
			}
		} else {
			s.t();
		}
	}
}

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.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);
}
