﻿// 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);
//    /* more code to run on page load */
// });






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 = '/list';
    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 toggleTwo(element1, element2) {
  $(element1,element2).invoke('toggle');
}



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


// Create a character counter for text areas
function createCounter(id, maxsize, limited) {
  if (limited == null) limited = true;
  if ($(id)) {
    Event.observe($(id), 'keyup', function(){charCounter(id,maxsize,limited);}, false);
    Event.observe($(id), 'keydown', function(){charCounter(id,maxsize,limited);}, false);
    charCounter(id,maxsize,limited);
  }
}

function charCounter(id, maxlimit, limited) {
  if (!$('counter-'+id)) {
    $(id).insert({after: '<div class="charcount-counter" id="counter-'+id+'"></div>'});
  }
  var remaining = maxlimit - $F(id).length;
  var counter = $('counter-'+id);
  var textfield = $(id);
  if(remaining<=0) {
    //error
    if(limited){  textfield.value = $F(id).substring(0, maxlimit); }
    counter.addClassName('charcount-over');
    textfield.addClassName('charcount-over');
    counter.removeClassName('charcount-warning');
    textfield.removeClassName('charcount-warning');
  } else if(remaining < 10) {
    //warning
    counter.addClassName('charcount-warning');
    textfield.addClassName('charcount-warning');
    counter.removeClassName('charcount-over');
    textfield.removeClassName('charcount-over');
  } else {
    //all clear
    counter.removeClassName('charcount-warning');
    counter.removeClassName('charcount-over');
    textfield.removeClassName('charcount-warning');
    textfield.removeClassName('charcount-over');
  }
  
  $('counter-'+id).update(remaining);
}



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



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

  Element.hide('divorce'+ii_string);
  Element.hide('married'+ii_string);

  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";
  }

}



// Profile Index page


function loadRelationshipPath(rpath, through_id, relationship_path) {
  var rpath = $(rpath);
  var load_msg_delay = 300;
  var loadTimer = setTimeout(function(){
    rpath.addClassName('loading');
  },load_msg_delay)
  new Ajax.Request('/profile/relationship_path/'+page_profile.id,{
    parameters:{through:through_id, relationship_path:relationship_path},
    onComplete:function(){
      clearTimeout(loadTimer);
      rpath.removeClassName('loading');
    },
    onFailure:function(){rpath.addClassName('fail')},
    onSuccess:function(r){rpath.replace(r.responseText)}
  })
}

function toggleHandprintView(expand) {
  if(expand) {
    $('family_handprint').addClassName('expand');
    Cookie.set('show_handprint_text',true);
  } else {
    $('family_handprint').removeClassName('expand');
    Cookie.set('show_handprint_text',false);
  }
}




// 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'));
    }
  });
}

function hideConnectingPath() {
  $('pathway').removeClassName("adjusted");
  $('connecting_path').setStyle({display:'none'});
  $('connecting_path_toggle').show();
  $('toggled_path_actions').hide();
}

function showConnectingPath() {
  $('pathway').addClassName("adjusted");
  $('connecting_path').setStyle({display:'inline'});
  $('connecting_path_toggle').hide();
  $('toggled_path_actions').show();
}

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




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





// 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;
}


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




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) {
	  if(row.hasClassName('locked')) {
	  	alert('This field has been locked by a curator and cannot be changed.')
	  	return;
	  }
    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);
  }
}

// Used by home and profile pages

function resetStatusEditor() {
  if ($('status_input')) {
    $('status_input').value = "";
  } else if ( $('comment') ) {
    $('comment_input').value = "";
  }
  labels_init();
}

function insertStory() {
  var input_id = 'status_input';
  var label_id = 'status_input_label';
  var form_id  = 'status_form';

  if ( $(input_id) == null && $('comment') ) {
    input_id = 'comment';
    label_id = 'comment_label';
    form_id  = 'comment_form';
  }

  if ( $F(input_id).strip() != $F(label_id).strip() ) {
    $S(form_id);
    input = $F(input_id).truncate(240)

    $('story_preview').down('.status_preview_title').update(input);

    var storyPlaceholder = $('story_preview').down("tr").cloneNode(true);

    if ( $('display_holiday_reminder_excerpt') ) {
      $('display_holiday_reminder_excerpt').insert( { after: storyPlaceholder } );
    } else {
      $('newsfeed_table').down("tr").insert( { before: storyPlaceholder } );
    }

    Effect.Appear( $('newsfeed_table').down(".display_profile_status_excerpt"), { duration:1, delay:0.3 });

    if ($('latest_status')) {
      $('latest_status_timestamp').update('Today:');
      $('latest_status').update(input);
    }
  }
}


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',
        panelClass:link.getAttribute('data-panel-class') || 'panel',
        url:link.getAttribute('href'),
        displayOverlay:true,
        width:link.getAttribute('data-panel-width') || null
      }).open();
      Event.stop(event)
    }
  })
}
Event.observe(document,'dom:loaded',function(){
  addLightBoxControls();
});



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)



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



// check all checkboxes in an element
function checkAll(element,checked) {
  element = $(element);
  var checkboxes = element.select('input[type=checkbox]');
  checkboxes.each(function(checkbox){
    checkbox.checked = checked;
  })
}

function disableAll(selector,disable_flag) {
  $$(selector).each(function(el){
    el.disabled = disable_flag;
  })
}


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



JSONPRequest = Class.create({
  initialize: function(url,parameters,callback) {
    this.url = url;
    this.callback = callback;
    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
    });
    if(this.callback) this.scriptObj.observe('load',this.callback)
    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();
    }
}



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) {
    Element.toggle('add_fields');
    Element.toggle('add_link');
    return false;
  },
  toggleEditEditable: function(evt) {
    var link = Event.element(evt);
    var parent = link.up('.credit_card_container');
    Element.toggle('edit_fields');
    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;
  }
})


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


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() {
    if(this.notice_container.visible()) return;
    if(this.poller) this.poller.stop();
    this.poller = new PeriodicalExecuter(this.poll.bind(this), this.poll_interval);
    this.poll();
  },
  stop:function() {
    if(this.poller) this.poller.stop();
  },
  poll:function() {
    if(this.loading) return;
    this.loading = true
    new Ajax.Request(this.poll_url,{
      parameters:{source_url:window.location.href},
      onSuccess:function(r){
        if (r.responseText && !r.responseText.blank()) {
          var results = r.responseText.evalJSON();
          this.notice_id = results.id;
          if(results.url) {
            //this.showLightboxNotice(results.url);
          } else {
            this.showTextNotice(results.text);
          }
        }
        this.loading = false;
      }.bind(this)
    })
  },
  showTextNotice: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()
  },
  showLightboxNotice:function(url) {
    new Panel({
      panelId:'lightbox',
      url:url,
      displayOverlay:true,
      onClose:function(){
        this.start();
      }.bind(this)
    }).open();
    this.stop();
    this.markNoticeRead();
  },
  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){
    var on_edit_card = !((typeof(editCard)).match(/undefined/) && (typeof(freezeTree)).match(/undefined/))
    if(on_edit_card) {
      editCard.close()
      freezeTree()
    }
    new Panel({
      panelId:'lightbox',
      url:'/invite/lb_ifs/'+profile_id,
      displayOverlay:true,
      onClose:function(){
        if(on_edit_card) {
          unfreezeTree()
        }
      }
    }).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();
    }
  }









var RadioMenu = Class.create({
  initialize:function(element,callback) {
    this.element = $(element);
    this.callback = callback;
    this.element.observe('click',this.handleClick.bind(this));
  },
  handleClick:function(e) {
    this.element.select('a').invoke('removeClassName','selected')
    var link = Event.findElement(e,'a');
    var val = link.getAttribute('value');
    link.addClassName('selected');
    this.element.down('input[type=hidden]').value = val;
    if(this.callback) this.callback(link,val)
    e.stop();
  }
})

var RelationshipDeleter = Class.create({
  initialize: function(allowSplit, ignoreSplit) {
    this.allowSplit = allowSplit;
    this.ignoreSplit = ignoreSplit;
    this.deletedUnions = [];
    this.cycleUnions = {};
  },
  setCycleUnion: function(uid, cycle_uids) {
    this.cycleUnions[uid] = cycle_uids;
  },
  checkConnection: function(uid, checked){
    if (checked) {
      this.deletedUnions.push(uid);
    } else {
      this.deletedUnions = this.deletedUnions.without(uid);
    }

    if (this.ignoreSplit) {
      this.enableSubmitButton(true);
    } else {
      this.checkTreeSplit();
    }
  },
  checkTreeSplit: function() {
    if (this.treeSplit()) {
      $('cycles_list_inner').addClassName('warning_msg');
      $('split_warning').show();
      this.enableSubmitButton(this.allowSplit);
      return true;
    } else {
      $('cycles_list_inner').removeClassName('warning_msg');
      $('split_warning').hide();
      this.enableSubmitButton(true);
      return false;
    }
  },
  enableSubmitButton: function(enable) {
    if ($('submitRemoveConnections')) {
      if (enable && this.deletedUnions.length > 0) {
        $('submitRemoveConnections').removeClassName('disabled').disabled = false;
      } else {
        $('submitRemoveConnections').addClassName('disabled').disabled = true;
      }
    }
  },
  treeSplit: function() {
    deleter = this; // for the closure
    return this.deletedUnions.any( function(d) {
      return (deleter.cycleUnions[d] == undefined || deleter.cycleUnions[d].all( function(u) {
        return deleter.deletedUnions.member(u)
      }))
    })
  }
});



DropMenuManager = function(){
  $(document).observe('click',this.handleClick.bind(this));
  this.iframe_shim = new Element('iframe', {'src':'javascript:false;'}).hide();
  this.iframe_shim.setStyle({opacity:0,position:'absolute',zIndex:2});
}

DropMenuManager.prototype = {
  handleClick:function(e) {
		var dm = Event.findElement(e,'.drop-menu');
		this.deactivateMenus()
		if(dm) {
			dm.addClassName('active');
			this.updateIframeShim(dm);
			if(Event.findElement(e,'.drop-menu>span')) e.stop();
		}
  },
  deactivateMenus:function(){
    $$('.drop-menu.active').invoke('removeClassName','active');
    this.iframe_shim.hide();
  },
  updateIframeShim: function(dm) {
    var sm = dm.down('.sub-menu');
    if(!sm) return;
    dm.insert(this.iframe_shim);
    this.iframe_shim.show().clonePosition(sm);
  }
}

DropMenuManager = new DropMenuManager();

var PhotoGrid = function(el){
  if (!$(el || document.body)) return
  $(el || document.body).on('click','.delete_media',this.delete_media.bind(this))
}

/* Delete photos from photo grids */
PhotoGrid.prototype.delete_media = function(e){
  var photoli = Event.findElement(e,'li');
  var photoid = photoli.getAttribute('data-photo_id');
  new Ajax.Request("/photo/remove_multi_tags",{
    parameters:{profile_id:page_profile.id,'photos[]':[photoid]},
    onSuccess:function(){ photoli.fade({
      afterFinish: function(){ photoli.remove() },
      duration: 0.4
    }); }
  });
  e.stop();
}

/* Allow year inputs to accept only numbers */
$(document).on('keyup','input[data_validate=number]',function(e,el) {
  var val = $F(el);
  if(val.length == 0) { return; }
  var first = val.charAt(0);
  val = val.replace(/[^0-9]/g,'');
  if(first == '-') { 
    val = first + val.substring(0,4); 
  } else {
    val = val.substring(0,4);
  }
  el.setValue(val);
  return true;
})





var Orderable = function(element,options) {
	this.element = $(element);
	this.options = this.setOptions(options);

	Position.includeScrollOffsets = true;
	Sortable.create(this.element,{
		scroll:this.options.scroll,
		onChange:function() {
			this.element.select('li').each(function(el,i) {
				el.down('.num_field').value = (i+1);
				this.findDuplicates();
			}.bind(this))
		}.bind(this)
	});
	this.element.on('change','.num_field',this.findDuplicates.bind(this));
	this.findDuplicates();
}

Orderable.prototype = {
	
	findDuplicates: function() {
		var uniqs = [];
		var has_dups = false;
		this.element.select('.num_field').each(function(el) {
			if(!uniqs[el.value]) {
				uniqs[el.value] = el;
				el.removeClassName('orderable-error-field')
			} else {
				[uniqs[el.value],el].invoke('addClassName','orderable-error-field')
				has_dups = true;
			}
		})
		if(this.options.error_element) {
			if(has_dups) {
				$(this.options.error_element)
					.update(this.options.duplicate_error)
					.setStyle({display:'block'});
			} else {
				$(this.options.error_element)
					.setStyle({display:'none'});
			}
		}
	},
	
	setOptions:function(options) {
		return Object.extend({
			scroll:null,
			error_element:null,
			duplicate_error:'Duplicates are not allowed.'
		}, (options || {}));
	}
	
}


