var AdsHelper = {
  flashAds: new Array(),

  disableFlash: function() {
    this.flashAds = $$('.flash_ad').select(function(item) { return item.visible() });
    this.flashAds.each(function(item) { item.setStyle({ visibility: 'hidden' }); });
  },

  enableFlash: function() {
    this.flashAds.each(function(item) { item.setStyle({ visibility: '' }); });
    this.flashAds.clear();
  }
}

function showSignin(){
  var sn = document.getElementById("signin_notice");
  if (sn==null)
    return;
  sn.innerHTML = "";
  $('email').value = "";
  $('password').value = "";
  showFloater('land_signin_box');
  return false;
}

function hideSignin(){
  $('signin_notice').hide();
  hideFloater('land_signin_box');
  return false;
}

function showSignup(){
  var sn = document.getElementById("signup_notice");
  if (sn==null)
    return;
  sn.innerHTML = "";
  $('user_firstname').value = "";
  $('user_lastname').value = "";
  $('user_email').value = "";
  $('user_password').value = "";
  $('user_password_confirmation').value = "";
  showFloater('land_signup_box');
  document.getElementById("user_firstname").focus();
  return false;
}

function hideSignup(){
  hideFloater('land_signup_box');
  return false;
}

function showForgotPassword() {
  showFloater('land_password_box');
  return false;
}

function showPasswordBox(){
  var d = document.getElementById("password_notice") // response DIV
  if (d != null){
    d.innerHTML = "";
  }
  var e = $('email').value;
  $('request_email').value = e;
  Element.show('password_controls');
  Element.hide('password_close');
  center('land_password_box');
  new Effect.Shrink('land_signin_box', {direction: 'center', duration: 0.2, queue: 'front'});
  new Effect.Grow('land_password_box', {direction: 'center', duration: 0.3, queue: 'end'});
  setTimeout("Field.focus('request_email')",800);
}

function hidePassword(){
  hideFloater('land_password_box');
}
function showSafariOverlay(source){
  if (source == 'signin'){
    hideSignin();
  }else if(source == 'try_it'){
    // do nothing
  }else{
    hideSignup();
  }
  var sn = document.getElementById("box_fields");
  if (sn==null)
    return;
  showFloater('land_safari_box');
  return false;
}
function submitenter(myfield,e) {
  var keycode;
  if (window.event) keycode = window.event.keyCode;
  else if (e) keycode = e.which;
  else return true;

  if (keycode == 13){
    myfield.form.onsubmit();  // onsubmit, not submit for the Ajax form
    return false;
  }else{
    return true;
  }
}
function fixIE() {
  if ($('wait_comment') != null){ setTimeout('document.images["wait_comment"].src="/images/wait_green.gif"', 0); }
  if ($('wait_mail') != null){ setTimeout('document.images["wait_mail"].src="/images/wait_green.gif"', 0); }
  if ($('wait_map') != null){ setTimeout('document.images["wait_map"].src="/images/wait_green.gif"', 0); }
  if ($('wait_flickr') != null){ setTimeout('document.images["wait_flickr"].src="/images/wait_green.gif"', 0); }
  if ($('wait_upload') != null){ setTimeout('document.images["wait_upload"].src="/images/wait_green.gif"', 0); }
  return true;
}

function setConsensus(id, color){
  // clear them all
  document.getElementsByClassName('recommend').each( function(element){
    Element.setStyle(element, {visibility: 'hidden'});
  });
  document.getElementsByClassName('pad_date_wrap').each( function(element){
    Element.setStyle(element, {border: 'none'});
  });
  var consensus_element = $('pad_date_wrap_'+id);
  var consensus_element_top = $('pad_date_top_'+id);
  Element.setStyle(consensus_element, {border: '2px solid #'+color});
  Element.setStyle(consensus_element_top, {visibility: 'visible', backgroundColor: '#'+color, padding: '2px 5px'});
}

function showSomethingElse(){
  Effect.toggle('bringing_something_else', 'blind', {duration:0.3});
  setTimeout("Form.reset('add_item_form');var focus_element = $$('#bringing_something_else #title')[0];focus_element.focus();", 400);
  $('errors_for_add_item').hide();
}

function showDeleteButton(){
  if ($('delete_btn_wrap').visible() == false){
    new Effect.BlindDown('delete_btn_wrap', {duration:0.3});
  }
  any_checked = false;
  document.getElementsByClassName('invite_delete_btns').each( function(element){
    if(element.checked == true){
      any_checked = true
    }
  });
  if(any_checked == false){
    new Effect.BlindUp('delete_btn_wrap', {duration:0.3});
  }
}

function disablePreferences(){
  $$('#individual_prefs input').each( function(element){
    element.disable();
  });
  $('individual_prefs').addClassName('disabled');
}

function enablePreferences(){
  $$('#individual_prefs input').each( function(element){
    element.enable();
  });
  $('individual_prefs').removeClassName('disabled');
}
function showNavSubCats (id) {
  var nav_item = $('sub_cat_list_'+id);
  if (nav_item.visible() == false){
    // hide all the open ones
    $$('.sub_cat_list').each(function(e){if(e != null && e.visible()){new Effect.BlindUp(e, {duration: 0.3});}});
    new Effect.BlindDown(nav_item, {duration:0.3});
  }
}
function csvUploadCheck () {
  if($('csv_file').value == ""){
    Element.update("error_text", "<p>Click Browse to select a .csv file to upload<\/p>");
    show_error_floater();
  }else{
    Element.show('evite_wait_invite');
    $('csv_upload_form').submit();
  }
}
function uploadFileCheck() {
  if($('filename').value == ""){
    Element.update("error_text", "<p>Click Browse to select a file to upload<\/p>");
    show_error_floater();
  }else{
    Element.show('upload_file_spinner');
    $('upload_file_form').submit();
  }
}
function showError (text) {
  Element.update("error_text", "<p>"+ text +"<\/p>");
  show_error_floater();
}
function share_facebook(update_event_url, share_url, title) {
  new Ajax.Request(update_event_url, { asynchronous:true, evalScripts:true });

  var ran = Math.round(Math.random() * 10000000);
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(share_url+'?'+ran)+'&t='+encodeURIComponent(title),'sharer','toolbar=0,status=0,width=626,height=436');
}
function showHelp() {
  if($('mypunchbowl_primer')) {
    if($('mypunchbowl_primer').visible())
      new Effect.Fade('mypunchbowl_primer', { duration: 0.3 });
    else
      new Effect.Appear('mypunchbowl_primer', { duration: 0.3 });
  } else {
    window.location = 'http://www.mypunchbowl.com/corporate/faq.php';
  }
}

function toggle_slide(element) {
  var display = element.style.display;
  if(display == 'none') {
    new Effect.SlideDown(element);
  } else {
    new Effect.SlideUp(element);
  }
}

function camelize(string) {
  return string.substr(0, 1).toUpperCase() + string.substr(1)
}

function select_all(search_for, state) {
  $$(search_for).each(function(item){item.checked = state});
}

function clean_html(text) {
  // Try to emulate this rails line so we have this function in JS too
  // auto_link(simple_format(h(strip_tags(text))), :all, :target => '_blank') unless text.blank?
  /*
    strip_tags
    h
    simple_format
    auto_link(:target => '_blank')
  */
  if(!text.empty()) {
    // initial text clean
    text = text.stripScripts().stripTags().escapeHTML().gsub(/[\r]/, '').gsub(/[\n]/, "<br/>");

    // Auto-Link
    // skip for now

    return text;
  }
}

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};


// Please Wait Floater
var ModalWait = Class.create({
  initialize: function(id, message, effects) {
    this.id = id;
    this.message = (message == null) ? "Please wait, this will just take a second" : message;
    this.bodyTag = $$('body').first();
    this.effects = (effects == null) ? false : effects;

    this.bodyTag.insert({ bottom: this.buildShade() });
    this.bodyTag.insert({ bottom: this.buildFloater() });

    this.shade = $(this.id+'_shade');
    this.floater = $(this.id+'_floater');

    this.preloadImages();
  },

  show: function() {
    AdsHelper.disableFlash();
    $(this.id+'_shade').setStyle({ height: getHeight() });
    center(this.id+'_floater');

    if(this.effects) {
      alert('effects!');
      shade = $(this.id+'_shade');
      floater = $(this.id+'_floater');

      // new Effect.Move(floater, { duration: 0, x: 50 });
      shade.appear({ duration: 0.3, from: 0, to: 0.5 });
      floater.appear({ duration: 0.3, from: 0, to: 1 });
      // new Effect.Move(floater, { duration: 0.3, x: -50 });

    } else {
      $(this.id+'_shade', this.id+'_floater').invoke('show');
    }
    //alert('1');
    //alert(this.id);
    //alert($(this.id).previous());
    //$(this.id).previous().scrollTo();
    //alert('2');
  },

  hide: function() {
    AdsHelper.enableFlash();
    if(this.effects) {
      shade = $(this.id+'_shade');
      floater = $(this.id+'_floater');

      shade.fade({ duration: 0.3, from: 0.5, to: 0 });
      floater.appear({ duration: 0.3, from: 1, to: 0 });
      // new Effect.Move(floater, { duration: 0.3, x: -50 });

    } else {
      $(this.id+'_shade', this.id+'_floater').invoke('hide');
    }

    if (this.afterHide) { this.afterHide(); }
  },

  afterHide: function() {
  },

  setMessage: function(new_message) {
    this.message = new_message;
    $(this.id+'_message').update(this.message);
  },

  buildShade: function() {
    var shade = Builder.node('div', { id: this.id+'_shade', className: 'modal_wait_shade', style: 'display: none;' }, [
      Builder.node('img', { src: '/images/transparent_bg.png', width: '1px', height: '1px' }) ]);
    return shade;
  },

  buildFloater: function() {
    var floater = Builder.node('div', { id: this.id+'_floater', className: 'modal_wait', style: 'display: none;' }, [
      Builder.node('div', { className: 'spinner', id: this.id+'_spinner' }, [
        Builder.node('img', { src: '/images/modal_wait/floater_spinner_48x48.gif' }) ]),
      Builder.node('div', { className: 'message' }, [
        Builder.node('p', { id: this.id+'_message' }, this.message ) ]),
      Builder.node('div', { className: 'plug' }) ]);
    return floater;
  },

  preloadImages: function() {
    new Image().src = '/images/modal_wait/modal_wait.png';
    new Image().src = '/images/modal_wait/floater_spinner_48x48.gif';
  }
});

var FbcLoginPrompt = Class.create(ModalWait, {
  initialize: function($super, id, message, effects, callbacks) {
    this.callbacks = (callbacks == null) ? {} : callbacks;
    $super(id, message, effects);
  },

  buildFloater: function($super) {
    var close = Builder.node("a", { className: "close_fb_onlogin", href: "#" }, "cancel");
    $(close).observe("click", function() { this.hide(); return false; }.bind(this));

    var test_link = Builder.node("a", { href: "#", title: "Click this!" }, "Click this!");

    var floater = Builder.node("div", { id: this.id + "_floater", className: "fb_onlogin", style: "display: none;" }, [
      Builder.node("div", {className: "fbc_floater"}, [
        Builder.node("div", {className: "fbc_floater_header"}),
        Builder.node("div", {className: "fbc_floater_content", style: "text-align: center"}, [
          Builder.node("h4", {style: "text-align: center"}, "Connecting to Facebook ..."),
          Builder.node('div', { className: 'spinner', id: this.id+'_spinner' }, [
            Builder.node('img', { src: '/images/progress_bar1.gif' })
            ])
          ]),
        Builder.node("div", {className: "fbc_floater_footer"})
        ])
      ]);

    return floater;
  },

  show: function($super) {
    $super();
  },

  setMessage: function($super) {
    return;
  },

preloadImages: function() {
    new Image().src = '/images/fb_float_top.png';
    new Image().src = '/images/fb_float_bottom.png';
    new Image().src = '/images/fb_float_middle.png';
    new Image().src = '/images/progress_bar1.gif';
  }

});

var YesNoCancelPrompt = Class.create(ModalWait, {
  initialize: function($super, id, message, effects, callbacks) {
    this.callbacks = (callbacks == null) ? {} : callbacks;
    $super(id, message, effects);
  },

  buildFloater: function($super) {
    var cancel  = Builder.node('input', { type: 'button', value: 'Cancel', className: 'cancel_button' });
    var no      = Builder.node('input', { type: 'button', value: 'No', className: 'no_button' });
    var yes     = Builder.node('input', { type: 'button', value: 'Yes', className: 'yes_button' });

    $(cancel).observe('click', this.callbacks.cancel);
    $(no).observe('click', this.callbacks.no);
    $(yes).observe('click', this.callbacks.yes);

    var floater = Builder.node('div', { id: this.id+'_floater', className: 'modal_wait', style: 'display: none;' }, [
      Builder.node('div', { className: 'spinner', id: this.id+'_spinner' }, [
        Builder.node('img', { src: '/images/modal_wait/floater_spinner_48x48.gif' }) ]),
      Builder.node('div', { className: 'question' }, [
        Builder.node('p', { id: this.id+'_message' }, this.message ) ]),
        Builder.node('div', { className: 'buttons' }, [ cancel, yes, no, Builder.node('div', { style: 'clear: both;' } )]),
      Builder.node('div', { className: 'plug' }) ]);

    return floater;
  }
});

var TrialNoticePrompt = Class.create(ModalWait, {
  initialize: function($super, id) {
    $super(id, "You need to create an account before you can do that.", false);
  },

  buildFloater: function($super) {

    var close = Builder.node("a", { className: "close_trial", href: "#" }, "cancel");
    $(close).observe("click", function() { this.hide(); return false; }.bind(this));

    var signup = Builder.node("a", { href: "#", title: "Create a free account" }, [
      Builder.node("img", { src: "/images/trial/trial_createaccount_glow_191x41.jpg", alt: "Create a free account" })
    ]);

    $(signup).observe("click", function() {
      window.location.href = "/signup?" + $H({ return_to: window.location.href }).toQueryString();
      return false;
    });

    var floater = Builder.node("div", { id: this.id + "_floater", className: "trial_wait", style: "display: none;" }, [
      Builder.node("table", {}, [
        Builder.node("tbody", {}, [
          Builder.node("tr", {}, [
            Builder.node("td", {}, [
              Builder.node("p", {}, [ this.message, Builder.node("br"), signup ]),
              Builder.node("p", {}, [ close ])
            ])
          ])
        ])
      ])
    ]);

    return floater;
  },

  show: function($super) {
    $super();
  },

  setMessage: function($super) {
    return;
  },

  afterHide: function($super) {
  },

  preloadImages: function($super) {
    new Image().src = "/images/modal_wait/trial_wait.png";
    new Image().src = "/images/trial/trial_createaccount_glow_191x41.jpg";
  }
});

var NextStepPrompt = Class.create(ModalWait, {
  initialize: function($super, id) {
    $super(id, "What do you want to send to guests?", false);
  },

  buildFloater: function($super) {

    var close = Builder.node("a", { className: "close_trial", href: "#" }, "cancel");
    $(close).observe("click", function() { this.hide(); return false; }.bind(this));

    var signup = Builder.node("a", { href: "#", title: "Create a free account" }, [
      Builder.node("img", { src: "/images/trial/trial_createaccount_glow_191x41.jpg", alt: "Create a free account" })
    ]);

    $(signup).observe("click", function() {
      window.location.href = "/signup?" + $H({ return_to: window.location.href }).toQueryString();
      return false;
    });

    var floater = Builder.node("div", { id: this.id + "_floater", className: "trial_wait", style: "display: none;" }, [
      Builder.node("table", {}, [
        Builder.node("tbody", {}, [
          Builder.node("tr", {}, [
            Builder.node("td", {}, [
              Builder.node("p", {}, [ this.message, Builder.node("br"), signup ]),
              Builder.node("p", {}, [ close ])
            ])
          ])
        ])
      ])
    ]);

    return floater;
  },

  show: function($super) {
    $super();
  },

  setMessage: function($super) {
    return;
  },

  afterHide: function($super) {
  },

  preloadImages: function($super) {
    new Image().src = "/images/modal_wait/trial_wait.png";
    new Image().src = "/images/trial/trial_createaccount_glow_191x41.jpg";
  }
});

var AjaxFloater = Class.create(ModalWait, {
  initialize: function($super, id, action) {
    this.response = new Ajax.Request(action, {method: 'get', asynchronous: false});
    $super(id);
  },

  buildFloater: function($super) {
    var floater = Builder.node("div", {id: this.id + "_floater", className: "trial_wait", style: "display: none;"});
    floater.innerHTML = this.response.transport.responseText;

    return floater;
  },

  show: function($super) {
    $super();
  },

  setMessage: function($super) {
    return;
  },

  preloadImages: function($super) {
    $super();
  },

  afterHide: function($super) {
  }

});

var InlineFloater = Class.create(ModalWait, {
  initialize: function($super, src_id) {
    this.html = $(src_id).innerHTML;
    $(src_id).remove();
    $super(src_id);
  },

  buildFloater: function($super) {
    var floater = Builder.node("div", {id: this.id + "_floater", className: "trial_wait", style: "display: none;"});
    floater.innerHTML = this.html;

    return floater;
  },

  show: function($super) {
    $super();
  },

  setMessage: function($super) {
    return;
  },

  preloadImages: function($super) {
    $super();
  },

  afterHide: function($super) {
  }

});

var LargeFloater = Class.create(ModalWait, {
  initialize: function($super, src_id) {
    this.html = $(src_id).innerHTML;
    $(src_id).remove();
    $super(src_id);
  },

  buildFloater: function($super) {
    var middle_node = Builder.node("div", {id: this.id + "_floater_mid", className: "large_floater_mid"});
    middle_node.innerHTML = this.html;

    var floater = Builder.node("div", {id: this.id + "_floater", className: "large_floater_wrapper", style: "display: none;"}, [
        Builder.node("div", {id: this.id + "_floater_top", className: "large_floater_top"}, ""),
        middle_node,
        Builder.node("div", {id: this.id + "_floater_bottom", className: "large_floater_bottom"}, "")
      ]);

    return floater;
  },

  show: function($super) {
    this.hidden_selects = $$('#guest_list select').select(function(i) { return i.visible()});
    this.hidden_selects.each(function(i) {
      i.hide();
      var t = i.down('option[value='+i.value+']').innerHTML;
      i.next().show().innerHTML = t;
    });
    $super();
  },

  setMessage: function($super) {
    return;
  },

  preloadImages: function($super) {
    $super();
  },

  afterHide: function($super) {
    this.hidden_selects.each(function(i) {
      i.show();
      i.next().hide();
    });
  }

});

var AddHostPrompt = Class.create(InlineFloater, {
  initialize: function($super, src_id) {
    $super(src_id);
  },

  preloadImages: function($super) {
    new Image().src = "/images/modal_wait/trial_wait.png";
  },

  afterHide: function($super) {
  },

  show: function($super) {
    $super();
  }

});

// Pulled from complex-form-examples
replace_ids = function(s){
  var new_id = new Date().getTime();
  return s.replace(/NEW_RECORD/g, new_id);
}

var templates = {};

var preview_behaviors = Behavior.create({
  onclick: Event.delegate({
    'a': function(e) {
      e.stop();
      alert('This action is not allowed in Preview Mode.');
      return false;
    },
   'input': function(e) {
      e.stop();
      e.element().blur();
      alert('This action is not allowed in Preview Mode.');
      return false;
    }
  }),
  onsubmit: Event.delegate({
    'form' : function(e) {
      e.stop();
      alert('This action is not allowed in Preview Mode.');
      return false;
    }
  })
});

var trial_disable = Behavior.create({
  onclick: Event.delegate({
    '.disable_in_trial': function(e) {
      e.stop();
      if (trial_prompt) {
        trial_prompt.show();
      } else {
        alert('You cannot do that in a Trial account');
      }
    }
  })
})


/* IE6 */
var setup_potluck_info = function() {
  $('potluck_msg_form_text').onchange = function(e) {
    this.up('form').onsubmit();
  };

  $('potluck_msg_form_check').onclick = function(e) {
    this.up('form').onsubmit();
  };
}

var nested_attr_behaviors = Behavior.create({
  onclick: Event.delegate({
     '.remove': function(e){
      var el = Event.findElement(e);
      var target = el.href.replace(/.*#/, '.');
      el.up(target).hide();
      if(hidden_input = el.previous("input[type=hidden]")) hidden_input.value = '1';
    },

    '.delete_new_item': function(e){
      e.stop();
      var el = Event.findElement(e);
      el.up('div').remove();
    },

    '.delete_existing_item': function(e) {
      e.stop();
      var el = Event.findElement(e);
      el.next().value = '1';
      el.up('div').hide();
    },

    '.add_nested_item': function(e){
      var el = Event.findElement(e);
      var template = eval("templates."+el.href.replace(/.*#/, ''))
      $(el.rel).insert({
        bottom: replace_ids(template)
      });
    },

    '.cancel_item_edit': function(e) {
      var el = Event.findElement(e);
      this.switch_item_view(el);
    },

    '.edit_item_details': function(e) {
      e.stop();
      var el = Event.findElement(e);
      this.switch_item_view(el);
    },
    '.guest_add_item': function(e) {
      var el = Event.findElement(e);
      e.stop();
      var targ = el.up('p');
      targ.hide();
      targ = targ.previous();
      targ.show();
      targ.down('.item_heading').hide();
      targ.down('.item_details').show();
    },
    '.guest_cancel_add': function(e) {
      var el = Event.findElement(e);
      e.stop();
      var targ = el.up('.new_item');
      targ.hide();
      targ.next().show();
    },
    '.simple_disable': function(e) {
      var el = Event.findElement(e);
      if (el.safe_disabled == 1) {
        e.stop();
        return false;
      }
      if (el.tagName == 'INPUT') {
        el.original = el.value;
        el.value = 'Please wait...';
        el.reEnable = function() { this.value = this.original; this.safe_disabled = null };
        el.safe_disabled = 1;
      } else if (el.tagName == 'A') {
        el.replace('please wait...');
      }
      return true;
    }
}),
  switch_item_view: function(elm) {
    var container = elm.up('div.item');
    container.down('div.item_details').toggle();
    container.down('div.item_heading').toggle();
  }
});

function init_edit_in_place() {
  $$('.edit_in_place').each(function(i) {
    if (i.orig_val == null) i.orig_val = i.value;

    i.onfocus = function(e) {
        if (this.hasClassName('blur')) {
          this.removeClassName('blur');
          this.value = '';
        }
      }
      i.onblur = function(e) {
        if (this.value == '') {
          this.addClassName('blur');
          this.value = this.orig_val;
        }
      }
  });
}

var manage_guest_behaviors = Behavior.create({
  onclick: Event.delegate({
    'a.edit_guest': function(e) {
      var elm = Event.findElement(e);
      e.stop();
      elm.up('div.invite_record').next().show();
      elm.up('div.invite_record').hide();
    },
    'a.cancel_edit_guest': function(e) {
      var elm = Event.findElement(e);
      e.stop();
      elm.up('div.edit_invite_record').previous().show().down('li.delete').show().next().hide();
      elm.up('div.edit_invite_record').hide();
    }
  })
});

var send_message_to_guest_behaviors = Behavior.create({
  onclick: Event.delegate({
    'input.confirm_send': function(e) {
      if (!confirm('Are you sure you want to send this message?')) {
        e.stop();
      } else {
        $('sending_wait').show();
      }
    }
  })
});

var relationship_behaviors = Behavior.create({
  onclick: Event.delegate({
    'a.cancel_edit_relationship': function(e) {
      var elm = Event.findElement(e);
      var main_parent = elm.up('.relationship_record');
      main_parent.down().show().next().hide();
      e.stop();
    },
    'a.from_guest_list':function(e) {
      var elm = Event.findElement(e);
      elm.addClassName('selected').next().removeClassName('selected');
      elm.next('select').show().next().hide();
      elm.next('a.boxover').hide();
      elm.previous('.active_field').value = 'from_guest_list';
      e.stop();
    },
    'a.from_new_person':function(e) {
      var elm = Event.findElement(e);
      elm.addClassName('selected').previous().removeClassName('selected');
      elm.next('select').hide().next().show().focus();
      elm.next('a.boxover').show();
      elm.previous('.active_field').value = 'from_new_person';
      e.stop();
    },
    'a.show_guests_tab':function(e) {
      show_guests_tab();
      e.stop();
   }
  })
});

function before_show_relationships_tab(key) {
  $('relationship_list').show();
  $('invite_list').hide();
  $('relationship_list_inner').hide().next().show();
  $$('div.add_guests_relationships')[0].addClassName('relationships').removeClassName('guests');

  new Ajax.Request('/events/' + key + '/relationship_list');
}

function show_guests_tab() {
  $$('div.add_guests_relationships')[0].removeClassName('relationships').addClassName('guests');
  $('relationship_list').hide();
  $('invite_list').show();
}

var guest_relationships_behaviors = Behavior.create({
  onclick: Event.delegate({
    'a.change_relation_rsvp':function(e) {
      var elm = e.element();
      elm.up('div').hide().next().show();
      e.stop();
    },
    'a.respond_for_relation':function(e) {
      var elm = e.element();
      elm.up('div').hide().next().show();
      e.stop();
    },
    'a.cancel_edit_relation':function(e) {
      var elm = e.element();
      elm.up('div.edit_relation_response').hide().previous().show();
      e.stop();
    },
    'a#add_link.active': function(e) {
      $('save_others').show();
      var new_e = $('rsvp_for_other_template').cloneNode(true);
      new_e.id = null;
      new_e.down('input').value = '';
      Element.insert($('rsvp_for_other_list'), {bottom: new_e});
      new_e.show();

      var other_count = $$('.rsvp_for_other_template').size();

      var others_left = e.element().readAttribute('others_left') || 1
      if (other_count >= others_left) {
        $('add_link').hide();
      }

      if (other_count % 2 == 0) {
        new_e.addClassName('odd');
      }
    },
    '.rsvp_for_other input[type=submit]': function(e) {
      var elm = e.element();
      var r_div = elm.up('div.response');
      var radios = [r_div.down('.radio_yes'), r_div.down('.radio_no')];
      if (radios[0].checked == false && radios[1].checked == false) {
        alert('Please choose a response.');
        return false;
      }
    }
  })
});

function resetInviteBackgroundColors() {
  var elms = $('guest_list_inner').childElements('.invite_record_wrapper');
  var odd = false;

  elms.each(function(i) {
    if (!odd) {
      i.removeClassName('odd').addClassName('even');

      i.descendants().each(function(a) {
        if (a.hasClassName('odd')) {
          a.toggleClassName('odd').toggleClassName('even');
        }
      });

    } else {
      i.addClassName('odd').removeClassName('even');

      i.descendants().each(function(a) {
        if (a.hasClassName('even')) {
          a.toggleClassName('odd').toggleClassName('even');
        }
      });

    }
    odd = !odd;
  });
}

document.observe('dom:loaded', function() {
  Event.addBehavior({
    'body': trial_disable,
    'div#guest_list': manage_guest_behaviors,
    'div#invite_guests_column': relationship_behaviors,
    'div#send_message_inner': send_message_to_guest_behaviors
  });
});

// A helper to display a message when a user is about to leave the page without
//  submitting one of the given forms or clicking on one of the *excluded_links*
//  (see below)
//
// Params:
//  start_on_alert:         Whether to start in alert mode
//  listen_for_form_focus:  Whether to listen for form focus to enable alert
//  message:                The message to be displayed when the user is to be alerted
//  excluded_links:         Any links (or IDs of links) that the user should be allowed
//                           to click without being warned
// If neither start_on_alert nor listen_for_form_focus is enabled, this object will do nothing
//
// Note: Originally inspired by this tutorial:
//  http://www.phpriot.com/articles/reminding-users-to-submit-forms
var FormProtector = Class.create({

    forms              : null,  // the forms being protected
    options            : null,
    alert              : false, // whether or not to show the confirm box
    listenForFormFocus : false,

    // The message to display in confirm box
    message : 'Please remember to submit the form',

    initialize : function(forms, options) {
      this.options = options;

      // Check whether we should start on alert
      if (options['start_on_alert']) {
        this.alert = true;
      }

      if (options['message']) {
        this.message = options['message'];
      }

      // Check whether we should listen to form elements for focus
      //  to go on alert
      if ($H(options).keys().include('listen_for_form_focus')) {
        this.listenForFormFocus = options['listen_for_form_focus'];
      }

      // Setup our "excluded links" which will disable the bugging message
      excluded_links = [];
      if (links = options['excluded_links']) {
        links.each(function (link) {
          excluded_links.push($(link));
        });
      }

      excluded_links.each(function(link) {
        link.observe('click', function(e) {
          this.alert = false;
        }.bindAsEventListener(this));
      }.bind(this));

      // Bind to the forms's submit action so that we can disable the bugging
      // message when the user is submitting a form
      this.forms = forms;
      this.forms.each(function (form) {
        this_form = $(form);

        this_form.observe('submit', this._onFormSubmit.bindAsEventListener(this));

        if (this.listenForFormFocus) {
          // Listen to this form's elements for focus, which indicates user activity
          this_form.getElements().each(function(elt) {
              elt.observe('focus', function() {
                  this.alert = true;
              }.bindAsEventListener(this));
          }.bind(this));
        }

      }.bind(this));

      Event.observe(window, 'beforeunload', this._onBeforeUnload.bindAsEventListener(this));
    },

    setMessage : function(str) {
      this.message = str;
    },

    _onFormSubmit : function(e) {
      this.alert = false;
    },

    _onBeforeUnload : function(e) {
      // debug_ie("interrupting: " + this.alert);
      if (this.alert) { e.returnValue = this.message; }
    }
});

// debug_ie = function(message) {
//   debug_field = $('add_a_list');
//   if (debug_field) {
//     debug_field.value += message + "\n";
//   }
// }



function show_standard_error_box(message) {
  $('error_text').update(message);
  show_error_floater();
}

function ismaxlength(obj, showMsg, msgId) {
  var over;
  var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : ""
    if (obj.getAttribute && obj.value.length>=mlength) {
      over = true;
      obj.value=obj.value.substring(0,mlength)
    }

  if (showMsg && msgId) {
    if (over) {
      $(msgId).show();
    } else {
      $(msgId).hide();
    }
  }
}

function getHeight(){
  var yScroll;

  if (window.innerHeight && window.scrollMaxY) {
    yScroll = window.innerHeight + window.scrollMaxY;
  } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    yScroll = document.body.scrollHeight;
  } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    yScroll = document.body.offsetHeight;
  }

  var windowWidth, windowHeight;
  if (self.innerHeight) {  // all except Explorer
    windowHeight = self.innerHeight;
  } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    windowHeight = document.documentElement.clientHeight;
  } else if (document.body) { // other Explorers
    windowHeight = document.body.clientHeight;
  }

  // for small pages with total height less then height of the viewport
  if(yScroll < windowHeight){
    pageHeight = windowHeight;
  } else {
    pageHeight = yScroll;
  }
  return pageHeight + 'px';
}

var pb_floaters = new Array();

function open_floater(floater_name) {
  open_floater(floater_name, {});
}

function open_floater(floater_name, options) {
  if (!options) {
    options = {};
  }

  floater = pb_floaters[floater_name];

  if (!floater) {
    return false;
  }

  floater.show();

  callback = options.callback;

  if (callback) {
    callback();
  }

  hide_selects = options.hide_selects;

  hide_as_needed(hide_selects);
}

function close_floater(floater_name) {
  close_floater(floater_name, null);
}

function close_floater(floater_name, callback) {
  floater = pb_floaters[floater_name];

  if (!floater) {
    return false;
  }

  floater.hide();

  if (callback) {
    callback();
  }

  show_as_needed();
}