document.observe("dom:loaded", function() {
  
  
  // Resize user forum thread images that are too big
  $$("td.forum_message img").each(function(i){
    Ebaby.scaleImage(i, 430);
  });
  

  // Replacement for target="_blank" that's XHTML compliant
  $$("a").each(function(anchor) {
    if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
      Event.observe(anchor, 'click', function(e) {
        window.open(anchor.getAttribute("href"));
        Event.stop(e);
      });
    }
  });
  
  
  // For go super page rollovers
  if ($('gs_1')) {
    $R(1,10).each(function(i) {
      var li = 'gs_' + i;
      $(li).onmouseover = function() { this.addClassName('no_bg'); }
      $(li).onmouseout = function() { this.removeClassName('no_bg'); }
    });
  }


  // Toggle mailbox delete checkboxes
  if ($('mailbox_delete')) {
    Event.observe('mailbox_delete_link', 'click', function() {
      // Toggle checkboxes
      $$('form#mailbox_delete input').each(function(i){
        i.checked == true ? i.checked = false : i.checked = true;
      });
    });
  }
  
  // Toggle mailbox delete checkboxes
  if ($('select_all_mail')) {
    Event.observe('select_all_mail', 'click', function() {
      // Toggle checkboxes
      $$('form#mailbox_delete input').each(function(i){
        i.checked == true ? i.checked = false : i.checked = true;
      });
    });
  }
  
  // Toggle my vocab checkboxes
  if ($('my_vocab_words')) {
    Event.observe('vocab_remove_checks', 'click', function() {
      // Toggle checkboxes
      $$('table#my_vocab_words input.check_delete').each(function(i){
        i.checked == true ? i.checked = false : i.checked = true;
      });
    });
  }
  
  
  // For client demo page (ELS)
  if ($('els_content')) {
    $$('div#els_content a').each(Ebaby.killLinks);
    // Prevent float issue in IE
    $$('div.member_reviews img').each(function(i) {
        i.alt = '';
    });
  }
  
  
  // Lesson main page search toggle
  if ($('exp_search')) { 
    $('exp_search_default').selected = true; 
    $('grammar_default').selected = true;
    $('themes_default').selected = true;
    $('keywords').value = '';
    $('author').value = ''; 
    $('search_type').onchange = function() {
      Ebaby.turnOn(this.value);
    }
  }
  
  
  // Listening quiz
  if ($('quiz_reset')) {
    Event.observe('quiz_reset', 'click', function() {
      $$('div#quiz span').each(function(i){
        Element.removeClassName(i, 'correct');
        Element.removeClassName(i, 'incorrect');
      });
      $$('div#quiz input').each(function(i){
        if (i.checked) {
          i.checked = false;
        }
      });
    });
  }
  
  // Insert line-break for long member names in threads
  $$('td.forum_thread_member p strong a', 'div.member_reviews td p strong a').each(Ebaby.shortenNames);
  $$('td.forum_thread_member img', 'div.member_reviews table th img').each(Ebaby.clearLongAlts);
  
  
  // Toggle 'add new photo album' option in My Photo
  if ($('new_album')) {
    Ebaby.toggleWithEffect('new_album', 'new');
  }
  
  // Toggle 'add new image' option in My Photo
  if ($('new_image')) {
    Ebaby.toggleWithEffect('new_image', 'new_image_field');
  }
  
  // Chat popup
  if ($('chat_form')) {
    $('chat_form').target = 'chat_pop';
    Event.observe('chat_form', 'submit', function(e) {
      window.open('/community/launch_chat', 'chat_pop', 'location=0, width=990, height=810, scrollbars=1');
      $('chat_form').target = 'chat_pop';
      Event.stop(e);
      $('chat_form').submit();
    });
  }
  
  
  // Temp Alert
  if ($('temp_promo')) {
    var state;
    var obj = $('temp_promo');
    state = (state == null) ? 'visible' : state;
    obj.className = state;

    Event.observe('hide_box', 'click', function(e){
      obj.className = (obj.className == 'invisible') ? 'not_invisible' : 'invisible';
      state = obj.className;
      setPromoCookie();
      return false;
    });

    function setPromoCookie() {
      var exp = new Date();
      plusMonth = exp.getTime() + (31*24*60*60*1000);
      exp.setTime(plusMonth);
      document.cookie = 'State=' + state + ';expires=' + exp.toGMTString();
    }

    function readPromoCookie() {
      if (document.cookie) {
        var tmp = document.cookie.split(';');
        tmp.each(function(i) {
          i = i.split('=');
          i[0] = Ebaby.trim(i[0]);
          if(i[0] == 'State') {
            state = i[1];
            obj.className = state;
          }
        });
      }
    }

    readPromoCookie();
  }
  
  // Sign up grid
  if ($$('table#sug')) {
    
    // $$('table#sug tbody p').each(function(i){
    //   i.addClassName("invisible");
    // });
    
    $$('table#sug tbody a').each(function(i){
        var desc = i.next(0);
        desc.addClassName("invisible");
        // parent cell of link
        var cell = i.up();
        // parent cell of checkmark
        var checkCell = i.up().next("td");
        // the link
        var link = i;
        // the checkmark
        var checkmark = checkCell.descendants()[0];
        // Trigger on hover over th cell
        Event.observe(cell, 'mouseover', function() {
          // hide the feature description
          desc.removeClassName("invisible");
          // hide the checkmark
          checkmark.hide();
          checkCell.insert(desc);
        });
        Event.observe(cell, 'mouseout', function() {
          desc.addClassName("invisible");
          checkmark.show();
        });
    });
    
  };
  
  
  // Truncate usernames in forum topics page to fit
  $$('p.forum_topic_thumb strong a.show_member_username').each(function(i){
    i.innerHTML = Ebaby.shortenNamesWithEllipses(i.innerHTML, 10);
  });
  
  // Crop/scale thumbs to 30px square
  $$('span.forum_topic_thumb_restraint img').each(function(i){
    Ebaby.cropSquareAndScale(i, 30);
  });
  
  // Crop/scale thumbs to 30px square
  $$('span.thumb_list1 img').each(function(i){
    Ebaby.cropSquareAndScale(i, 30);
  });
  
  // Indent activity feed info without having to manually add DIV's to every single activity
  // Remove blank activity feed li's
  $$('ul.activity_feed li').each(function(i){
    if (i.empty()) {
      i.remove();
    }
    i.insert({ top : '<div class="feed_height"></div>' });
    i.insert({ bottom : '<div class="clear"></div>' });
  });
  
});


// Random number for cache-busting Doubleclick
function cacheBuster(url) {
  var axel = Math.random() + "";
  var num = axel * 1000000000000000000;
  document.write('<img src="' + url + num + '?" alt="" />');
}


Ebaby = { // Start Ebaby
  
  
  trim : function(str, chars) {
  	return Ebaby.ltrim(Ebaby.rtrim(str, chars), chars);
  },
  
  
  ltrim : function(str, chars) {
  	chars = chars || "\\s";
  	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
  },
  
  
  rtrim : function(str, chars) {
  	chars = chars || "\\s";
  	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
  },
  
  
  // Clear alt tags when username is too long
  clearLongAlts : function(i) {
    if (i.alt.length > 10) {
      i.alt = '';
    }
  },
  
  
  // Shorten long usernames by inserting line-break
  shortenNames : function(i) {
    if (i.innerHTML.length > 10) {
      i.innerHTML = i.innerHTML.substr(0,10) + '<br />' + i.innerHTML.substr(10);
    }
  },
  
  
  // Shorten long usernames by truncating and adding ...
  shortenNamesWithEllipses : function(i, length) {
    if (i.length > length) {
      i = i.substr(0, length);
      i += "&hellip;";
    }
    return i;
  },
  
  
  // Clear href from links and prevent them from going anywhere
  killLinks : function(i) {
    i.href = 'javascript:void(0);';
    Event.observe(i, 'click', function(e) {
      Event.stop(e);
    });
  },
  
  
  // Toggle with effect
  toggleWithEffect : function(object, target) {
    Event.observe(object, 'click', function(e) {
      $(target).hasClassName('visible') ? $(target).removeClassName('visible') : $(target).addClassName('visible');
      $(target).hasClassName('invisible') ? $(target).removeClassName('invisible') : $(target).addClassName('invisible');
      new Effect.Highlight('album_label', { duration:0.5, startcolor:'#FFFAD3', endcolor:'#FFFFFF' } );
      Event.stop(e);
    });
  },
  
  
  // For lessons main page search
  turnOn : function(this_one) {
    var dropdowns = [ $('category_drop'), 
                      $('grammar_drop'), 
                      $('theme_drop'), 
                      $('keyword_drop'), 
                      $('date_drop'), 
                      $('author_drop') ];
    dropdowns.each(function(dropdown) {
      dropdown.style.display = "none";
    });
    Effect.toggle(this_one, 'appear', { duration: 0.5 });
  },
  
  
  // Scale to fit divs
  scaleImage : function(i, width) {
    w = i.width;
    h = i.height;
    if (w > width) {
      // Scale width at same ratio
      h =  h/(w/width);
      i.setAttribute("width", width);
      i.setAttribute("height", Math.round(h));
      Element.insert(i, { before : "<br />" }); // Has to do this because IE6 won't display image as block
    }
  },
  
  
  // Clear alts on tiny thumbnails to prevent IE layout issues while images are rendering
  // Also scales to 30px wide or tall depending on smallest side and centers image
  cropSquareAndScale : function(i, size) {
    i.alt = '';
    var width = i.width;
    var height = i.height;
    if (width > height) {
      i.setAttribute("height", size); 
      var newWidth = i.width;
      i.setStyle({ left: '-' + Math.round((newWidth - size)/2) + 'px' })
    } else if (height > width) {
      i.setAttribute("width", size);
      var newHeight = i.height;
      i.setStyle({ top: '-' + Math.round((newHeight - size)/2) + 'px' });
    } else {
      i.setAttribute("height", size); 
    }
  }

  
} // End of Ebaby


// ReCAPTCHA Theme
var RecaptchaOptions = {
   theme : 'white'
};


// Scroll to top
function backToTop(coordinates) {
  if (coordinates > 0) {
    var x1 = x2 = x3 = 0;
    var topOfPage = coordinates
    var y1 = y2 = y3 = topOfPage;
    if (document.documentElement) {
        x1 = document.documentElement.scrollLeft || 0;
        y1 = document.documentElement.scrollTop || topOfPage;
    }
    if (document.body) {
        x2 = document.body.scrollLeft || 0;
        y2 = document.body.scrollTop || topOfPage;
    }
    x3 = window.scrollX || 0;
    y3 = window.scrollY || topOfPage;
    var x = Math.max(x1, Math.max(x2, x3));
    var y = Math.max(y1, Math.max(y2, y3));
    window.scrollTo(Math.floor(x / 2), Math.floor(y / 2));
    if (x > 0 || y > topOfPage) {
        window.setTimeout("backToTop()", 25);
    }
  }
}


var flagged_state = 'unchecked';
function toggle_select() {
  field = document.theform['flagged[]'];
  if (flagged_state == 'unchecked') {
    if (field.length) {
      for (i = 0; i < field.length; i++) {
        field[i].checked = true;
      }
    } else {
      field.checked = true;
    }
    flagged_state = 'checked';
  } else {
    if (field.length) {
      for (i = 0; i < field.length; i++) {
        field[i].checked = false;
      }
    } else {
      field.checked = false;
    }
    flagged_state = 'unchecked';
  }
}
