// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
Object.extend(String.prototype, {
  upcase: function() {
    return this.toUpperCase();
  },

  downcase: function() {
    return this.toLowerCase();
  },

  strip: function() {
    return this.replace(/^\s+/, '').replace(/\s+$/, '');
  },

  toInteger: function() {
    return parseInt(this);
  },

  toSlug: function() {
    return this.strip().downcase().replace(/[^-a-z0-9~\s\.:;+=_]/g, '').replace(/[\s\.:;=+]+/g, '-');
  }
});

String.prototype.humanize = function() {
  split = this.split(/[\s_]/);
  result = "";
  for(i = 0, len = split.length; i < len; i++) {
    word = split[i];
    newFirstLetter = word[0].toUpperCase();
    newWord = newFirstLetter + word.substr(1);
    result += newWord;
    if(i < (len - 1)) {
      result += " ";
    }
  }
  return result;
}

function showInstantEmailUpdatesForm() {
  try {
    Effect.BlindUp('invite');
  } catch(e) {
    // Fail Silently.
  }
  Effect.BlindDown.delay(1, 'invite_form');
  window.location = '#instant_email_updates_top';
}

function showEvent(id) {
  // new Ajax.Updater('event', '/event-details/' + id, {
  //     parameters: { 'authenticity_token' : AUTH_TOKEN }
  //   });
  new Ajax.Updater('event', '/event_details/' + id, {
    parameters: { '_method' : 'get' }
  });
  
  if(currentlyVisible != null) {
    Element.removeClassName('event_clickable_' + currentlyVisible, 'selected');
    currentlyVisible = id;
    Element.addClassName('event_clickable_' + currentlyVisible, 'selected');
  } else {
    currentlyVisible = id;
    Element.addClassName('event_clickable_' + currentlyVisible, 'selected');
  }
  
}

function showCommittee(id) {
  
  if(currentlyVisibleID != null) {
    Element.removeClassName('committee-link-' + currentlyVisibleID, 'highlight');
    // $('committee-link-' + currentlyVisibleID).up(1).removeClassName('highlight');
  }
  
  new Ajax.Updater('event', '/committee_details/' + id, {
    parameters: { '_method' : 'get' }
  });
  
  currentlyVisibleTab = 'overview';
  currentlyVisibleID = id;
  
  Element.addClassName('committee-link-' + currentlyVisibleID, 'highlight');
  // $('committee-link-' + currentlyVisibleID).up(1).addClassName('highlight');
  
  // if(currentlyVisible != null) {
  //   Element.removeClassName('event_clickable_' + currentlyVisible, 'selected');
  //   currentlyVisible = id;
  //   Element.addClassName('event_clickable_' + currentlyVisible, 'selected');
  // } else {
  //   currentlyVisible = id;
  //   Element.addClassName('event_clickable_' + currentlyVisible, 'selected');
  // }
  
}

function dismissShadowboxAndRedirectTo(path) {
  window.parent.location = path;
}

function showTab(id) {
  Element.removeClassName(currentlyVisibleTab + '_tab', 'active');
  $(currentlyVisibleTab).hide();
  $(id).show();
  Element.addClassName(id + '_tab', 'active');
  currentlyVisibleTab = id;
}

function setupTheDealAccordions() {
  loc = window.location;
  var idToShow = 1;
  if(loc.hash != '') {
    id = loc.hash.substr(1);
    
    if(id == "travel") {
      idToShow = 1;
    } else if(id == "mentorship") {
      idToShow = 2;
    } else if(id == "activities") {
      idToShow = 3;
    } else if(id == "community") {
      idToShow = 4;
    } else if(id == "annualretreat") {
      idToShow = 5;
    } else {
      idToShow = 1;
    }
  }
  
  accordion = new Accordion("the_deal", idToShow);
  
}

function showTimelineYear(id) {
  if(currentlyVisibleTimeline == null) {
    Effect.Appear('year_' + id);
  } else {
    Effect.Fade(currentlyVisibleTimeline);
    Effect.Appear.delay(1, 'year_' + id);
  }
  
  currentlyVisibleTimeline = 'year_' + id;
}

function closeTimelineYear(id) {
  if(currentlyVisibleTimeline == null) {
    // Don't do anything
  } else {
    Effect.Fade(currentlyVisibleTimeline);
  }
  
  currentlyVisibleTimeline = null;
}

function emailToAFriend() {
  $('email_to_a_friend').submit();
}

function showSlideshowPhoto(id) {
  $('slideshow-' + currentlyVisible).hide();
  $('slideshow-' + currentlyVisible).removeClassName('active');
  $('slideshow-' + id).show();
  $('slideshow-' + id).addClassName('active');
  currentlyVisible = id;
}

function showPreviousSlideshowPhoto() {
  if(currentlyVisible != 1) {
    show = currentlyVisible - 1;
    $('slideshow-' + currentlyVisible).hide();
    $('slideshow-' + currentlyVisible).removeClassName('active');
    $('slideshow-' + show).show();
    $('slideshow-' + show).addClassName('active');
    currentlyVisible = show;
  } else {
    $('slideshow-1').hide();
    $('slideshow-1').removeClassName('active');
    $('slideshow-6').show();
    $('slideshow-6').addClassName('active');
    currentlyVisible = 6;
  }
}

function showNextSlideshowPhoto() {
  if(currentlyVisible != 6) {
    show = currentlyVisible + 1;
    $('slideshow-' + currentlyVisible).hide();
    $('slideshow-' + currentlyVisible).removeClassName('active');
    $('slideshow-' + show).show();
    $('slideshow-' + show).addClassName('active');
    currentlyVisible = show;
  } else {
    $('slideshow-6').hide();
    $('slideshow-6').removeClassName('active');
    $('slideshow-1').show();
    $('slideshow-1').addClassName('active');
    currentlyVisible = 1;
  }
}

var glossary = null;
var glossaryItems = new Array();
var glossaryWords = new Array();
var glossarySections = ['#featured_news_article span.teaser',
                        '#recent_news_articles span.content',
                        'div.news_individual div.summary',
                        'div.news_individual div.full_story div.body'];
function setupGlossary() {
  new Ajax.Request('/glossary.json', {
    method: 'get',
    onSuccess: function(transport){
      // alert('running');
      
      data = transport.responseText;
      //alert("Received: " + data);
      // alert('about to eval');
      glossary = eval(data);
      // debugger
      // alert('after eval');
      //alert("glossary: " + glossary)
      
      for(i = 0; i < glossary.length; i++) {
        name = glossary[i].glossary_item.name;
        body = glossary[i].glossary_item.body;
        
        glossaryWords[i] = name;
        glossaryItems[name] = body;
      }
      
      // Get the text inside items that can be glossary-ized, and then pass it accordingly.
      for(i = 0; i < glossarySections.length; i++) {
        
        var section = glossarySections[i];
        var items = $$(section);
        
        for(j = 0; j < items.length; j++) {
          var item = items[j];
          data = item.innerHTML;
          replacement = data.highlight(glossaryWords, glossaryReplacement);
          // item.innerHTML.replace(replacement);
          // Element.replace(item.innerHTML, replacement);
          item.innerHTML = replacement;
        }
      }
    }
  });
}

function glossaryReplacement(word, index) {
  lower = word.toLowerCase();
  replacement = "<span class='glossary-word'>" + word + "<span class='glossary-definition'><span>" + lower + ": " + glossaryItems[lower] + "</span></span></span>";
  return replacement;
}

function showAdditionalSignupFields(field) {
  if(field.checked){
    $('email_updates_additional_information').show();
  } else {
    $('email_updates_additional_information').hide();
  }
}

function warnIfLarger(field, max, warn, message) {
  value = parseInt(field.value);
  if(value > max) {
    $(warn).update(message);
  } else {
    $(warn).update("&nbsp;");
  }
}

function swapLoginFields() {
  textField = $('fake_password');
  passwordField = $('password');
  textField.hide();
  passwordField.show();
  passwordField.focus();
}

function unswapLoginFields() {
  passwordField = $('password');
  if(passwordField.value == '') {
    textField = $('fake_password');
    passwordField.hide();
    textField.show();
  }
}

function swapSidebarLoginFields() {
  textField = $('fake_password');
  passwordField = $('password');
  textField.hide();
  passwordField.show();
  passwordField.focus();
}

function unswapSidebarLoginFields() {
  passwordField = $('password');
  if(passwordField.value == '') {
    textField = $('fake_password');
    passwordField.hide();
    textField.show();
  }
}

function viewAllTags() {
  $("top_fifty_tags").hide();
  $("all_tags").show();
}

function showTopTags() {
  $("all_tags").hide();
  $("top_fifty_tags").show();
}

function showValidationError(errorTarget, errorMessage) {
  errorTarget = $(errorTarget);
  errorTarget.innerHTML = errorMessage;
  errorTarget.addClassName('error');
  errorTarget.removeClassName('small');
}

function resetValidationError(errorTarget) {
  errorTarget = $(errorTarget);
  errorTarget.innerHTML = "&nbsp;";
}

function trimNumber(s) {
  return s.replace(/^0+/, '');
} 

function validateStartTime(fieldName, minHour, minMinute, outOfBoundsMessage) {
  h = trimNumber($("room_request_" + fieldName + "_4i").value);
  mVal = $("room_request_" + fieldName + "_5i").value;
  if(mVal == "00") {
    m = "0";
  } else {
    m = trimNumber(mVal);
  }
  t = $("room_request_" + fieldName + "_6i").value;

  hInt = parseInt(h);
  mInt = parseInt(m);
  if(isNaN(hInt) || isNaN(mInt)) {
    showValidationError(fieldName + "_error", "This field requires a valid entry.");
    return false;
  } else {
    if((t == "0") && ((hInt < minHour) || ((hInt == minHour) && (mInt < minMinute)))) {
      showValidationError(fieldName + "_error", outOfBoundsMessage);
      return false;
    } else {
      resetValidationError(fieldName + "_error");
      return true;
    }
  }
}

function validateEndTime(fieldName, maxHour, maxMinute, outOfBoundsMessage) {
  h = trimNumber($("room_request_" + fieldName + "_4i").value);
  mVal = $("room_request_" + fieldName + "_5i").value;
  if(mVal == "00") {
    m = "0";
  } else {
    m = trimNumber(mVal);
  }
  t = $("room_request_" + fieldName + "_6i").value;

  hInt = parseInt(h);
  mInt = parseInt(m);
  if(isNaN(hInt) || isNaN(mInt)) {
    showValidationError(fieldName + "_error", "This field requires a valid entry.");
    return false;
  } else {
    if(((t == "1") && (hInt != 12)) && ((hInt > maxHour) || ((hInt == maxHour) && (mInt > maxMinute)))) {
      showValidationError(fieldName + "_error", outOfBoundsMessage);
      return false
    } else {
      resetValidationError(fieldName + "_error");
      return true;
    }
  }
}

function validateRoomRequestForm() {
  errorFree = true;
  
  // Validate all fields which require simple text entry
  requirePresent = ['sponsoring_organization', 'address_line_one', 'city', 'state', 'zip_code', 'contact_name', 'contact_title', 'phone_number', 'fax_number', 'email_address', 'preferred_room_configuration', 'name_of_event', 'purpose_of_event', 'beverages_requested', 'caterer'];
  for(i = 0, len = requirePresent.length; i < len; i++) {
    errorName = requirePresent[i];
    fieldName = "room_request_" + errorName;
    val = $(fieldName).value;
    if(val == null || val == "") {
      errorFree = false;
      showValidationError(errorName + "_error", "This field requires a valid entry.");
    } else {
      resetValidationError(errorName + "_error");
    }
  }

  // Validate email address
  emailVal = $("room_request_email_address").value;
  emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  if(!emailPattern.test(emailVal)) {
    errorFree = false;
    showValidationError("email_address_error", "Invalid email address.")
  } else {
    resetValidationError("email_address_error");
  }
  
  // Validate date of event
  dateVal = $("room_request_date_of_event").value;
  dateRegexp = /^(January|February|March|April|May|June|July|August|September|October|November|December) ([0-9]{1,2}), 20([0-9]{2})$/;
  if(dateVal == null || dateVal == "") {
    errorFree = false;
    showValidationError("date_of_event_error", "This field requires a valid entry.");
  } else if(!dateRegexp.test(dateVal)) {
    errorFree = false;
    showValidationError("date_of_event_error", "Invalid format.");
  } else {
    resetValidationError("date_of_event_error");
  }

  // Validate number of participants
  numParticipants = $("room_request_number_of_participants").value;
  if(numParticipants == null || numParticipants == "") {
    errorFree = false;
    showValidationError("number_of_participants_error", "This field requires a valid entry.");
  } else {
    parsedVal = parseInt(numParticipants);
    // Ensure the value is numeric
    if(isNaN(parsedVal)) {
      errorFree = false;
      showValidationError("number_of_participants_error", "Must be a number.");
    } else if (parsedVal > 72) {
      errorFree = false;
      showValidationError("number_of_participants_error", "Must be 72 or less.");
    } else {
      resetValidationError("number_of_participants_error");
    }
  }

  // Validate that at least one equipment checkbox is checked
  equipmentValid = false;
  equipmentCheckBoxes = ['no_equipment_needed', 'freestanding_podium', 'dvd_player', 'podium_microphone', 'flip_chart', 'slide_projector', 'laptop', 'speakerphone', 'lavaliere_microphone', 'vcr', 'lcd_projector', 'wall_mounted_screen', 'overhead_projector', 'white_board'];
  for(i = 0, len = equipmentCheckBoxes.length; i < len; i++) {
    fieldName = "room_request_equipment_" + equipmentCheckBoxes[i];
    if($(fieldName).checked) {
      equipmentValid = true;
    }
  }
  if(!equipmentValid) {
    errorFree = false;
    showValidationError("equipment_list_error", "At least one item must be checked.");
  } else {
    resetValidationError("equipment_list_error");
  }

  // Validate times
  startTimeFields = ['meeting_start_time', 'room_access_start_time'];
  endTimeFields = ['meeting_end_time', 'room_access_end_time'];
  validTimes = true;
  if(validateStartTime("meeting_start_time", 8, 30, "Must be 8:30 AM or later.") && validateStartTime("room_access_start_time", 8, 0, "Must be 8:00 AM or later.") && validateEndTime("meeting_end_time", 4, 30, "Must be 4:30 PM or earlier.") && validateEndTime("room_access_end_time", 4, 30, "Must be 4:30 PM or earlier")) {
    // Do nothing
  } else {
    errorFree = false;
  }

  return errorFree;
}
