/*
 * Berkeley PBL v2.0
 *
 * Copyright (c) 2009 Anhang Zhu & Timothy Yung
 *
 */

if (!PBL) {
  var PBL = {};
}

PBL.init = {
  admin: function () {
      if ($('#role-assignment-form').length != 0){
        $('#role-assignment-form #member-selection ul').tabs({fx: {height: 'toggle', opacity: 'toggle'}});
        //Roles: Copy id's of selected people to hidden field to be sent
        $("#assign-roles").submit(function (event) {
          $("#people_id_list").val(PBL.admin.people_list.join(", "));
          $("#roles_id_list").val(PBL.admin.roles_list.join(", "));
        })
        //uncheck all checkboxes
        $("input[type='checkbox']:not([disabled='disabled'])").attr('checked', false);
      }
  },
  about: function () {
    var link = $("#executive-email-link");
    if (link.size() > 0) {
      link.attr("href", PBL.util.unmungeEmail(link.attr("href")));
    }

		div = $("#past-officers-table");
		form = $("#past-officers-search", div);
		form.submit(function() {
			$.ajax({
				type: "GET",
				dataType: "json",
				url: $(this).attr("action"),
				processData: false,
				data: $(this).serialize(),
				beforeSend: function(xmlhttprequest){
					$('.spinner', div).show();
					$(".content", div).fadeOut(100);
				},
				success: function(json){
					PBL.util.form.clearSelect($("select", form));
					$(".content", div).html(json.html);
				},
				complete: function(xmlhttprequest){
					$('.spinner', div).hide();
					$(".content", div).fadeIn(100);
				}
			});
			return false;
		});


  },
  blog: function () {
    $("#stickied p a").each(function () {
      $(this).hyphenate();
    });
    $("#recent-comments p a").each(function () {
      $(this).hyphenate();
    });

    if($('#post #new_comment').length != 0){
      PBL.blog.enable_mouseover_on_coment_controls();
      PBL.blog.enable_editable();
      PBL.blog.init_destroy_comments_buttons();
      PBL.blog.create_comment();
    }

    // Blog Index > New Post Form
    var postForm = $("#posts #new_post");
    if (postForm) {
      var titleInput = $("#post_title", postForm);
      var bodyEditor = $("#post_body", postForm);
      var cancelLink = $(".cancel", postForm)
      
      var defaultText = "Write a new blog post!";
      var isDefault = (titleInput.val() == "") || (titleInput.val() == defaultText);
      var showForm = function () {
        if (isDefault) {
          isDefault = false;
          this.value = "";
        }
        postForm.removeClass("collapsed");
      };
      var hideForm = function (event) {
        if ((bodyEditor.html() == "" && titleInput.val() == "") ||
            confirm("You will lose the contents of this post. Continue?")) {
          isDefault = true;
          titleInput.val(defaultText);
          bodyEditor.html("");
          postForm.addClass("collapsed");
        }
        event.preventDefault();
      };
      if (isDefault) {
        titleInput.val(defaultText);
        postForm.addClass("collapsed");
      }
      titleInput.focus(showForm);
      cancelLink.click(hideForm)
    }
    
    PBL.blog.attachments.init();
  },

  calendar: function () {
    if ($.fullCalendar) {
      var feedUrl = "/calendar/attending";
      $.getJSON(feedUrl, null, function (data) {
        var attendingIds = [];
        if (data.member) {
          for (var i = 0; i < data.event_ids.length; i++) {
            attendingIds[data.event_ids[i]] = true;
          }
        }
        
        switch ($("body").attr("id")) {
        case "home":
          PBL.upcomingEvents.load();
          break;
        case "calendar":
          $('#js-calendar').fullCalendar({
            header: {
              left:   'title',
              center: '',
              right:  'prev today next'
            },
            buttonText: {
              today: '&nbsp;This Month&nbsp;'
            },
            events: $.fullCalendar.gcalFeed(
              $("#js-calendar").attr("data-feed"),
              {className: 'gcal-events'}
            ),
            eventClick: function (calEvent, jsEvent, view) {
              PBL.overlay.events.show(calEvent);
              jsEvent.preventDefault();
            },
            eventRender: function (event, el) {
              $(el).attr("id", event.id);
              if (attendingIds[event.id]) {
                $(el).addClass("attending");
              }
            }
          });
          break;
        }
      });
    }
  },
  overlay: function () {

    $("#overlay").click(function (event) {
      var target = $(event.target);
      if (target.hasClass('close') ||
          target.closest(".aside").size() == 0) {
        PBL.overlay.hide();
        event.preventDefault();
      }
    });
    // Initialize event-info behavior if we will be using it.
    if ($.fullCalendar) {
      var div = $("#event-info");
      
      PBL.overlay.events.attendees.init();
    }
  },
  inlineLabels: function () {
    var label = function (input) {
      return $(input).prev("label.inlined");
    }
    var handlers = {
      focus: function () {
        label(this).addClass("focus");
      },
      keypress: function () {
        label(this).addClass("has-text").removeClass("focus");
      },
      blur: function () {
        if ($(this).val() == "") {
          label(this).removeClass("has-text").removeClass("focus");
        }
      }
    };
    $("label.inlined + input.text").each(function () {
      $(this).focus(handlers.focus);
      $(this).keypress(handlers.keypress);
      $(this).blur(handlers.blur);
      if ($(this).val() != "") {
        label(this).addClass("has-text");
      }
    });
  },
  loginForm: function () {
    var form = $("#sessions form");
    if (form.size() > 0) {
      var email = $("#email", form);
      var check = new LiveValidation(email.get(0), {
        onlyOnBlur: true
      });
      check.add(Validate.Email);
      check.validate();
    }
  },
  mailingList: function () {
    // Dynamic Form Validation
    var input = $("#mailing-list .text");
    var image = $("#mailing-list .submit");
    var check = new LiveValidation(input.get(0), {
      onValid: function () {
        image.attr("src", "/images/accept.png");
        image.attr("disabled", false);
      },
      onInvalid: function () {
        image.attr("src", "/images/accept-gray.png");
        image.attr("disabled", true);
      }
    });
    check.add(Validate.Presence);
    check.add(Validate.Email);
    check.validate();
    // Home Page Link
    var link = $("#mailing-list-link");
    if (link.size() > 0) {
      link.attr("href", PBL.util.unmungeEmail(link.attr("href")));
      link.click(function (event) {
        event.preventDefault();
        PBL.mailingList.scrollTo();
        setTimeout(PBL.mailingList.highlight, 250);
      });
    }
    $("#mailing-list").click(function () {
      PBL.mailingList.revertToNormal();
    });
  },
  feedback: function () {
    var div = $("#feedback-info");
    PBL.overlay.hide(div);
    var link = $("#feedback-link");
    if (link.size() > 0) {
      link.click(function (event) {
        event.preventDefault();
        PBL.overlay.show(div);
      });
    }



  },

  memberBar: function () {
    var el = $("#member-bar");
    // Show/hide member bar on mouseover/mouseout.
    el.mouseover(function () {
      el.addClass("hover");
    });
    el.mouseout(function () {
      el.removeClass("hover");
    });
    // Add AJAX to "Remember Me" checkbox.
    var feedUrlPrefix = $("p a:first", el).attr("href");
    $("#remember_me", el).change(function (event) {
      var checkbox = this;
      var remember = checkbox.checked;
      checkbox.disabled = true;
      
      var feedUrl = feedUrlPrefix;
      if (remember) {
        feedUrl += "/remember";
      } else {
        feedUrl += "/forget";
      }
      
      $.getJSON(feedUrl, null, function (data) {
        if (data.remember_me != remember) {
          alert("Unable to update your login status. Please try again.");
          checkbox.checked = data.remember_me;
        }
        checkbox.disabled = false;
      });
    });
  },
  memberForms: function () {
    // Stop autocomplete from messing with the user experience.
    $("#member_password").val("");
    
    // Validations
    var emailInput = $("#member_email");
    if (emailInput.size() > 0) {
      var check = new LiveValidation(emailInput.get(0), {
        onlyOnBlur: true
      });
      check.add(Validate.Email);
      check.add(Validate.Presence);
      check.validate();
    }
    
    var passwordInput = $("#member_password");
    var confirmPasswordInput = $("#member_password_confirmation");
    if (passwordInput.size() > 0 && confirmPasswordInput.size() > 0) {
      var check = new LiveValidation(passwordInput.get(0));
      check.add(Validate.Length, {
        minimum: 4,
        maximum: 40
      });
      var confirmCheck = new LiveValidation(confirmPasswordInput.get(0));
      confirmCheck.add(Validate.Confirmation, {
        match: passwordInput.get(0)
      });
    }
    
  },
  membersTable: function () {
    var lis = $("li.officer");
    $(".email", lis).each(function () {
      var link = $(this);
      var unmunge = PBL.util.unmungeEmail;
      link.text(unmunge(link.text()));
      link.attr("href", unmunge(link.attr("href")));
    });
    // Initialize page with an officer hovered.
    var hovered;
    if (window.location.hash == "#external-vp") {
      lis.each(function () {
        if (!hovered) {
          var position = $(".position", this).text();
          if (position.match(/.*Corporate/)) {
            hovered = $(this);
          }
        }
      });
    }
    if (!hovered) {
      hovered = $(lis.get(0));
    }
    hovered.addClass("hover");
    lis.mouseover(function () {
      if (hovered) {
        hovered.removeClass("hover");
        hovered = null;
      }
      var li = $(this);
      var details = $(".details", li);
      var windowHeight = $(window).height() - 20;
      var windowScroll = $(window).scrollTop();
      var offsetTop = li.offset().top - windowScroll
      li.addClass("hover");
      // Adjust position of hover if close to bottom.
      var detailHeight = details.height();
      
      var spaceLeft = windowHeight - (offsetTop + detailHeight);
      if (spaceLeft > 0) {
        spaceLeft = 0;
      }
      details.css("top", spaceLeft + "px");
      
    });
    lis.mouseout(function (event) {
      $(this).removeClass("hover");
    });
    // Unmunge mailing list addresses.
    $("#mailing-lists a").each(function () {
      var link = $(this);
      var unmunge = PBL.util.unmungeEmail;
      link.text(unmunge(link.text()));
      link.attr("href", unmunge(link.attr("href")));
    });
  },
  membersOnline: function () {
    var timeout = 30 * 1000;
    var feedUrl = "/members/online";
    var el = $("#site-info .online p");
    var handleHTML = function (html) {
      setTimeout(updateOnline, timeout);
      if (html != el.html()) {
        el.fadeOut("fast", function () {
          el.html(html).fadeIn("fast");
        });
      }
    };
    var updateOnline = function () {
      $.get(feedUrl, null, handleHTML);
    };
    updateOnline();
  },
  navigation: function () {
    var nav = $("#banner .nav");
    var defaultTip = $("p", nav);
    var hoveredTip = defaultTip;
    
    var defaultName = defaultTip.attr("class");
    // |showDefault| increments on each mouseout.
    // If it is negative, then an item is mouseovered.
    // It is used to ensure only the last mouseout timeout is successful.
    var showDefault = -1;
    
    var showHoveredTip = function (event) {
      showDefault = -Math.abs(showDefault);
      var name = $(this).closest("li").attr("class");
      if (!hoveredTip.hasClass(name)) {
        $("blurb").html(name);
        if (name == defaultName) {
          showDefaultTip();
        } else {
          var tipText = $(this).attr("title");
          var tip = $("<p>" + tipText + "</p>").addClass(name).css({
            left: Math.round(nav.width() / 2) + "px",
            opacity: 0
          });
          nav.append(tip);
          tip.animate({
            left: 0,
            opacity: 1
          }, {
            duration: 500,
            easing: "easeOutQuint"
          });
          hoveredTip.animate({
            opacity: 0
          }, 250, removeNode);
          hoveredTip = tip;
        }
      }
    };
    var showDefaultTip = function () {
      if (defaultTip != hoveredTip) {
        hoveredTip.animate({
            opacity: 0
          }, 250, removeNode);
        defaultTip.animate({
          opacity: 1
        }, {
          duration: 500,
          easing: "easeOutQuint"
        });
        hoveredTip = defaultTip;
      }
    };
    var delayShowDefaultTip = function (event) {
      showDefault = Math.abs(showDefault) + 1;
      var timeoutId = showDefault;
      setTimeout(function () {
        if (showDefault == timeoutId) {
          showDefaultTip();
        }
      }, 1500);
    };
    var removeNode = function () {
      if (this != defaultTip.get(0)) {
        $(this).remove();
      }
    };
    
    $("a", nav).mouseover(showHoveredTip).mouseout(delayShowDefaultTip);
  },
  permalink : function () {
    if ($.getUrlVars().indexOf("event") != -1 && $("#bad-event-id").html()!="true") {
      var div = $(".description", "#event-info");
      div.html(PBL.overlay.events.parse_desc(div.html()) || "<em>No description.</em>");
      PBL.overlay.show("#event-info");
    }
  },
  testBank: function () {
    var link = $(".test-bank a");
    if (link.size() > 0) {
      if (link.attr("href") == "#") {
        link.click(function (event) {
          alert("You must be an officer to access the test bank.");
          event.preventDefault();
        });
      }
    }
  },
  tinyMCE: function () {
    $('textarea.editor').tinymce({
      // Location of TinyMCE script
      script_url : "/javascripts/tiny_mce/tiny_mce.js",
      
      // General options
      theme: "advanced",
      skin: "o2k7",
      plugins: "safari,table,emotions,inlinepopups,media,paste",
      
      // Cleanup/output options
      cleanup_on_startup: true,
      fix_list_elements: true,
      fix_table_elements: true,
      fix_nesting: true,

      // Theme options
      theme_advanced_buttons1: "bold,italic,underline,strikethrough,|,link,unlink,|,bullist,numlist,outdent,indent,|,table,delete_table,|,row_before,row_after,delete_row,|,col_before,col_after,delete_col,|,image,media,emotions",
      theme_advanced_buttons2: "",
      theme_advanced_buttons3: "",
      theme_advanced_toolbar_location: "top",
      theme_advanced_toolbar_align: "left",

      // Paste options
      paste_remove_spans: true,
      paste_remove_styles: true,

      // Inline popups options
      inlinepopups_skin: "clearlooks2"
    });
  }
};

PBL.util = {
  formatEventDate: function (event) {
    if ($.fullCalendar) {
      var start = $.fullCalendar.parseDate(event.start);
      var end   = $.fullCalendar.parseDate(event.end);
      var string = "";
      if (event.allDay) {
        string += $.fullCalendar.formatDates(start, end, "dddd, M/d{[ 'to' dddd, M/d]}");
      } else {
        var startString = $.fullCalendar.formatDate(start, "dddd, M/d");
        var endString   = $.fullCalendar.formatDate(end,   "dddd, M/d");
        if (startString == endString || end == null) {
          string += startString + $.fullCalendar.formatDates(start, end, " @ h(:mm)[tt]{-[h(:mm)tt]}");
        } else {
          string += $.fullCalendar.formatDates(start, end, "M/d @ h(:mm)tt 'to' {M/d @ h(:mm)tt}");
        }
      }
      return string;
    }
  },
  unmungeEmail: function (email) {
    return email.replace(/(.+)\[(.+)\]/, '$1@$2');
  },
	linkify: function (text){
	   if (text) {
	    text = text.replace(
	      /((https?\:\/\/)|(www\.))(\S+)(\w{2,4})(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/gi,
	      function(url){
	        var full_url = url;
	        if (!full_url.match('^https?:\/\/')) {
	          full_url = 'http://' + full_url;
	        }
	        return '<a href="' + full_url + '">' + url + '</a>';
	      }
	    );
	   }
	   return text;
	},
	stripAnchors: function (str) {
		return str.replace(/<a.*?>/g, ' ').replace(/<\/a>/g,' ');
	},
	form : {
		clearSelect : function(fields){
			$.each(fields, function(index, form){
				$(form).val($('option:first', form).val()); 
			})
		}
	}

};

PBL.upcomingEvents = {
  load: function () {
    var eventList = $("#upcoming ol");
    var endDate = eventList.attr("data-end");
    var limit   = eventList.attr("data-limit");
    
    var feedURL = eventList.attr("data-feed");
    var getFeed = $.fullCalendar.gcalFeed(feedURL);
    
    var start = new Date();
    var end = new Date(endDate);
    
    $("#upcoming ol").html("<li class=\"loading\">Loading events...</li>");
    
    var callback = function (events) {
      $("#upcoming ol").html("");
      events.sort(PBL.upcomingEvents.compareEvents);
      events = events.slice(0, limit);
      $(events).each(function (i) {
        PBL.upcomingEvents.createEvent(this);
      });
      $("#upcoming ol").click(PBL.upcomingEvents.clickHandler);
    };
    
    getFeed(start, end, callback);
  },
  createEvent: function (event) {
    // Event: allDay, description, end, id, location, start, title, url
    var li = $("<li><h3></h3><abbr></abbr></li>");
    li.attr("data-event", $.JSON.encode(event));
    if (this.inCurrentWeek(event)) {
      li.addClass("current-week");
    }
    $("h3", li).text(event.title);
    $("abbr", li).attr({
      title: event.start
    }).text($.fullCalendar.formatDate(event.start, "M/d"));
    if (event.location) {
      li.append(" in <address></address>");
      $("address", li).text(event.location);
    } else {
      li.append(" (Location TBA)");
    }
    
    li.mouseover(function () {
      li.addClass("hover");
    });
    li.mouseout(function () {
      li.removeClass("hover");
    });
    
    $("#upcoming ol").append(li);
  },
  clickHandler: function (event) {
    var data = $(event.target).closest("li").attr("data-event");
    if (data) {
      PBL.overlay.events.show($.JSON.decode(data));
      event.preventDefault();
    }
  },
  compareEvents: function(event1, event2) {
    var start1 = $.fullCalendar.parseDate(event1.start);
    var start2 = $.fullCalendar.parseDate(event2.start);
    return start1 - start2;
  },
  inCurrentWeek: (function () {
    var current = (new Date()).getTime();
    var fromEnd = (7 - new Date().getDay()) * 24 * 60 * 60 * 1000;
    var weekEnd = new Date(current + fromEnd);
    weekEnd.setHours(0);
    weekEnd.setMinutes(0);
    weekEnd.setSeconds(0);
    weekEnd.setMilliseconds(0);
    
    return function(event) {
      var start = $.fullCalendar.parseDate(event.start);
      return (weekEnd - start) > 0;
    };
  })()
};

PBL.overlay = {
  show: function (id) {

    // Show the overlay.
    $("#overlay").css({display: 'block'});
    $(id).css({
      display: 'block',
      opacity: 0
    }).animate({
      opacity: 1,
      duration: 100
    });
    // Vertically center the overlay.
    // NOTE: Can only be done after display is set to block.
    var windowHeight = $(window).height();
    var overlayHeight = $(id).height();
    var marginTop = Math.round((windowHeight - overlayHeight) / 2);
    if (marginTop < 0) {
      marginTop = 0;
    }
    $(id).css({
      marginTop: marginTop + "px"
    });
  },
  hide: function () {
    $("#overlay").css({display: 'none'});
    $("#overlay .aside").css({display: 'none'});
  },
  events: {
    parse_desc: function (msg){
            //[IMG] tag
            msg = msg.replace(/\[IMG\]\s*(.+)\s*\[\/IMG\]/, '<img src="$1" width="425"/>'); //IMAGE WIDTH IN CALENDAR

            //[URL] tag
            msg = msg.replace(/\[URL\s*=\s*(.+)\]\s*(.+)\s*\[\/URL\]/g, '<a href="$1">$2</a>');

            //[LIST] and [*] tags
            msg = msg.replace(/\[LIST\]([^\`]*)\[\/LIST\]/g, '<ul>$1</ul>'); //hacky. any list with the character ` will break this tag.
            msg = msg.replace(/\[\*\]\s*(.+)\s*/g, '<li>$1</li>')

            //line break
            msg = (msg.replace(/]/g, "] <br />")).replace(/\\\\/g,"<br />");
            return msg;
    },
    show: function (event) {
      // Event: allDay, description, end, id, location, start, title, url
      var div = $("#event-info");
      div.attr({"data-id": event.id});
      $(".header h3", div).html(event.title);
      $(".footer abbr", div).attr({title: event.start}).html(PBL.util.formatEventDate(event));
      $(".footer address", div).html(event.location || "<em>Not Available</em>");
      
      //Permalink setup
      var stripped_id = event.id.match(/(.*)@google.com/)[1];
      var permalink = "<a title='Permalink of "+event.title+"' href='http://berkeleypbl.com/?event=" + stripped_id + "'>\n\
        http://berkeleypbl.com/?event=" + stripped_id + "</a>";
      $(".permalink", div).html("<p>Permalink: "+permalink+"</p>");

      //Custom formatting, since GCal does not have html-valid line breaks, we use \\ and ]
      //var parsed_desc = (event.description.replace(/]/g, "] <br />")).replace(/\\\\/g,"<br />");
      $(".description", div).html(PBL.overlay.events.parse_desc(event.description) || "<em>No description.</em>");
      
		 //facebook like
	  	$(".like", div).html("<iframe src='http://www.facebook.com/plugins/like.php?href=http://berkeleypbl.com/?event=" +  stripped_id+"&amp;layout=standard&amp;show_faces=true&amp;width=450&amp;action=like&amp;font=tahoma&amp;colorscheme=light&amp;height=80' style='border: medium none; overflow: hidden; width: 450px; height: 80px;' allowtransparency='true' frameborder='0' scrolling='no'></iframe>");


      this.attendees.load(event.id);

      PBL.overlay.show(div);
    },
    attendees: {
      updating: false,
      driverCheckboxHandler: function (event) {
        var self = PBL.overlay.events.attendees;
        
        var rsvpCheckbox = $("#rsvp").get(0);
        if (rsvpCheckbox.checked) {
          self.rsvpCheckboxHandler(event);
        }
      },
      rsvpCheckboxHandler: function (event) {
        var self = PBL.overlay.events.attendees;
        var div = $("#event-info");
        
        if (self.updating) {
          alert("Already updating RSVP status. Please wait and try again.");
          event.preventDefault();
        } else {
          self.updating = true;
          var event_id = div.attr("data-id");
          
          var rsvpCheckbox = $("#rsvp").get(0);
          var status = rsvpCheckbox.checked;
          
          var driverCheckbox = $("#driver").get(0);
          var is_driver = driverCheckbox.checked;
        
          var feedUrl = "/calendar/rsvp/" + escape(event_id);
          var params = {status: status, is_driver: is_driver};
          rsvpCheckbox.disabled = true;
          driverCheckbox.disabled = true;
          $.getJSON(feedUrl, params, function (data) {
            rsvpCheckbox.disabled = false;
            // If member exists, then we are logged in.
            if (data.member) {
              if (status) {
                self.add(data.member, data.is_driver, "moments ago");
                $(document.getElementById(event_id)).addClass("attending");
                driverCheckbox.disabled = false;
              } else {
                self.remove(data.member);
                $(document.getElementById(event_id)).removeClass("attending");
              }
            }
            driverCheckbox.checked = data.is_driver;
            self.updating = false;
          });
        }
      },
      add: function (member, is_driver, rsvped_at) {
        var li;
        $("#event-info .attendees ol li").each(function () {
          if ($(this).attr("data-id") == member.id) {
            li = $(this);
          }
        }); 
        if (!li) {
          var formatted_time = rsvped_at.replace(/(.+)T(.+)-.+/, '$1 $2')
          li = $("<li title = 'Registered " + formatted_time + "'>" + member.name + "</li>");
          li.attr("data-id", member.id)
          $("#event-info .attendees ol").append(li);
          this.setCount($("#event-info .attendees ol li").size());
        }
        if (is_driver) {
          li.addClass("driver");
        } else {
          li.removeClass("driver");
        }
        
      },
      remove: function (member) {
        $("#event-info .attendees ol li").each(function () {
          var li = $(this);
          if (li.attr("data-id") == member.id) {
            li.remove();
          }
        });
        this.setCount($("#event-info .attendees ol li").size());
      },
      setCount: function (count) {
        var text = "Attendees";
        if (count || count == 0) {
          text += " (" + count + ")";
        }
        $("#event-info .attendees h3").text(text);
      },
      init: function () {
        $("#rsvp").change(this.rsvpCheckboxHandler);
        $("#driver").change(this.driverCheckboxHandler);
      },
      load: function (event_id) {
        var self = PBL.overlay.events.attendees;
        var div = $("#event-info");
        
        self.setCount(null);
        $(".attendees ol", div).html("<li>Loading...</li>");
        $("#rsvp").attr({
          checked: false,
          disabled: true
        });
        $("#driver").attr({
          checked: false,
          disabled: true
        });
    
        var feedUrl = "/calendar/attendees/" + escape(event_id);
        var attendees = $.getJSON(feedUrl, null, function (data) {
          var members = data.attendees;
          var list = $(".attendees ol", div);
          list.html("");
          self.setCount(members.length);
          $(members).each(function () {
            self.add(this, this.is_driver, this.rsvped_at);
          });
          // If member exists, then we are logged in.
          if (data.member) {
            $("#rsvp").attr({
              checked: data.status,
              disabled: false
            });
            if (data.status) {
              $("#driver").attr({
                checked: data.is_driver,
                disabled: false
              });
            }
          }
        });
      }
    }
  }
};

PBL.mailingList = {
  scrollTo: function () {
    $(window).scrollTo($("#mailing-list"), {
      duration: 1000,
      easing: "easeOutQuint"
    });
  },
  highlight: function () {
    $("#mailing-list").css({
      backgroundColor: "#CCCCCC"
    }).animate({
      backgroundColor: "#222222"
    }, 1000);
  },
  revertToNormal: function () {
    $("#mailing-list").css({backgroundColor: "transparent"});
  }
};

PBL.blog = {
  attachments: {
    count: 0,
    init: function () {
      var self = this;
      var input = $("#attachment_file");
      input.attr("name", "attachment[ignore]");
      input.change(function (event) {
        if (input.val()) {
          self.process();
        }
      });
    },
    process: function () {
      var input = $("#attachment_file");
      var olist = input.closest("ol");
      
      var placeholder = $("<li class=\"attachment\" />").appendTo(olist);
      var filename = input.val().match(/([^\\\/]+)$/)[1];
      var textInput = $("<span/>").text(filename);
      var removeLink = this.createRemoveLink();
      removeLink.prepend(textInput);
      placeholder.append(removeLink);
      
      var newInput = input.clone(true).val(null);
      input.replaceWith(newInput).css({
        position: "absolute",
        left: "-3000px"
      }).appendTo(placeholder);
      
      input.attr({
        id:   null, // IDs are unique!
        name: "attachment[file][" + this.count + "]"
      });
      this.count++;
      
      this.init();
    },
    createRemoveLink: (function () {
      var html = "<a href=\"#\" title=\"Remove this attachment from the upload queue.\">Remove</a>";
      var handleClick = function (event) {
        $(this).closest("li").remove();
        event.preventDefault();
      };
      return function () {
        return $(html).click(handleClick);
      };
    })()
  },
  //Mouseover comment controls effect
  enable_mouseover_on_coment_controls : function(){
    var comment = $(".comment-entry");
    var comment_controls = $(".control");
    comment.mouseover(function () {
      comment_controls.addClass("hover");
    });
    comment.mouseout(function () {
      comment_controls.removeClass("hover");
    });
  },
  search : function(){
    $("#blog_search").submit(function (event) {
      if ($("#query").val().length < 4) {
        alert("Search parameters must be at least 4 characters.");
      event.preventDefault();
      }
    });
  },
  //Inline editing of text
  enable_editable : function(){
    var p = $('#comments .comment-entry.editable .text p');
    $.each(p, function(index, value){
			var comment_id = $(value).parent().parent().attr("id").match(/comment-(\d*)/)[1];
	    var url = ($('#new_comment').attr("action") + "/" + comment_id);
	    $(value).editable(url, {
	      indicator : '<img src="/images/spinner.gif"/>',
	      tooltip   : "Double-click to edit",
				event     : 'dblclick',
	      name      : 'comment[body]',
	      method    : 'PUT',
			  data		  : function(value, settings){
				  return PBL.util.stripAnchors(value);
			  },
			  callback  : function(value, settings){
				  $(this).html(PBL.util.linkify(value));
			  } 
	    });
			
		})

  },
  //Destroy comment buttons
  init_destroy_comments_buttons : function(){
    var destroy_buttons = $('#comments .control .destroy')
    destroy_buttons.removeAttr('onclick').unbind('click', false)
    destroy_buttons.click(function(){
      var b = $(this);
      $.delete_($(this).attr("href"), b.serialize(), function(json){
        if(json.success){
          b.parent().parent().fadeOut();
        }
      }, "json");
      return false;
    })
  },
  //Ajax comment creation with graceful degredation
  create_comment : function(){
    form = $('#new_comment');
    form.submit(function() {
      $.ajax({
        type: "POST",
        dataType: "json",
        url: $(this).attr("action"),
        processData: false,
        data: $(this).serialize(),
        beforeSend: function(xmlhttprequest){
          $('#comments .spinner').show();
        },
        success: function(json){
          $('#comments').children('ol').prepend(json.html);
          PBL.blog.enable_editable();
          PBL.blog.enable_mouseover_on_coment_controls();
          PBL.blog.init_destroy_comments_buttons();
          $("textarea", form).val("");
        },
        complete: function(xmlhttprequest){
          $('#comments .spinner').hide();
					$('#comments .tip').show().delay(1000).fadeOut(1000);
        }
      });

      return false;
    });
  }
};

PBL.admin = {
    people_list: [], //keep track of all member_id needed to assign roles
    people_html: [],
    roles_list: [],
    roles_html: [],
    toggle_people: function (checkbox) {
      if ($(checkbox).is(':checked')){
          PBL.admin.people_list.push($(checkbox).val());
          PBL.admin.people_html.push('<li>'+$(checkbox).attr('person_name')+'</li>');
      } else {
          PBL.admin.people_list.splice(PBL.admin.people_list.indexOf($(checkbox).val()), 1);
          PBL.admin.people_html.splice(PBL.admin.people_html.indexOf('<li>'+$(checkbox).attr('person_name')+'</li>'), 1);
      }
      $('#selected-members-list').html(PBL.admin.people_html.join(""));
    },
    toggle_roles: function (checkbox) {
      if ($(checkbox).is(':checked')){
          PBL.admin.roles_list.push($(checkbox).val());
          PBL.admin.roles_html.push('<li>'+$(checkbox).attr('role_name')+'</li>');
      } else {
          PBL.admin.roles_list.splice(PBL.admin.roles_list.indexOf($(checkbox).val()), 1);
          PBL.admin.roles_html.splice(PBL.admin.roles_html.indexOf('<li>'+$(checkbox).attr('role_name')+'</li>'), 1);
      }
      $('#selected-roles-list').html(PBL.admin.roles_html.join(""));
    },
    toggle_groups: function (title) {
      $('#'+title+' > li input:checkbox').each(function(index) {
        $(this).click();
      });
    }

}

$(document).ready(function () {
  PBL.init.tinyMCE();
  PBL.init.admin();
  PBL.init.about();
  PBL.init.blog();
  PBL.init.calendar();
  PBL.init.overlay();
  PBL.init.inlineLabels();
  PBL.init.loginForm();
  PBL.init.mailingList();
  PBL.init.feedback();
  PBL.init.memberBar();
  PBL.init.memberForms();
  PBL.init.membersTable();
  PBL.init.membersOnline();
  PBL.init.navigation();
  PBL.init.testBank();
  PBL.init.permalink();

  
});


$.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  }
});

$.extend({
  put: function(url, data, callback, type) {
      return _ajax_request(url, data, callback, type, 'PUT');
  },
  delete_: function(url, data, callback, type) {
      return _ajax_request(url, data, callback, type, 'DELETE');
  }
});
function _ajax_request(url, data, callback, type, method) {
    if (jQuery.isFunction(data)) {
        callback = data;
        data = {};
    }
    return jQuery.ajax({
        type: method,
        url: url,
        data: data,
        success: callback,
        dataType: type
        });
}
$.ajaxSetup({'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}});
