// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// Onload wrapper: any previously added onload functions will be
// executed first.
// http://simon.incutio.com/archive/2004/05/26/addLoadEvent
// usage:
// addLoadEvent(nameOfSomeFunctionToRunOnPageLoad);
// addLoadEvent(function() {
//    /* more code to run on page load */
// });



window.is_focused = true;
window.onblur   = function() {window.is_focused = false;}
window.onfocus  = function() {window.is_focused = true;}



function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  }
  else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function handle_search_forest_widget() {
  sel = document.getElementById('id_selector');
  val = sel.options[sel.selectedIndex].value;

  if (val == '0') {
    document.location.href = '/family-tree/forest';
  } else {
    document.getElementById('search_selector_form').submit();
  }
}

function handle_forest_widget(field_name) {
  if (field_name == null) field_name = 'id';

  sel = $(field_name);
  id  = sel.options[sel.selectedIndex].value;

  if (id == '0') {
    document.location.href = '/family-tree/forest';
  } else {
    document.getElementById('forest_widget_form').submit();
  }
}

function closeAllDropdowns() {
  // redefined if you insert <%= auto_close_dropdowns %> in the view after all dropdowns have been created.
}

function handle_forest_action(user_id) {
  sel = document.getElementById("action_"+user_id);
  val = sel.selectedIndex;
  switch(val) {
  // view tree
  case 1:
    document.location.href = '/family-tree/index/'+user_id;
    break;
  // view list
  case 2:
    document.location.href = '/family-tree/family_list/'+user_id;
    break;
  // view index
  case 3:
    document.location.href = '/family-tree/names/'+user_id;
    break;
  // search
  case 4:
    document.location.href = '/family-tree/search/'+user_id;
    break;
  // GEDCOM export
  case 5:
    document.location.href = '/family-tree/export/'+user_id;
    break;
  }
}

function toggleDisplay(id) {
  state = document.getElementById(id).style.display;
  if(state == "block") {
    document.getElementById(id).style.display = "none";
  }
  if(state == "none") {
    document.getElementById(id).style.display = "block";
  }
}

function toggleTwo(element1, element2) {
  Element.toggle(element1);
  Element.toggle(element2);
}

function setDisplay(id, display_setting) {
  document.getElementById(id).style.display = display_setting;
}

function setBackgroundColor(id, background_color_setting) {
  document.getElementById(id).style.backgroundColor  = background_color_setting;
}

Ajax.Responders.register({
  onCreate: function() {
    if($('busy') && Ajax.activeRequestCount > 0) {
      Effect.Appear('busy', {duration:0.2, queue:'end'});
    }
  },
  onComplete: function() {
    if($('busy') && Ajax.activeRequestCount == 0) {
      Effect.Fade('busy', {duration:0.1, queue:'end'});
    }
  }
});

var address_importer_panel;
function openCard(url) {
  if(!address_importer_panel) {
    address_importer_panel = new Panel({
      panelId:'lightbox',
      displayOverlay:true
    })
  }
  address_importer_panel.open().update(url);
}


function closeCard(reload) {
  address_importer_panel.close();
  // no default parameter, so undefined means true
  if (undefined == reload || reload) window.location.reload();
}

function closeCardWithOptionalReload(form_obj) {
  lightbox.prototype.deactivate();

  if (form_obj.called_save_flag.value == "1") {
    if (form_obj.called_from_flash.value == "1") {
      flashProxy.call('tweenToTree');
    } else {
      window.location.reload();
    }
  }
}

// Returns a data structure containing first, last, email
// accessed as: conactInfo.first_name, contactInfo.last_name, contactInfo.email
function returnSelectedContact(id) {
  var contactInfo = {
    "first" : $F('fn_'+id),
    "last"  : $F('ln_'+id),
    "email" : $F('email_'+id)
  };
  return contactInfo;
}

// Returns a string of selected email addresses
function returnMultipleSelectedContacts(class_name) {
  allNodes = document.getElementsByClassName(class_name);
  output = [];
  for(i = 0; i < allNodes.length; i++) {
    if ( allNodes[i].checked == true ) {
      output.push(allNodes[i].value);
    }
  }
  return output.join(', ');
}

// Clears the value of element if it equals text
// This is generally tied to the onclick callback to clear default values of textboxes (see search or comments)
function clearIf(element, text) {
  if (element.value == text) {
   element.value = "";
  }
}

// Sets the style of standard buttons
function buttonMouseOver(element) {
  element.style.color = "black";
  element.style.cursor = "pointer";
}

function buttonMouseOut(element) {
  element.style.color = "white";
  element.style.cursor = "pointer";
}

// If current partner is selected, sets all others to former
function resolvePartnerTypes( element_at_hand, ids ) {
  var arry = new Array();
  arry = ids.split(',');

  if (element_at_hand.selectedIndex == 0) {
    for(i=0; i<arry.length; i++) {
      temp_element = $(arry[i]);
      if (temp_element.id != element_at_hand.id) {
        if (temp_element.selectedIndex == 0) {
          temp_element.selectedIndex = 1;
        }
      }
    }
  }
}

function checkAll(class_name, check_flag) {
  allNodes = document.getElementsByClassName(class_name);
  if (check_flag == false) {
    for(i = 0; i < allNodes.length; i++) {
      allNodes[i].checked = false;
    }
  } else {
    for(i = 0; i < allNodes.length; i++) {
      allNodes[i].checked = true;
    }
  }
}

// If field named field_name is not empty, ", " will be appended to the contents
function prepFieldForAdditions(field_name) {
  if ( $F(field_name) != "" ) {
    $(field_name).value += ", ";
  }

}

function toggleIfEqual (element_to_toggle, element_to_compare, value_to_compare) {
  if ( $F(element_to_compare) == value_to_compare ){
    Element.toggle(element_to_toggle);
  }
}

function resolvePartnerFields(ii) {
  if (ii) { ii_string = "_" + ii };
  // First hide divorce fields
  Element.hide('divorce'+ii_string);
 // Element.hide('partnered'+ii_string);
  Element.hide('married'+ii_string);


  // Show divorce fields if partner is an ex-spouse
  //toggleIfEqual('married'+ii_string, 'partner'+ii_string, 'partner');
  //toggleIfEqual('married'+ii_string, 'partner'+ii_string, 'ex-partner');
  //toggleIfEqual('divorce'+ii_string, 'partner'+ii_string, 'ex-partner');
  toggleIfEqual('married'+ii_string, 'partner'+ii_string, 'spouse');
  toggleIfEqual('married'+ii_string, 'partner'+ii_string, 'ex-spouse');
  toggleIfEqual('divorce'+ii_string, 'partner'+ii_string, 'ex-spouse');
  toggleIfEqual('married'+ii_string, 'partner'+ii_string, 'fiance');


  // Change marriage date and location labels if engaged
  // First reset Married on/in labels
  $('marriage_date'+ii_string).innerHTML = "Married on";
  $('marriage_location'+ii_string).innerHTML = "Married in";
  $('divorce_date'+ii_string).innerHTML = "Divorced On";
  $('divorce_location'+ii_string).innerHTML = "Divorced In";

  // Next change Married on/in labels
  if ( $('partner'+ii_string).value.match(/fiance{1,2}/) ) {
    $('marriage_date'+ii_string).innerHTML = "Wedding date";
    $('marriage_location'+ii_string).innerHTML = "Wedding location";
  }

  //if ( $('partner'+ii_string).value.match(/partner/) ) {
  //  $('marriage_date'+ii_string).innerHTML = "Started on";
  //  $('marriage_location'+ii_string).innerHTML = "Started In";
  //  $('divorce_date'+ii_string).innerHTML = "Ended On";
  //  $('divorce_location'+ii_string).innerHTML = "Ended In";
  //}


}

function toggleCB(item) {
    cb = $(item);
    (cb.checked) ? cb.checked=false : cb.checked=true;
}

// Profile Index page

function checkEmailDetails() {
  var email_off = false;
  $$('#email_details input[type="checkbox"]').each(function(el) {if(el.checked){email_off = true;}});
  if (email_off) Effect.Fade('email_details', {duration:0.7})
}

// Recent Albums page

function selectAlbums(id) {
  var base_url = '/photo/recent_albums/'+id
  if ($('show_family').checked && ($('show_friends').checked)) {
    return base_url
  } else if ($('show_family').checked && !($('show_friends').checked)) {
    return base_url+'?family=1'
  } else if ($('show_friends').checked && !($('show_family').checked)) {
    return base_url+'?friends=1'
  } else {
    return base_url+'?none=1'
  }
}


// Profile Functions
function changeState(field, index, field_id) {
  if(index) {
    field_id = field+"_"+index
    field_name = field+"["+index+"]"
  } else if(field_id){
    field_name = field
  } else {
    field_id = field
    field_name = field
  }

  code = $F(field_id+"_country");
  new Ajax.Request("/options/dropdown_or_text?field=province&field_id="+field_id+"_state&field_name="+field_name+"[state]&scope="+code+"&value="+$(field_id+'_state').value+"&include_blank=1&no_code=1&label_name=State/Province",{
    onSuccess: function(request) {
      $(field_id+'_state').id = field_id+'_state_old';
      var newEl = new Insertion.Before(field_id+'_state_old',request.responseText);
      var elP = $(field_id+'_state_old').parentNode;
      elP.removeChild($(field_id+'_state_old'));
    }
  });
}


// Used by invite_others/choose_address_book
function select_url() {
  if ($RF('email_form','email_app').match(/^domain/)) {
    document.location.href = '/invite_others/webmail_form?domain='+$RF('email_form','email_app').split(/:/)[1]+'&family_or_friends='+$F('family_or_friends');
  } else {
    document.location.href = '/invite_others/contactfile_form?family_or_friends='+$F('family_or_friends');
  }
}

// Profile Gift Functions
function chooseGift(gift_id) {
  $('gift_option_id').value = gift_id + ''; // Needs to be a string, for very large IDs like 6000000000000003520?

  $$('div.gift_menu_item').each(function(item) {
    item.removeClassName('selected');
  });

  $('gift_menu_item_' + gift_id).addClassName('selected');

  $('selected_gift').update($('gift_menu_item_' + gift_id).innerHTML);

}

// Custom Dollar Functions

$S = function(form) {
  f = $(form) // Chrome loses the handle to $(form) after err
  try {
     if(f.onsubmit()!=false) f.submit()
  } catch(err) {
    f.submit();
  }
}

// Returns the value of the selected radio button in the radio group
//
// @param {radio Object} or {radio id} el
// OR
// @param {form Object} or {form id} el
// @param {radio group name} radioGroup
function $RF(el, radioGroup) {
  if($(el).type == 'radio') {
    var el = $(el).form;
    var radioGroup = $(el).name;
  } else if ($(el).tagName.toLowerCase() != 'form') {
    return false;
  }
  return $F($(el).getInputs('radio', radioGroup).find(
    function(re) {return re.checked;}
  ));
}


// Profile privacy checkbox logic

function checkboxOn(theCheckbox) {
  if (theCheckbox && !theCheckbox.checked) {
    theCheckbox.click();
  }
}

function checkboxOff(theCheckbox) {
  if (theCheckbox && theCheckbox.checked) {
    theCheckbox.click();
  }
}

function privacyCheckbox( name, network, group ) {
  return $(name + '|' + network + '|' + group);
}

function checkPrivacy( name, network, group ) {
  theCheckbox     = privacyCheckbox( name, network,           group );
  familyCheckbox  = privacyCheckbox( name, 'family',          group );
  extFamCheckbox  = privacyCheckbox( name, 'extended_family', group );
  friendsCheckbox = privacyCheckbox( name, 'friends',         group );
  publicCheckbox  = privacyCheckbox( name, 'public',          group );

  if ( name == 'view_full_profile' && theCheckbox.checked ) {
    checkboxOn( privacyCheckbox( 'view_profile_photo',    network, group ) );
    checkboxOn( privacyCheckbox( 'view_location',         network, group ) );
  }

  if ( name == 'add_to_node' && theCheckbox.checked ) {
    checkboxOn( privacyCheckbox( 'find_in_tree', network, group ) );
  }

  if ( name == 'find_in_tree' && !theCheckbox.checked ) {
    checkboxOff( privacyCheckbox( 'add_to_node',  network, group ) );
  }

  if ( !theCheckbox.checked && (name == 'view_profile_photo' || name == 'view_location') ) {
    checkboxOff( privacyCheckbox( 'view_full_profile', network, group ) );
  }

  if ( name == 'search_profile' ) {
    if (! theCheckbox.checked ) {
      if ( group.match(/^managed_/) ) {
        theCheckbox.checked = !confirmCheckbox(theCheckbox, '', 'This will prevent people from searching for profiles you have added. \nAre you sure you want to do this?');
      } else {
        theCheckbox.checked = !confirmCheckbox(theCheckbox, '', 'This will prevent anyone outside your infinite tree from searching for you. \nAre you sure you want to do this?');
      }
    }
  } else if ( name == 'view_profile_photo' || name == 'view_location' ) {
    if (! theCheckbox.checked ) {
      if ( group.match(/^managed_/) ) {
        theCheckbox.checked = !confirmCheckbox(theCheckbox, '', 'This will make it harder for people to search for profiles you have added.\nAre you sure you want to do this?')
      } else {
        theCheckbox.checked = !confirmCheckbox(theCheckbox, '', 'This will make it harder for anyone outside your family to search for you.\nAre you sure you want to do this?')
      }
    }
  }

  switch(network) {
  case 'public':
    // check all other boxes if Public is checked
    if ( publicCheckbox.checked ) {
      if ( familyCheckbox  ) familyCheckbox.checked  = true;
      if ( extFamCheckbox  ) extFamCheckbox.checked  = true;
      if ( friendsCheckbox ) friendsCheckbox.checked = true;
    }
    break;
  case 'extended_family':
    if ( extFamCheckbox.checked ) {
      // check Family if Extended Family is checked
      if ( familyCheckbox ) familyCheckbox.checked = true;
    } else {
      // uncheck Public if Extended Family is unchecked
      if ( publicCheckbox ) publicCheckbox.checked = false;
    }
    break;
  case 'friends':
    if ( !friendsCheckbox.checked ) {
      // uncheck Public if Friends is unchecked
      if ( publicCheckbox ) publicCheckbox.checked = false;
    }
    break;
  case 'family':
    if ( !familyCheckbox.checked ) {
      // uncheck Public and Extended Family if Family is unchecked
      if ( publicCheckbox ) publicCheckbox.checked = false;
      if ( extFamCheckbox ) extFamCheckbox.checked = false;
    }
    break;
  }
}

function togglePrivacyTray( tray_name ) {
  new Effect.toggle( tray_name, 'blind', {duration:.25});
  toggleTwo( $(tray_name+'_arrow_down'), $(tray_name+'_arrow_right') );
  toggleTwo( $(tray_name+'_expand_link'), $(tray_name+'_close_link') );
}


var privacy_groups = ['family','friends','extended_family','public'];
var parent_groups =  ['basic','photos','videos'];

var basic_group =  ['view_profile_photo','view_location','view_birthday','view_birthyear','view_birthplace','view_maiden','view_nicknames','view_occupation','view_email','view_last_login','view_joined_on'];
var photos_group = ['view_photos_of_me','view_photo_albums','view_photo_favorites'];
var videos_group = ['view_videos_of_me','view_my_videos','view_video_favorites'];

function invalidateParentCheckbox(parent,group,isParent) {
  if(isParent) return checkAllOrNone($(parent+'|'+group+'|'),parent,group);
  privacy_groups.each(function(privacy_group){
    var parentCheck = $(parent+'|'+privacy_group+'|');
    if(!parentCheck) return;
    var thirdState = $(parent+'_'+privacy_group+'_third_state');
    var checkbox_count = 0;
    var checked_sum = 0;
    this[parent+'_group'].each(function(el){
      if ($(el+'|'+privacy_group+'|') && !$(el+'|'+privacy_group+'|').disabled) {
        checkbox_count++;
        checked_sum += $(el+'|'+privacy_group+'|').checked || ($F(el+'|'+privacy_group+'|') == "on");
      }
    }.bind(this))
    if (checked_sum == 0) {
      if (thirdState.visible())
        $(parentCheck,thirdState).invoke('toggle');
      parentCheck.checked = false;
    } else if (checked_sum == checkbox_count) {
      if (thirdState.visible())
        $(parentCheck,thirdState).invoke('toggle');
      parentCheck.checked = true;
    } else {
      if (!thirdState.visible())
        $(parentCheck,thirdState).invoke('toggle');
    }
  }.bind(this))
}

function checkAllOrNone (checkbox,parent,group) {
  var ischecked = (checkbox.checked || checkbox.hasClassName('cb_third_state'));
  this[parent+'_group'].each(function(el){
    if ($(el+'|'+group+'|')) {
      if (!$(el+'|'+group+'|').disabled) $(el+'|'+group+'|').checked = ischecked;
      if ($(el+'|'+group+'|').type == "checkbox") $(el+'|'+group+'|').onclick();
    }
  }.bind(this))
  privacy_groups.each(function(group){
    invalidateParentCheckbox(parent,group);
  }.bind(this))
}

function setDefaultChecks() {
  parent_groups.each(function(parent_group){
    privacy_groups.each(function(privacy_group) {
      invalidateParentCheckbox(parent_group,privacy_group);
    }.bind(this));
  }.bind(this));
}

// Move and reveal a dialog
function moveDialog( dialog_id, theEvent, offsetX, offsetY, content ) {
  if ( offsetX === undefined ) offsetX = 0;
  if ( offsetY === undefined ) offsetY = 0;
  if ( content === undefined ) content = "";

  posX = Event.pointerX(theEvent);
  posY = Event.pointerY(theEvent);
  posX += offsetX;
  posY += offsetY;
  $(dialog_id).setStyle(
    {
    left:posX+"px",
    top:posY+"px",
    visibility:'visible',
    display:'block'
    }
  );
  if (content) $(dialog_id+"_body").innerHTML = content;
}

// Position a tooltip element above an another element
function moveTooltip(elementToMoveName, anchorElementName){
  moveTooltipBumpCenter(elementToMoveName, anchorElementName, 0)
}

function moveTooltipBumpCenter(elementToMoveName, anchorElementName, shiftCenter) {

  anchorElement = $(anchorElementName);
  elementToMove = $(elementToMoveName);

  // calculate the horizontal center of the anchor element
  dimensions = Element.getDimensions(anchorElement);
  anchorWidth = dimensions.width;
  anchorHeight = dimensions.height;

  position = Position.cumulativeOffset(anchorElement);
  posX = position[0];
  posY = position[1];

  posX += anchorWidth / 2 + shiftCenter;
  posY -= anchorHeight;

  // calculate the width and height of the tooltip
  dialogW = elementToMove.getStyle('width');
  dialogH = elementToMove.getStyle('height');
  offsetW = -(parseInt(dialogW)/2) - 12;
  offsetH = -(parseInt(dialogH)) - 20;

  posX += offsetW;
  posY += offsetH;

  // move the tooltip center and above the anchor element
  $(elementToMove).setStyle(
    {
    left:posX+"px",
    top:posY+"px",
    visibility:'visible',
    display:'block',
    backgroundPosition: (-250 - shiftCenter)+"px bottom"
    }
  );
//$(elementToMove).setStyle({backgroundPosition:'-165px bottom' })
}

function hideTooltip(elementToMoveName){
  elementToMove = $(elementToMoveName);
  $(elementToMove).setStyle({visibility:'hidden'})
}

function tooltipDialog( theEvent, content ) {
  if ( content === undefined ) content = null;

  posX = Event.pointerX(theEvent);
  posY = Event.pointerY(theEvent);
  posX -= 60;
  posY -= 5;
  $('tooltip_dialog').setStyle(
    {
    left:posX+"px",
    top:posY+"px",
    display:'block'
    }
  );
  $("tooltip_dialog_body").innerHTML = content;
}


// Displays a confirmation box when a checkbox or radio button is clicked
function confirmCheckbox( theCheckbox, messageWhenChecked, messageWhenUnchecked ) {
  if ( messageWhenChecked   === undefined ) messageWhenChecked   = null;
  if ( messageWhenUnchecked === undefined ) messageWhenUnchecked = null;

  if (theCheckbox.checked) {
    if (messageWhenChecked) {
      return confirm(messageWhenChecked)
    }
  } else {
    if (messageWhenUnchecked) {
      return confirm(messageWhenUnchecked)
    }
  }
}

// Some basic helper methods that may be useful in different sections of the site
function getRealLeft(obj) {
  var xPos = eval(obj).offsetLeft;
  var tempEl = eval(obj).offsetParent;
  while (tempEl != null) {
      xPos += tempEl.offsetLeft;
      tempEl = tempEl.offsetParent;
  }
  return xPos;
}

function getRealTop(obj) {
  var yPos = eval(obj).offsetTop;
  var tempEl = eval(obj).offsetParent;
  while (tempEl != null) {
      yPos += tempEl.offsetTop;
      tempEl = tempEl.offsetParent;
  }
  return yPos;
}

function getAbsolutePosition(obj) {
  return {"x":getRealLeft(obj), "y":getRealTop(obj)};
}


function isValidURL(url) {
  return true;
    var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_~:\+%&,#\?\/.=]+$");
    if (!v.test(url)) {
        alert("You have provided an invalid URL. Please correct the URL and try again.");
        return false;
    }
  return true;
}

/* Inbox and Request Message Indicator */
var MessageIndicator = Class.create({
  initialize: function(link,frequency) {
    this.msgs = {};
    this.msgLink = $(link);
    this.refresh = frequency;
    if(!this.refresh) return;
    new PeriodicalExecuter(this.loadMessageCounts.bind(this), this.refresh);
  },
  loadMessageCounts: function() {
    new Ajax.Request('/threads/update_home_tab', {
      evalScripts:true,
      method:'get',
      onSuccess: function(transport) {
        this.msgs = transport.responseText.evalJSON();
        this.updateMessageLink()
      }.bind(this)
    });
  },
  updateMessageLink: function() {
    if(this.msgs.requests) {
      this.msgLink.show().href = "/requests";
    } else if (this.msgs.inbox) {
      this.msgLink.show().href = "/threads";
    } else {
      this.msgLink.hide().href = "/threads";
    }
  }
});



function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


var mergeResolver = Class.create({
  initialize:function(pageProfile,atts){
    this.pageProfile = pageProfile;
    this.attributes = atts;
  },
  selectColumnData:function(row,colindex) {
    var value
    var forminput = row.down('input')
    var ii = 0
    var cell = row.cells[ii]

    while ( ! (cell === undefined) ) {
      if (ii == colindex) {
        cell.style.backgroundColor = '#aaffaa';
        value = cell.down('div').innerHTML
      } else {
        cell.style.backgroundColor = '#ffffff';
      }
      cell = row.cells[++ii];
    }

    forminput.value = value;
  },
  selectData:function(event) {
    var actioncell = Event.element(event).up('td')
    var colindex = actioncell.previousSiblings().length;
    var actionrow = actioncell.up('tr')

    this.selectColumnData(actionrow,colindex);
  },
  selectColumn:function(event,numRowsToSkip) {
    var actioncell = Event.element(event).up('th')
    var colindex = actioncell.previousSiblings().length;
    var actiontable = actioncell.up('table')
    var ii = numRowsToSkip
    var row = actiontable.rows[ii]

    while ( ! (row === undefined) ) {
      this.selectColumnData(row,colindex);
      row = actiontable.rows[++ii];
    }
  }
})

// Used by home and calendar pages
function checkAllHolidays(flag) {
  var index = 0;
  chk = $("holiday_" + index);
  while (chk) {
    chk.checked = flag;
    index++;
  chk = $("holiday_" + index);
  }
}

// spawn a new browser window for Proflowers
function goProFlowers() {
    openProFlowersWindow();
    window.location = "proflowers_confirm";
    return false;
}
function openProFlowersWindow() {
    affiliate_window = window.open("proflowers_affiliate?gift_id="+$('gift_id').value,"proflowers_affiliate_window","toolbar=1,resizable=1,scrollbars=1,width=1185,height=825");
    affiliate_window.focus();
}

function addLightBoxControls() {
  if(window.lightboxes_added) return;
  window.lightboxes_added = true;
  Event.observe(document,'click',function(event){
    var link = Event.findElement(event,'a');
    if(link && link.hasClassName('lbOn')) {
      new Panel({
        panelId:'lightbox',
        url:link.getAttribute('href'),
        displayOverlay:true
      }).open();
      Event.stop(event)
    }
  })
}
Event.observe(document,'dom:loaded',function(){
  addLightBoxControls();
});

function openPremiumLightbox(target_arguments, form_id) {
  if (typeof form_id == "undefined") {
    form_id = null;
  }

  lightbox_url  = '/pro/premium_lightbox';
  lightbox_url += '?' + target_arguments;

  if (form_id) {
    lightbox_url += '&' + $(form_id).serialize();
  }

  premium_lb = new Panel( {url : lightbox_url, panelId : 'lightbox', hideEffect:'Fade', hideEffectOptions:{duration:0.5}} ).open();
}

function redirectToWall(target_arguments, form_id) {
  if (typeof form_id == "undefined") {
    form_id = null;
  }

  url  = '/pro/premium_feature';
  url += '?' + target_arguments;

  if (form_id) {
    url += '&' + $(form_id).serialize();
  }

  document.location = url
}

function clearForm(form_id) {
  var form, elements, i, elm, field;
  form = document.getElementById ? document.getElementById(form_id) : document.forms[form_id];

//look through by tag name
  if (document.getElementsByTagName) {
    //clear text boxes, check boxes, and radio buttons
    elements = form.getElementsByTagName('input');
    for(i = 0, elm; elm = elements.item(i++);) {
      if (elm.disabled == false) {
        //clear text boxes
        if (elm.getAttribute('type') == "text" || elm.getAttribute('type') == "password") {
          elm.value = '';
        } else if (elm.getAttribute('type') == "checkbox" || elm.getAttribute('type') == "radio") {
        //clear check boxes and radio buttons
          elm.checked = false;
        }
      }
    }

    //reset list boxes and drop down lists to the first item
    elements = form.getElementsByTagName('select');
    for(i = 0, elm; elm = elements.item(i++);) {
      if (elm.disabled == false) {
        elm.options.selectedIndex=0;
      }
    }
  } else {
  //look through by element type here but the result is the same as above for input type
    elements = form.elements;
    for(i = 0, elm; elm = elements[i++];) {
      if (elm.disabled == false) {
        //clear text boxes
        if (elm.type == "text" || elm.type == "password") {
          elm.value ='';
        } else if (elm.type == "checkbox" || elm.type == "radio") {
        //clear check boxes and radio buttons
        elm.checked = false;
        }
      }
    }

  }

} //clearForm(formId)



PossibleRelatives = Class.create({
  initialize:function(element){
    this.element = $(element);
    this.displayed = [];

    this.setDisplayedProfiles();
    Event.observe(this.element,'click',this.handleClickEvents.bind(this))
  },
  setDisplayedProfiles:function() {
    this.displayed.push(this.element.select('li[profile_id]').collect(function(li){
      return li.getAttribute('profile_id')
    }));
    this.displayed = this.displayed.uniq();
  },
  handleClickEvents:function(event) {
    var li = Event.findElement(event,'li');
    var link = Event.findElement(event,'a');
    var checkbox = Event.findElement(event,'input[type=checkbox]');
    if(li) {
      if(link && link.hasClassName('add_family')) return this.add(li);
      if(link && link.hasClassName('remove_family')) return this.remove(li);
      if(checkbox && checkbox.hasClassName('check_family')) return this.check(li,checkbox);
    }
  },
  add:function(li) {
    //new Effect.Opacity(li,{to:0,duration:0.4});
    li.fade({duration:0.4});
    var profile_id = li.getAttribute('profile_id');
    new Ajax.Request('/profile_actions/invite_possible_relative/'+profile_id,{
      params:{displayed_profiles:this.displayed},
      onSuccess:function(request) {
        this.handleResponse(li,request.responseText)
      }.bind(this)
    });
  },
  remove:function(li) {
    //new Effect.Opacity(li,{to:0,duration:0.4});
    li.fade({duration:0.4});
    var profile_id = li.getAttribute('profile_id');
    new Ajax.Request('/profile_actions/remove_possible_relative/'+profile_id,{
      params:{displayed_profiles:this.displayed},
      onSuccess:function(request) {
        this.handleResponse(li,request.responseText)
      }.bind(this)
    });
  },
  check:function(li,checkbox) {
    if(checkbox.checked) {
      li.addClassName('selected');
    } else {
      li.removeClassName('selected');
    }
  },
  handleResponse:function(li,html) {
    if(html.blank()) {
      li.remove()
    } else {
      li.replace(request.responseText);
      li.appear({duration:0.4});
    }
  }
});

function updateMatchCount( origin, destination ) {
  origin_div      = $(origin);
  destination_div = $(destination);
  if(!origin_div || !destination_div) return;

  origin_count         = parseInt(origin_div.innerHTML);
  destination_count    = parseInt(destination_div.innerHTML);

  origin_div.innerHTML      = origin_count - 1;
  destination_div.innerHTML = destination_count + 1;
}

function showHide( element_id, show_hide ) {
  if (show_hide) {
    Element.show(element_id);
  } else {
    Element.hide(element_id);
  }
}

function isValidEmail(val){
    var re = /^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,4}|\d+)$/i;
    return (!val.match(re)) ? false : true ;
}


Editable = Class.create({
  initialize: function(element) {
    this.element = $(element);
    this.element.observe('click',this.delegateEvents.bind(this));
  },
  delegateEvents: function(event) {
    var link = Event.findElement(event,'');
    if(link && link.hasClassName('toggle_editable')) {
      this.toggleEditable(link);
      Event.stop(event);
    }
  },
  toggleEditable: function(link) {
    var editable_container = link.up('.editable');
    if(editable_container) {
      var add_remove = (editable_container.hasClassName('edit_on')) ? 'remove' : 'add';
      this.collapse();
      editable_container[add_remove+'ClassName']('edit_on');
    }
  },
  collapse: function() {
    this.element.select('.edit_on').each(function(el){el.removeClassName('edit_on')});
  },
  inEditMode:function() {
    return !!this.element.down('.edit_on');
  }
});

// Submits a form while disallowing multiple submits and disabling cancel button
// Inputs: form_name, include_cancel_button
// Global variables: formHasBeenSubmitted
// Assumptions: button id=submit_button, cancel id=cancel_button
var formHasBeenSubmitted = false;
function submitFormWithFeedback(form_name, include_cancel_button){
  if ( include_cancel_button === undefined ) {
      include_cancel_button = true;
   }
  if (!formHasBeenSubmitted) {
    formHasBeenSubmitted = true;
    $('submit_button').innerHTML = "<span>Please Wait...</span>";
    if (include_cancel_button) {
      // disable cancel button
      $('cancel_button').hide();
    }
    $S(form_name);
  }
  return false;
}

// Favorites related functions
function previewBookmarks(fav_box_id) {
  new Ajax.Updater(fav_box_id, '/bookmarks/preview', {
    onSuccess:function(request) {
    }
  });
}

function addBookmark(obj_type, obj_id){
  new Ajax.Request('/bookmarks/add', {
    parameters:{'obj_type':obj_type, 'obj_id':obj_id},
    onSuccess:function(request) {
      if (request.responseText.indexOf('Error') != -1) {
        alert(request.responseText);
      }
    }
  });
}

function removeBookmark(obj_type, obj_id){
  new Ajax.Request('/bookmarks/remove', {
    parameters:{'obj_type':obj_type, 'obj_id':obj_id},
    onSuccess:function(request) {
      if (request.responseText.indexOf('Error') != -1) {
        alert(request.responseText);
      }
    }
  });
}



// Bookmark Control

var Bookmark = {
  type:null,
  id:null,
  is_bookmarked:false,
  togglePanel:function() {
    if(!this.preview_panel) {
      this.preview_panel = new Panel({
        positionRelativeTo:$('toggle_bookmarks_panel'),
        useShim:true,
        hooks:['BR','TR'],
        url:'/bookmarks/preview?per_page=20',
        panelClass:'bookmark_panel',
        showLoading:false,
        enableClickOut:true,
        displayOverlay:false,
        excludeFromClickOut:['toggle_panel_link'],
        onLoadComplete:this.registerPanelEvents.bind(this)
      }).open()
    } else {
      this.preview_panel.toggle()
    }
  },
  toggleBookmark:function() {
    // each page can define its own way of saving bookmarks, like lists or searches
    if (!this.is_bookmarked && (typeof savePageBookmark == 'function')) {
       savePageBookmark();
    } else if (this.is_bookmarked && (typeof deletePageBookmark == 'function')) {
       deletePageBookmark();
    } else {
      var url = (this.is_bookmarked) ? '/bookmarks/remove' : '/bookmarks/add';
      new Ajax.Request(url,{
        parameters:{obj_type:this.type,obj_id:this.id},
        onSuccess:function() {
          this.is_bookmarked = !this.is_bookmarked;
          this.finalizeBookmarkAction();
        }.bind(this)
      })
    }

  },
  finalizeBookmarkAction:function() {
    var button =  $('bookmark_btn')
    var button_text = (this.is_bookmarked) ? "Remove Bookmark" : "Add Bookmark";
    var button_state = (this.is_bookmarked) ? "on" : "off";
    button.className = button_state;
    button.title = button_text;
    if(this.preview_panel) this.updatePanel();
  },
  markAsDirty:function() {
    this.is_bookmarked = false;
    $('toggle_bookmark_link').update("Add Bookmark");
  },
  registerPanelEvents:function() {
    $('bookmark_links').observe('click',function(event){
      var link = Event.findElement(event,'a');
      if(link && link.hasClassName('remove')) {
        link.up('tr').fade({duration:0.4});
        Event.stop(event);
        new Ajax.Request(link.href);
      }
    })
  },
  updatePanel:function() {
    new Ajax.Updater(this.preview_panel.element, '/bookmarks/preview?per_page=20');
  },
  remove:function(type,id,element) {
    new Ajax.Request('/bookmarks/remove',{
      parameters:{obj_type:type,obj_id:id},
      onSuccess:function() {
        if(element && $(element)) $(element).fade({duration:0.3});
        if(this.preview_panel) this.updatePanel();
      }.bind(this)
    })
  }
}



JSONPRequest = Class.create({
  initialize: function(url,parameters) {
    this.url = url;
    if(parameters) {
      this.url += "?"+Object.toQueryString(parameters)
    }
    this.headLoc = document.getElementsByTagName("head").item(0);
    window.JSONscriptCounter = window.JSONscriptCounter || 1;
    this.scriptId = 'JscriptId' + window.JSONscriptCounter++;
    this.buildScriptTag();
  },
  buildScriptTag: function () {
    this.scriptObj = new Element("script",{
      'type':'text/javascript',
      'charset':'utf-8',
      'src':this.url,
      'id':this.scriptId
    });
    this.headLoc.appendChild(this.scriptObj);
  }
});

function inviteProfile(profile_id, invitation_type) {

   $('profile_spinner_' + profile_id).show();

   if ($('submit_links_' + profile_id)) {
     $('submit_links_' + profile_id).hide();
   }
   if ($('profile_email_form_' + profile_id)) {
     $('profile_email_form_' + profile_id).hide();
   }

   var params = {};
   if ($('profile_email_' + profile_id)) {
     params = {"email": $F('profile_email_' + profile_id)};
   }

   new Ajax.Request('/profile_actions/invite_tree/' + profile_id, {
      method: 'get',
      parameters: params,
      onSuccess: function(request) {
       $('profile_spinner_' + profile_id).hide();
       $('profile_email_success_' + profile_id).show();
       if (invitation_type == 'separate_controls') {
         $('profile_email_' + profile_id).hide();
         $('entered_email_address_' + profile_id).update($F('profile_email_' + profile_id));
         $('entered_email_address_' + profile_id).show();
       }
      },
      onFailure: function(request) {
       $('profile_spinner_' + profile_id).hide();
       $('profile_email_failure_' + profile_id).show();
      }
   });
}

function tryInvitingProfileAgain(profile_id) {
    $('profile_email_success_' + profile_id).hide();
    $('profile_email_failure_' + profile_id).hide();
    $('profile_email_form_' + profile_id).show();

    if ($('profile_email_' + profile_id)) {
      $('profile_email_' + profile_id).focus();
    }
}

FileInput = Class.create({
  initialize: function(container,input) {
    this.container = $(container);
    this.input = $(input);
    this.input.setStyle({opacity:0})
    this.registerEvents();
  },
  registerEvents: function() {
    this.container.observe('mouseover',function() {
      Event.observe(document,'mousemove',this.attachment_move.bind(this));
      this.container.addClassName('hover');
    }.bind(this));
    this.container.observe('mouseout',function() {
      Event.stopObserving(document,'mousemove',this.attachment_move.bind(this));
      this.container.removeClassName('hover');
    }.bind(this));
  },
  attachment_move:function (event) {
    var x = Event.pointerX(event) - $(this.container).cumulativeOffset()[0] - $(this.input).getWidth() + 25;
    var y = Event.pointerY(event) - $(this.container).cumulativeOffset()[1] - 8;
    $(this.input).setStyle({left:x+'px',top:y+'px'});
  }
});


imported_addrs = null;
ImportedAddressTagger = Class.create({
  initialize:function(element,field_name,use_name){
    this.element = $(element);
    if(!imported_addrs || !imported_addrs.any()) return;
    new Autocomplete(this.element,imported_addrs,{
      inputTemplate:function(item){
        if(use_name) {
          return ([item.first_name,item.last_name].join(" "));
        } else {
          return item.email
        }
      },
      listTemplate:"<strong>#{first_name} #{last_name}</strong><br><em>#{email}</em>",
      onSelect:function(item) {
        var name_field = $(field_name+"_display_name");
        var email_field = $(field_name+"_email");
        if(name_field) {
          name_field.value = [item.first_name,item.last_name].join(" ");
          name_field.focus();
          name_field.blur();
        }
        if(email_field) {
          email_field.value = item.email;
          email_field.focus();
          email_field.blur();
        }
      }
    })
  }
});

CreditCardDetails = Class.create({
  initialize: function(profile_id) {
    this.profile_id = profile_id;
    this.initEditables();
  },
  initEditables: function() {
    Event.observe('cc_body', 'click', function(event) {
      var theLink = Event.findElement(event, 'a');
      if (!theLink)
        return;
      switch(theLink.getAttribute('rel'))
      {
      case 'edit_toggle':
        this.toggleEditEditable(event);
        break;
      case 'edit_submit':
        this.editCreditCard(event);
        break;
      case 'add_toggle':
        this.toggleAddEditable(event);
        break;
      case 'add_submit':
        this.addCreditCard(event);
        break;
      default:
      }
    }.bind(this))

  },

  toggleAddEditable: function(evt) {
    new Effect.toggle( 'add_fields', 'blind', {duration:.2});
    Element.toggle('add_link');
    return false;
  },
  toggleEditEditable: function(evt) {
    var link = Event.element(evt);
    var parent = link.up('.credit_card_container');
    new Effect.toggle( parent.down('.edit_fields'), 'blind', {duration:.2});
    Element.toggle(parent.down('.credit_card_body'));
    return false;
  },
  addCreditCard: function() {
    $('add_fields').addClassName('loading');
    $('add_submit').addClassName('loading');
    $S('form_add_credit_card');
    return false;
  },
  editCreditCard: function(evt) {
    var the_form = Event.element(evt).up('form');
    the_form.down('.edit_fields').addClassName('loading');
    $S(the_form);
    return false;
  }
})


NoticePoller = Class.create({
  initialize:function(notice_id) {
    this.poller = null;
    this.poll_url = "/notification/alert"
    this.read_msg_url = "/notification/alert_read";
    this.notice_container = $('active_notice');
    this.notice_body = this.notice_container.down('.message');
    this.close_btn = this.notice_container.down('.close');
    this.notice_id = notice_id;
    this.poll_interval = 60;
    this.close_btn.observe('click',this.hideNotice.bind(this));

    Event.observe(document,'scroll',this.markNoticeReadIfVisible.bind(this));
    Event.observe(window,'focus',this.start.bind(this, true));
    Event.observe(window,'blur',this.stop.bind(this));

    this.start();
  },
  start:function(poll_immediately) {
    if(this.notice_container.visible()) return;
    if(this.poller) this.poller.stop();
    if(poll_immediately && this.poller) this.poll();
    this.poller = new PeriodicalExecuter(this.poll.bind(this), this.poll_interval);
  },
  stop:function() {
    if(this.poller) this.poller.stop();
  },
  poll:function() {
    if(this.loading) return;
    this.loading = true
    new Ajax.Request(this.poll_url,{
      onSuccess:function(r){
        if (r.responseText && !r.responseText.blank()) {
          var results = r.responseText.evalJSON();
          this.notice_id = results[0];
          this.showNotice(results[1]);

//          handling page functions - needed for #16230
//          if (results[2] && window[results[2]] && (typeof window[results[2]] == 'function')) {
//            window[results[2]]();
//          }

        }
        this.loading = false;
      }.bind(this)
    })
  },
  showNotice:function(text) {
    if(!window.is_focused) return;
    this.notice_container.highlight();
    if(!this.notice_container.visible()) {
      $('system_notice_container').show()
      this.notice_container.blindDown({duration:0.4})
    }
    this.notice_body.update(text);
    this.stop();
    this.markNoticeReadIfVisible()
  },
  markNoticeReadIfVisible:function() {
    if (document.viewport.getScrollOffsets().top < 25) {
      this.markNoticeRead()
    }
  },
  hideNotice:function() {
    this.notice_container.blindUp({
      duration:0.3,
      afterFinish:function(){
        this.notice_body.update();
        this.start();
      }.bind(this)
    })
  },
  markNoticeRead:function() {
    if (this.notice_id) {
      new Ajax.Request(this.read_msg_url, {
        parameters: {id:this.notice_id}
      });
      this.notice_id = null;
    }
  },
  setPollInterval:function(value) {
    this.poll_interval = value;
    this.start();
  }
})




  function getNewRow(new_id) {
    $('add_new_row').addClassName('loading')
    new Ajax.Request('/invite/ifs_row',{
      method:'get',
      parameters:{new_id:new_id, id:page_profile.id},
      onSuccess:function(transport) {
        $('add_new_row').removeClassName('loading');
        new_id--;
        var new_row = $('immediate_family_table').insert(transport.responseText);
        new_row.getElementsBySelector('input[label]').each(function(el){
          new LabelMaker(el, el.getAttribute('label'));
        });
      }
    })
  }



  function openIFSLightbox(profile_id){
    new Panel({
      panelId:'lightbox',
      url:'/invite/lb_ifs/'+profile_id,
      displayOverlay:true
    }).open();
  }


  function addShareButton(options) {
    SHARETHIS.addEntry({
      title:options.title,
      summary:options.summary,
      url:options.url,
      icon: 'http://www.geni.com/images/Geni.gif'
    }, {button:true});
  }

  function counterUpdate(opt_countedTextBox, opt_countBody, opt_maxSize) {
          var countedTextBox = opt_countedTextBox ? opt_countedTextBox : "counttxt";
          var countBody = opt_countBody ? opt_countBody : "countBody";
          var maxSize = opt_maxSize ? opt_maxSize : 1024;

          var field = document.getElementById(countedTextBox);

          if (field && field.value.length >= maxSize) {
                  field.value = field.value.substring(0, maxSize);
          }
          var txtField = document.getElementById(countBody);
                  if (txtField) {  
                  //txtField.innerHTML = field.value.length;
                  txtField.innerHTML = maxSize- field.value.length;
          }
  }
  
  // NEWSFEED FUNCTIONS
  
  function hidden_names(link, storyId) {
    
    var nfn = $(link).up('.newsfeed_hidden_names') || $(link).up('td').down('.newsfeed_hidden_names');
    [nfn.down('.nfnon'),nfn.down('.nfnames'),nfn.up('td').down('.nfnoff')].invoke('toggle');

    elemName = 'hidden_excerpt_' + storyId
    if ($(elemName)) {
      $(elemName).toggle();
    }
  }

