var CSS3_prepends = ["Moz", "Webkit"];
// Tests for checking CSS3 support.
// TODO: rgba test
var CSS3Support = {
  // Test for borderRadius
  borderRadius: function() {
    for(var i = 0; i < CSS3_prepends.length; i++) {
      if(document.body.style[CSS3_prepends[i] + "BorderRadius"] != undefined) return true;
    };
    return false;
  },
  // Test for boxShadow
  boxShadow: function() {
    for(var i = 0; i < CSS3_prepends.length; i++) {
      if(document.body.style[CSS3_prepends[i] + "BoxShadow"] != undefined) return true;
    };
    return false;
  }
};

// TODO allow a 'corner-skip' selector or force corner (i.e. on elements that may not have the box className)
function RoundedCorners(element) {
  var boxes = element ? [element] : $$('div.box, ol.box');
  var classes = ["tl", "tr", "bl", "br"];
  var mainClass = "corner";
  
  function createDomCorners() {
    var container = document.createElement("DIV");
    container.style.clear = "both";
    container.style.width = container.style.height = "0px";
    var corner;
    for(var j = 0; j < classes.length; j++) {
      corner = document.createElement("DIV");
      corner.className = [mainClass, mainClass + "-" + classes[j]].join(" ");
      container.appendChild(corner);
    };
    return container;
  };
  
  var div = createDomCorners();
    for(var i = 0; i < boxes.length; i++) {
    var box = boxes[i];
    (function() {
      box.style.overflow = "visible";
      box.appendChild(div.cloneNode(true));
    })();
  };
};
Event.addBehavior({ 'body' : function() { if(CSS3Support.borderRadius() == false) new RoundedCorners() }});
Event.addBehavior({ 'body#my-home h2#welcome-header' : function() { if(CSS3Support.borderRadius() == false) new RoundedCorners(this) }});


/** Browser viewport alignment fix **/
function doAlignmentFix() {
  function fix() {
    var obj = $$('html')[0];
    if((document.width + parseInt(obj.style.marginLeft)) % 2 == 1) {
      obj.style.marginLeft = "-1px;";
    } else {
      obj.style.marginLeft = "0px;";
    };
  };
  if('\v' != 'v') {
    window.onresize = fix;
    fix();
  };
};
var alignmentFix = Behavior.create({
  initialize: doAlignmentFix
});
Event.addBehavior({ 'body' : alignmentFix });
/** End browser viewport alignment fix **/

/*** Facebook Connect ***/
var triggerFacebook = Behavior.create({
  onclick: function() {
    triggerFBC(this.element.href);
    return false;
  }
});
Event.addBehavior({ '.do-facebook' : triggerFacebook });

function triggerFBC(url) {
    new Ajax.Request(url, {
      method: 'post',
      parameters: 'authenticity_token='+AUTH_TOKEN
    });
};

function facebookLogout(url) {
  var url = url;
  // Logout of facebook, logout of bragster through a callback
  FB.Connect.logout(function() { bragsterLogout(url) });

  // After 3 seconds, if facebook have not responded, log out of bragster anyway
  setTimeout(function(){ bragsterLogout(url) }, 3000);
};
function bragsterLogout(url) {
  window.location = url;
};

var facebookLogoutListener = Behavior.create({
  onclick: function() {
    facebookLogout(this.element.href);
    return false;
  }
});
Event.addBehavior({ 'a.fbc-logout' : facebookLogoutListener });

/*** General ***/
Event.addBehavior.reassignAfterAjax = true;

/** submit a form with ajax **/
var AjaxForm = function(element) {  
  new Ajax.Request(element.action, { asynchronous: true,
                                     evalScripts: true,
                                     method: element.method,
                                     parameters:Form.serialize(element)
                                    });
};
var remoteFormListener = Behavior.create({
  onsubmit: function() {
    new AjaxForm(this.element);
    return false;
  }
});
Event.addBehavior({ 'form.remote' : remoteFormListener });
/** end submit a form with ajax **/
/** Tabbed content **/
function tabbedContent(element) {
  var content = [];
  var tabCollection = element.getElementsByTagName("a");
  var obj = this;
  var defaultContent;

  function initialize() {
    for(var i = 0; i < tabCollection.length; i++) {
      (function() {
        var currentTab = tabCollection[i];
        Element.extend(currentTab);
        var contentID = currentTab.href.gsub(/.*?#/, '');
        var o = {};
        if(e = $(contentID)) {
          o.element = e;
          o.tab = currentTab;
          o.zIndex = tabCollection.length + 1 - i;
          content.push(o);
        };
        currentTab.style.zIndex = tabCollection.length + 1 - i;      
        currentTab.onclick = function() { obj.setActiveTab(o); return false };
        if(currentTab.hasClassName("active")) defaultContent = o;
      })();
    };
    tabCollection[0].addClassName("first");
  };

  this.setActiveTab = function (contentObject) {
    for(var i = 0; i < content.length; i++) {
      (function() {
        var currentContent = content[i];
        if(currentContent != contentObject) {
          currentContent.element.addClassName("hide");
          currentContent.tab.removeClassName("active");
          currentContent.tab.removeClassName("active-first");
          currentContent.tab.style.zIndex = currentContent.zIndex;
        } else {
          currentContent.element.removeClassName("hide");
          currentContent.tab.addClassName("active");
          currentContent.tab.style.zIndex = "";
          if(currentContent.tab == tabCollection[0]) currentContent.tab.addClassName("active-first");
        };
      })();
    };
  };
  initialize();
  this.setActiveTab(defaultContent);
};

var tabbedContentListener = Behavior.create({
  initialize: function() { new tabbedContent(this.element); }
});
Event.addBehavior({ 'ul.tabs' : tabbedContentListener });
/** End tabbed content **/
/** Character limiter **/
function CharLimiter(element) {
  var notifier = element;
  var text = " characters remaining";
  var maxLength = parseInt(notifier.innerHTML.replace(text, ""), 10);

  var field = $(notifier.id.replace(/^observe-/,""));
  if(field) {
    field.onkeyup = function() {
      notifier.innerHTML = (maxLength - field.value.length) + text;
      if(maxLength - field.value.length < 0) {
        notifier.addClassName("excess-characters");
      } else {
        notifier.removeClassName("excess-characters");
      };
    };
    field.form.onsubmit = function() {
      if(maxLength - field.value.length < 0) {
        alert('Sorry, the field cannot be longer than ' + maxLength + ' characters');
        return false;
      };
      return;
    };
  };
};
var charLimitListener = Behavior.create({
  initialize: function() { new CharLimiter(this.element); }
});
Event.addBehavior({ "span.characters-remaining" : charLimitListener });
/** End character limiter **/
/** Find position of an element relative to document.body **/
function findPos(obj) {
  var curleft = curtop = 0;
  if (obj.offsetParent) {
    do {
      curleft += obj.offsetLeft;
      curtop += obj.offsetTop;
    } while (obj = obj.offsetParent);
    return [curleft,curtop];
  };
};
/** End position of element **/

/** Basic switch display of two elements **/
function switchDisplay(elementHide, elementShow) {
  Element.extend(elementHide);Element.extend(elementShow);
  elementHide.addClassName("hide");
  elementShow.removeClassName("hide");
};
/** End switch display of two elements **/
/** Toggle display between two elements **/
function toggleDisplay(elementA, elementB) {
  Element.extend(elementA);Element.extend(elementB);
  if(elementA.hasClassName("hide") && !elementB.hasClassName("hide")) {
    switchDisplay(elementB, elementA);
  } else if(elementB.hasClassName("hide") && !elementA.hasClassName("hide")) {
    switchDisplay(elementA, elementB);
  };
};
/** End toggle display between two elements **/
/** Toggle the display of a single element **/
function toggleElement(element) {
  Element.extend(element);
  if(element.hasClassName("hide")) {
    element.removeClassName("hide");
    return true;
  } else {
    element.addClassName("hide");
    return false;
  };
};
/** End toggle the display of a single element **/
/** Expand & retract content **/
function expandRetract(element) {
  Element.extend(element);
  Element.extend(element.parentNode.parentNode);
  if(element.hasClassName("expand")) {
    var fullContent = element.parentNode.parentNode.down(".more-description");
    var previewContent = element.parentNode;
    element.onclick = function() {
      switchDisplay(previewContent, fullContent);
      return false;
    };
  } else if(element.hasClassName("retract")) {
    var fullContent = element.parentNode;
    var previewContent = element.parentNode.parentNode.down(".less-description");
    element.onclick = function() {
      switchDisplay(fullContent, previewContent);
      return false;
    };
  };
};
var expandRetractListener = Behavior.create({
  initialize: function() { new expandRetract(this.element); }
});
Event.addBehavior({ 'a.expand-retract' : expandRetractListener });
/** End expand & retract content **/
/** hasDefaultValue fields **/
function hasDefaultValue(defaultString) {
  if(!this.value) this.value = defaultString;
  this.default_value = (typeof this.default_value == "undefined" ? this.value : this.default_value);
  this.onfocus = function() {
    if(this.tagName != "TEXTAREA") {
      if(this.value == this.default_value)  { this.value = ""; this.style.color = "#333333" };
    } else {
      if(this.value == this.innerHTML) { this.value = ""; this.style.color = "#333333" };
    };
    return true;
  };
  this.onblur = function() {
    if(this.id != "email_addresses_visible") {
      if(this.value.length == 0) { this.value = this.default_value; this.style.color = "#999999" };
    };
  };
}
var hasDefaultValueListener = Behavior.create({
  initialize: function() { hasDefaultValue.call(this.element, this.element.value); }
});
Event.addBehavior({ ".has-default-value" : hasDefaultValueListener });
/** End hasDefaultValue fields **/
/*** End General ***/

/*** Brag ***/
/*** End Brag ***/

/*** Dare ***/
function SlideableDare(element) {
  var o = this;
  this.ppf = 30;
  this.expandedX = -121;
  this.button = Element.extend(element);
  this.state = false;
  this.aInterval;
  this.dare = this.button.parentNode;
  this.dare.style.left = "0px";
  this.buttonText = this.button.innerHTML;
  this.dare.behavior = function(_state) {
    o.state = _state;
    o.trigger();
  };
  this.button.onclick = function() {
    o.trigger();
    return false;
  };
};
SlideableDare.prototype.trigger = function() {
  var o = this;
  clearInterval(this.aInterval);
  this.state = !(this.state);
  this.aInterval = setInterval(function() {o.animate()}, 25);
};
SlideableDare.prototype.animate = function() {
  this.x = parseInt(this.dare.style.left, 10);
  if(this.state == true) {
    if(this.x > this.expandedX) {
      var target = this.x - this.ppf;
      if(target <= this.expandedX) {
        this.finish(this.expandedX);
      } else {
        this.dare.style.left = this.x - this.ppf + "px";
      };
    } else {
      this.finish(this.expandedX);
      return;
    };
  } else if(this.state === false) {
    if(this.x < 0) {
      var target = this.x + this.ppf;
      if(target >= 0) {
        this.finish(0);
      } else {
        this.dare.style.left = this.x + this.ppf + "px";
      };
    } else {
      this.finish(0);
      return;
    };
  };
};
SlideableDare.prototype.finish = function(x) {
  this.dare.style.left = x + "px";
  clearInterval(this.aInterval);
  if(this.state == true) {
    this.button.removeClassName("icon-alt-expand-left");
    this.button.addClassName("icon-alt-expand-right");
    this.button.innerHTML = this.buttonText.replace(/^View/, "Hide");
  } else {
    this.button.addClassName("icon-alt-expand-left");
    this.button.removeClassName("icon-alt-expand-right");
    this.button.innerHTML = this.buttonText;
  };
  return;
};

var dareSliderListener = Behavior.create({
  initialize: function() { new SlideableDare(this.element); }
});
Event.addBehavior({ 'li.dare a.see-latest-evidence' : dareSliderListener });

var allDareSliderListener = Behavior.create({
  initialize: function() {
    this.state = false;
    this.text = this.element.innerHTML;
  },
  onclick: function() {
    this.state = !(this.state);
    this.element.innerHTML = (this.state == false ? this.text : this.text.replace(/^View/, "Hide"));
    var dares = $$('div.column-8 li.dare');
    for(var i = 0; i < dares.length; i++) {
      if(dares[i].behavior) dares[i].behavior(!this.state);
    };
    return false;
  }
});
Event.addBehavior({ 'a.preview-all-dare-entries' : allDareSliderListener });
/*** End Dare ***/
/** Medal gallery medal viewer **/
function MedalGallery(button) {
  var button = button;
  var container = Element.extend(button.parentNode.parentNode).previous();

  function whileLoading() {
    container.innerHTML = "<div><img src=\"/images/ui_icons/ajax-loader.gif\" width=\"16\" height=\"16\" alt=\"loading\" /></div>";
  };

  button.onclick = function() {
    if(!button.hasClassName('unattained')) {
      new Ajax.Request(button.href, {
        method: "get",
        onLoading: whileLoading
      });
    };
    return false;
  };
};
var medalGalleryListener = Behavior.create({
  initialize: function() { new MedalGallery(this.element); }
});
Event.addBehavior({ 'body#profile div.medals a.medal-thumb' : medalGalleryListener });
/** End gallery medal viewer **/

/** Forum post tasks **/
function ForumThread(commentList) {
  var commentList = commentList;
  var replyButtons = commentList.getElementsByClassName('reply-to');
  var childrenButtons = commentList.getElementsByClassName('show-children');
  var field = $('forum_post_reply_to_id');
  var form = $('new_forum_post');
  var messageField = $('forum_post_message');

  function replyButtonOnClick() {
    var pID = this.parentNode.parentNode.id.replace("comment-", "");
    field.value = pID;
    form.scrollTo();
    new Effect.Highlight(messageField);
    messageField.focus();
  };
  
  function childrenButtonOnClick() {
    var childThread = this.next('ol.children');
    if(toggleElement(childThread) == true) {
      this.innerHTML = this.innerHTML.replace(/Show/, "Hide");
      this.className = "show-children icon-alt icon-alt-expand-down";
    } else {
      this.innerHTML = this.innerHTML.replace(/Hide/, "Show");
      this.className = "show-children icon-alt icon-alt-expand-right";
    };
  };

  for(var i = 0; i < replyButtons.length; i++) {
    (function() {
      var button = replyButtons[i];
      button.onclick = function() { replyButtonOnClick.call(button); return false };
    })();
  };
  
  for(var i = 0; i < childrenButtons.length; i++) {
    (function() {
      var button = childrenButtons[i];
      button.onclick = function() { childrenButtonOnClick.call(button); return false };
    })();
  };

};
var forumThreadListener = Behavior.create({
  initialize: function() { new ForumThread(this.element); }
});
Event.addBehavior({ 'ol#comments' : forumThreadListener });
/** End forum post tasks **/

/* Add media to comment */
function CommentMedia(optionContainer) {
  var optionContainer = optionContainer;
  var buttons = optionContainer.getElementsByTagName("A");
  var fields = $$('form#new_forum_post li.media');
  for(var i = 0; i < buttons.length; i++) {
    (function() {
      var button = buttons[i];
      Element.extend(button);
      button.onclick = function() {
        for(var j = 0; j < fields.length; j++) {
         (function() {
           var field = fields[j];
           Element.extend(field);
           if(field.id == (button.getAttribute('rel'))) {
             field.hasClassName("hide") ? field.removeClassName("hide") : field.addClassName("hide");
           } else {
             if(!field.hasClassName("hide")) field.addClassName("hide");
           }
         })();
        };
        return false;
      };
    })();
  };
}
var commentMediaListener = Behavior.create({
  initialize: function() { new CommentMedia(this.element); }
});
Event.addBehavior({ 'div#attach-media' : commentMediaListener })


/** Start avatar menu **/
var singletonAvatarMenu;
function AvatarMenu() {
  var o = this;
  this.positionOffset = 4;

  function constructMenu() {
    var elements = [];
    elements.push(o.container = document.createElement('div'));
    elements.push(o.menuUserThumb = document.createElement('div'));
    elements.push(o.userName = document.createElement('h4'));
    elements.push(o.country = document.createElement('span'));
    elements.push(o.brights = document.createElement('span'));
    elements.push(o.menuToggle = document.createElement('a'));
    elements.push(o.menuList = document.createElement('ul'));
    
    for(var i = 0; i < elements.length; i++) {
      (function() {
        var e = elements[i];
        Element.extend(e);
        if(e != o.container) o.container.appendChild(e);
      })();
    };

    var li;
    for(var i = 0; i < 5; i++) {
      li = document.createElement("li");
      o.menuList.appendChild(li);
    };
    li.className = "last";
    
    o.container.addClassName("avatar-menu hide");
    o.menuUserThumb.addClassName("user-thumbnail");
    o.country.addClassName("country");
    o.brights.addClassName("bragging-rights");
    o.menuToggle.addClassName("menu-toggle");
    o.menuList.addClassName("type-1");
  
    o.menuToggle.href = "#toggle-menu";
    o.menuToggle.onmouseover = function() {
      o.container.addClassName("avatar-menu-show");
    };
    
    o.container.onmouseout = function(e) {
      var e = e || window.event;
      if(isMouseLeaveOrEnter(e, o.container)) {
        o.container.removeClassName("avatar-menu-show");
        o.container.addClassName("hide");
      };
    };
    
    document.body.appendChild(o.container);
    return true;
  };
  
  if(!this.container) {
    constructMenu();    
  };
};

AvatarMenu.prototype.addItem = function(item) {
  var item = Element.extend(item);
  var o = this;
  item.onmouseover = function() { o.switchTo(item) };
};

AvatarMenu.prototype.switchTo = function(element) {
  var e = element;
  var coords = findPos(e);
  var o = this; 
  var listItem;
  
  function fillData() {
    var jsonContainer = e.next("span");
      var data = jsonContainer.innerHTML.evalJSON();
      function revertHTML(d, p) {
        d[p] = d[p].gsub(/&lt;/, "<").gsub(/&gt;/, ">");
      };
      for(var prop in data) {
        if(typeof data[prop] == "string") {
          revertHTML(data, prop);
        };
      };
      var listItem = Element.extend(o.menuList.down());
      for(var prop in data.submenu) {
        if((typeof data.submenu[prop] == "string") && listItem) {
          revertHTML(data.submenu, prop);
          listItem.innerHTML = data.submenu[prop];
          listItem = listItem.next();
        };
      };
      o.menuUserThumb.innerHTML = data.image;
      o.userName.innerHTML = data.nickname;
      o.country.innerHTML = data.flag_img;
      o.brights.innerHTML = data.brights;
      return true;
  };
  
  if(fillData() == true) {
    this.container.style.left = coords[0] - this.positionOffset + "px";
    this.container.style.top = coords[1] - this.positionOffset + "px";
    this.container.removeClassName("hide");
  };
};

var avatarMenuListener = Behavior.create({
  initialize: function() { 
    if(typeof window.singletonAvatarMenu == "undefined") {
      singletonAvatarMenu = new AvatarMenu();
    };
    singletonAvatarMenu.addItem(this.element);
  }
});
Event.addBehavior({" img.has-menu" : avatarMenuListener });


function UpdateFanLinks(selector, content) {
  var elements = $$('span.' + selector);
  for(var i = 0; i < elements.length; i++) {
    elements[i].replace(content);
  };
};
/** End avatar menu **/

/** Expand retracted carousels **/
function ExpandCarousel(button) {
  var button = Element.extend(button);
  var carousel = button.previous();
  button.onclick = function() {
    if(carousel.hasClassName("carousel-container-expanded")) {
      carousel.removeClassName("carousel-container-expanded");
      button.removeClassName('icon-alt-expand-up');button.addClassName('icon-alt-expand-down');
      button.innerHTML = button.innerHTML.replace(/Hide/, "Expand");
    } else {
      carousel.addClassName("carousel-container-expanded");
      button.removeClassName('icon-alt-expand-down');button.addClassName('icon-alt-expand-up');
      button.innerHTML = button.innerHTML.replace(/Expand/, "Hide");
    };
    return false;
  };
};
var expandCarouselListener = Behavior.create({
  initialize: function() {
    new ExpandCarousel(this.element);
  }
});
Event.addBehavior({ 'a.expand-carousel' : expandCarouselListener });
/** End expand retracted carousels **/

/** Fan Brag carousels **/
var fanBragCarousel = Behavior.create({
    initialize: function() {
      new CarouselJs(this.element.id, { pauseInterval: 0.2, speed: 50 });
    }
});
Event.addBehavior({ 'body#my-home ul.fan-brags-carousel' : fanBragCarousel });
/** End Fan Brag carousels **/

/** Dare entry carousel **/
var dareEntriesCarousel = Behavior.create({
    initialize: function() {
      new CarouselJs(this.element.id, { pauseInterval: 0.2, speed: 30, defaultItemClass: "viewing-now"  });
    }
});
Event.addBehavior({ 'body#brag ul#brag-carousel' : dareEntriesCarousel });
/** End dare entry carousel **/


/** Episode carousels **/
var episodeCarousel = Behavior.create({
  initialize: function() {
    new CarouselJs(this.element.id, { pauseInterval: 0.2, speed: 30, defaultItemClass: "episode-offset" });
  }
});
Event.addBehavior({ 'body#group-page ul#episode-carousel' : episodeCarousel }); 
/** End episode carousels **/

/** Close flash notices/errors **/
var closeNotice = Behavior.create({
  initialize: function() {
    var e = this.element.up();
    if(!Prototype.Browser.IE) e.pulsate({ pulses: 1, duration: 1 });
  },
  onclick: function() {
    var e = this.element.up();
    new Effect.Fade(e, { duration: 0.3, afterFinish: function() { Element.remove(e) } });
  }
});
Event.addBehavior({ 'a.close-notice' : closeNotice });
/** End close flash notices/errors **/

/** Respond to the flash player to confirm it is not embedded */
function doBragsterEmbeddedPlayerCheck() {
  return true;
};
/** End flash player response*/

/* Homepage intro video */
var homepageVideo = Behavior.create({
    onclick: function() {
        var new_media_lightwindow = new LightWindow({ content_type: "remote", 
                                                      content_url: this.element.href, 
                                                      lose_focus: true, 
                                                      close_button: true });
        return false;
    }
})
Event.addBehavior({ 'body#visitor-home a.watch-intro-video' : homepageVideo });
/* End homepage intro video */

/* For communication to Actionscript's externalInterface */
function getFlashMovie(movieName) {
  var isIE = navigator.appName.indexOf("Microsoft") != -1;
  return (isIE) ? window[movieName] : document[movieName];
}
/* End communication to AS externalInterface */

/** 'Take Picture' video thumbnailer toggle **/
var toggleThumbnailerListener = Behavior.create({
  onclick: function() {
    if(bragPlayer) {
      new Effect.Fade(this.element.parentNode, { duration: 0.5 });
      var data = this.element.getAttribute("rel").split(";");
      bragPlayer.reload({ doThumbnailer: true, 
                          viewerid: data[0], 
                          fullscreen: false,  
                          authenticity_token: data[1] });
    };
    return false;
  }
});
Event.addBehavior({ 'body#brag a.choose-thumbnail' : toggleThumbnailerListener });
/** End 'Take Picture' video thumbnailer toggle **/

/** Javascript date countdown **/
function Countdown(targetDate, element) {
  var element = element;
  var monthArray = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
  var targetDate = targetDate;
  var today = new Date();
  var todayYear = today.getYear();

  if (todayYear < 1000) todayYear += 1900;

  var todayMonth = today.getMonth();
  var todayDay = today.getDate();
  var todayHour = today.getHours();
  var todayMin = today.getMinutes();
  var todaySec = today.getSeconds();

  var todaystring = monthArray[todayMonth] + " " + todayDay + ", " + todayYear + " " + todayHour + ":" + todayMin + ":" + todaySec;

  var dd = Date.parse(targetDate) - Date.parse(todaystring);
  var dday = Math.floor(dd/(60*60*1000*24)*1);
  var dhour = Math.floor((dd%(60*60*1000*24))/(60*60*1000)*1);
  var dmin = Math.floor(((dd%(60*60*1000*24))%(60*60*1000))/(60*1000)*1);
  var dsec = Math.floor((((dd%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1);

  if(dday==0&&dhour==0&&dmin==0&&dsec==1) {
    element.innerHTML = "Finished";
    return;
  } else {
    element.innerHTML = dday + " days, "+dhour+" hrs, "+dmin+" mins, "+dsec+" secs";
    setTimeout(function() { Countdown(targetDate, element)}, 1000);
  };
};
/** End Javascript date countdown **/

var competitionCountdownListener = Behavior.create({
  initialize: function() {
    new Countdown(this.element.className, this.element);
  }
});
Event.addBehavior({ 'body#dare-show span#competition-countdown' : competitionCountdownListener });

/** Login and sign up modal windows **/
var signupModal = Behavior.create({
  onclick: function() {
    this.ui = new Modal('signup-modal');
    this.ui.retrieveContent('/users/new', 'get');
    return false;
  }
});
Event.addBehavior({ 'ul.visitor-menu a#signup' : signupModal });

var loginModal = Behavior.create({
  onclick: function() {
    this.ui = new Modal('login-modal');
    this.ui.retrieveContent('/sessions/new', 'get');
    return false;
  }
});
Event.addBehavior({ 'ul.visitor-menu a#login' : loginModal });

var loginFieldDefaultValues = Behavior.create({
  initialize: function() {
    if(this.element.value == "") {
      var el = this.element;
      var replacement = document.createElement("INPUT");
      replacement = $(replacement);
      replacement.type = "text";
      replacement.style.color = "#999";
      replacement.value = "Password";
      replacement.className = "text";
      el.hide();
      el.parentNode.appendChild(replacement);
      replacement.onfocus = function() {
        replacement.remove();
        el.show();
        el.focus();
      };
    };
  }
});
Event.addBehavior({ 'form input.has-default-value-password' : loginFieldDefaultValues });
/** End login and sign up modal windows **/

/** OpenID service switcher (modal window version) **/
var modalOpenIdSwitcher = Behavior.create({
  onclick: function() {
    var providers = $$('div.modal div.openid-sign-in');
    for(var i = 0; i < providers.length; i++) { providers[i].hide() };
    var provider = $$('div.modal div#' + this.element.id + "-form")[0];
    $('default-form').hide();
    provider.hide();
    provider.removeClassName("hide");
    Effect.Appear(provider, { duration: 1 });
    return false;
  }
});
Event.addBehavior({ 'div.modal-openid ul a' : modalOpenIdSwitcher });
var modalCancelOpenId = Behavior.create({
  onclick: function() {
    var providers = $$('div.modal div.openid-sign-in');
    for(var i = 0; i < providers.length; i++) { providers[i].hide() };
    $('default-form').show();
    return false;
  }
});
Event.addBehavior({ 'div.modal a.cancel-openid-provider' : modalCancelOpenId });
/** End OpenID service switcher (modal window version) **/

/** Expand/Retract 'accepted dares' on my home **/
var expandRetractAcceptedDares = Behavior.create({
  initialize: function() {
    this.box = this.element.up("div.accepted-dares-container");
  },
  onclick: function() {
    if(this.box.hasClassName("retracted")) {
      this.box.removeClassName("retracted");
      this.element.removeClassName("icon-alt-expand-right"); this.element.addClassName("icon-alt-expand-down");
    } else { 
      this.box.addClassName("retracted");
      this.element.addClassName("icon-alt-expand-right"); this.element.removeClassName("icon-alt-expand-down");
    };
    return false;
  }
});
Event.addBehavior({ 'body#my-home div.dare-tasks a.toggle-display' : expandRetractAcceptedDares });
/** End Expand/Retract 'accepted dares' on my home **/

/** Switch between 'fan brags' categories on my home **/
var initFanBrags = Behavior.create({
  initialize: function() {
    loadedFanBrags = [this.element.down("div").id];
  }
});
Event.addBehavior({ 'body#my-home div#fan-brags' : initFanBrags });

var loadedFanBrags;
var viewFanBrags = Behavior.create({
  onclick: function() {
    var request = $(this.element.getAttribute("rel") + "-container");
    for(var i = 0; i < loadedFanBrags.length; i++) {
      $(loadedFanBrags[i]).hide();
    };
    if(request) {
      request.show();
    } else {
      $('fan-brags-loader').removeClassName("hide");
      new Ajax.Request(this.element.href, { method: 'get'});
    };
    return false;
  }
});
Event.addBehavior({ 'body#my-home div#fan-brags ul.categories a.load-fan-brags' : viewFanBrags });

function afterFanBragsLoaded(action) {
  loadedFanBrags.push(action + "-container");
  $('fan-brags-loader').addClassName("hide");
}
/** End switch between 'fan brags' categories on my home **/

/** EVERYTHING BELOW THIS LINE STILL NEEDS TO BE REFACTORED **/

// Auto-select flagged text-fields
var autoSelect = Behavior.create({
    onclick: function() {
        this.element.focus();
        this.element.select();
    }
});

Event.addBehavior({ 'input.autoselect' : autoSelect });

// Enhanced mouseover/mouseout detection.
function isMouseLeaveOrEnter(e, handler) { 
    if (e.type != 'mouseout' && e.type != 'mouseover') return false;
    var reltg = e.relatedTarget ? e.relatedTarget : 
    e.type == 'mouseout' ? e.toElement : e.fromElement; 
    while (reltg && reltg != handler) reltg = reltg.parentNode; 
    return (reltg != handler); 
}

// Comment pagination
var remotePagination = Behavior.create({
    onclick: function() {
        new Ajax.Request(this.element.href, {
          method: 'get',
          onLoading: showLoading('comments-content')
        });
        return false;
    }
});
Event.addBehavior({ 'div#comments-box ol.pagination a' : remotePagination});
Event.addBehavior({ 'div#brag-comments ol.pagination a' : remotePagination});

function showLoading (container, hide_container_id) {
    if (hide_container = $(hide_container_id)) {
        hide_container.innerHTML = "";
    }
    $(container).innerHTML = '<p class="loading"><img src="/images/ui_icons/ajax-loader.gif" /></p>';
}
function unShowLoading (container) {
    $(container).innerHTML = '';
}
var youtube_brag = false;
var chooseYoutubeVideo = Behavior.create({
    onclick: function() {
        vidId = this.element.id;
        $('youtube_video_id').value = vidId;
        //alert($('youtube_video_id').value);
        $('media-file-browse').style.display = 'none';
        $('media-file-youtube').innerHTML = '<img src="/images/logos/3rd-party/youtube-small.png" alt="Youtube logo" /> ' + 
            this.element.title +
            ' (<a href="#" onclick="cancelYoutubeVideo();">Cancel</a>)';
        document.location.href = "#content";
        if ($('brag_title').value == '') {
            $('brag_title').value = this.element.title;
            new Effect.Highlight('brag_title');
        }
        new Effect.Highlight('media-file');
        youtube_brag = true;
        return false;
    }
});
function cancelYoutubeVideo () {
    $('media-file-youtube').update('');
    $('youtube_video_id').value = '';
    $('media-file-browse').style.display = '';
    youtube_brag = false;
}

// Switch email providers for finding friends
var switchProvider = Behavior.create({
    onclick: function() {
        // hide all description blocks and show the 'new' one
        var divs = $$('ul#find-friends-providers div.service-description');
        var target_service = this.element.id;
        var target_div_id = this.element.id + '-provider-description';
        for (var i = 0; i < divs.length; i++) {
            curr_div_id = divs[i].id;
            parent_li = $(curr_div_id).up('li');
            if (divs[i].id == target_div_id) {
                divs[i].style.display = 'block';
                $(parent_li.id).className = 'active';
            }
            else {
                divs[i].style.display = 'none';
                $(parent_li.id).className = '';
            }
        }
        var parentList = $$('ul#email-provider-links li');
        for (var x = 0; x < parentList.length; x++) {
            parentList[x].removeClassName('active');
        }
        this.element.up('li').addClassName('active');
        
        return false;
    }
});

Event.addBehavior({ 'body#find-friends ul#email-provider-links a' : switchProvider });

var liveLogin = Behavior.create({
    onclick: function() {
        $('live-login-form').toggle();
        if ($('live-login-form').style.display == '') {
            $('live-login-form').addClassName('box-form');
            new Effect.Highlight('live-login-form');
            $('login_name').focus();
            $('email-tip').hide();
        } else {
            $('live-provider').removeClassName('box-form');
        }
        
    }
});
Event.addBehavior({ 'body#what_next a#live-service-link' : liveLogin });

// non-obtrusive link_to_remote for user action block

var actionRequest = Behavior.create({

    initialize: function() {
        this.action_request = new AjaxUserActions(this.element);
    },

    onclick: function() {
        if(this.element.hasClassName('blocked')) {
          return false;
        }
        this.action_request.createFeedbackBox();
        var action_request_priv = this.action_request;
        new Ajax.Request(this.element.href, {
            asynchronous:true,
            evalScripts:true,
            onLoad: action_request_priv.loading(),
            method:'post'
        });
        return false;
        //this.action_request.loading(); 
    }
});
Event.addBehavior({ 'a.user-action' : actionRequest});


// Ajax action responses
// make the addBehaviour for these links react to a toggle variable

function AjaxUserActions(element) {
    this.action_link = element;
    this.action_block = $$('div#actions')[0];
    this.action_list = $$('div#actions ul')[0];
    this.feedback_container = $('action-feedback');
    this.loader;
}

AjaxUserActions.prototype.loading = function() {
    this.loader = document.createElement('img');
    this.loader.src = "/images/ui_icons/ajax-loader.gif";
    this.loader.className = "ajax-loader";
    this.feedback_container.innerHTML = "";
    this.feedback_container.appendChild(this.loader);
}

AjaxUserActions.prototype.createFeedbackBox = function() {
    if(this.feedback_container == null) {
        this.feedback_container = document.createElement('div');
        this.feedback_container.id = "action-feedback";
        this.action_block.appendChild(this.feedback_container);
    }
}

// Ajax Dare Rating
var rateDare = Behavior.create({
    initialize: function() {
        this.popularity_container = $$('div#dare-rating p')[0];
        this.rate_container = $('dare-rating');
        if(this.rate_container.hasClassName('show-loading')) {
          this.rate_container.removeClassName('show-loading');
        };
    },
    onclick: function() {
        this.popularity_container.addClassName('show-loading');
        new Ajax.Request(this.element.href, {
            asynchronous:true,
            evalScripts:true,
            method:'put',
            parameters:'authenticity_token='+ AUTH_TOKEN
        });
        return false;
    }
});
Event.addBehavior({ 'a.vote' : rateDare });

// removed textToRemove from a comma-separated string, str
function removeFromCommaSeparatedString(str, textToRemove) {
    str = str.gsub(/.+?,\s?/i, 
        function(match) {
            //alert(match);
            var matchStr = String(match).replace(/,\s?/, '');
            //alert('Matching '+matchStr+' with '+textToRemove);
            if (matchStr == textToRemove) {
                return '';
            } else {
                return match;
            }
        }
    );
    return str;
}
function removeLastFromCommaSeparatedString(str) {
    return str.gsub(/((.*?,\s?)*)(.+?)$/i, 
        function(match) {
            return match[1];
        }
    );
}


/* User search auto-completer */
function userTextListUpdate (el) {
    if (el) {
        var nickname = el.down('span.nickname').innerHTML;
        var bodyId = $$('body')[0].id;
        
        if (bodyId == 'what_next') {
            var liId = 'user-choice-' + nickname;
            removeUserTextListChoice(liId); // remove 'old' to avoid duplicates
            $('user-text-list-input').insert({
                before: '<li class="user-chosen" id="' +
                    liId +
                    '"><a href="#" class="remove-user-choice" onclick="removeUserTextListChoice(\''+liId+'\')">' +
                    nickname +
                    ' x</a></li>'
            });
            var theInput = $('user-text-list-input').down('input');
            //alert(theInput.value);
            theInput.value = removeLastFromCommaSeparatedString(theInput.value);
            //alert(theInput.value);
            theInput.focus();
            
            // keep the 'real' field up to date
            var hidden_field = $('email_addresses');
            if (hidden_field.value == '') {
                hidden_field.value = nickname + ', ';
            } else {
                hidden_field.value = hidden_field.value + nickname + ', ';
            }
        } else if (bodyId == 'create-dare') {
            $('daree_nickname').value = nickname;
            new Effect.Highlight('daree_nickname');
            $('dare_title').focus();
            new Effect.Highlight('dare_title');
        } else if (bodyId == 'create-brag') {
            var liId = 'user-choice-' + nickname;
            $('user-text-list-input').insert({
                before: '<li class="user-chosen" id="' +
                    liId +
                    '"><a href="#" class="remove-user-choice" onclick="removeUserTextListChoice(\''+liId+'\')">' +
                    nickname +
                    ' x</a></li>'
            });
            var theInput = $('user-text-list-input').down('input');
            //alert(theInput.value);
            theInput.value = removeLastFromCommaSeparatedString(theInput.value);
            //alert(theInput.value);
            theInput.focus();
            
            // keep the 'real' field up to date
            var hidden_field = $('brag_participants');
            if (hidden_field.value == '') {
                hidden_field.value = nickname + ', ';
            } else {
                hidden_field.value = hidden_field.value + nickname + ', ';
            }
        }//end create-brag
    }
    
    return false;
}
function removeUserTextListChoice(id) {
    var bodyId = $$('body')[0].id;
    if (bodyId == 'what_next') {
        var hidden_field = $('email_addresses');
    } else if (bodyId == 'create-brag') {
        var hidden_field = $('brag_participants');
    }
    
    var toRemove = $(id);
    if (toRemove) {
        var nick = toRemove.down('a').innerHTML.replace(' x', '');
        //alert('Got '+nick);
        hidden_field.value = removeFromCommaSeparatedString(hidden_field.value, nick);
        //alert('New value: '+$('email_addresses').value);
        toRemove.remove();
        $('user-text-list-input').down('input').focus();
    }
}

var loadingAutoCompleteList = false;
var autoCompleteOptions = {
    minChars:3,
    callback: function(el,q){
        //alert(loadingAutoCompleteList);
        if (loadingAutoCompleteList) {
            return false;
        }
        else {
            loadingAutoCompleteList = true;
            return q;
        }
    },
    onLoading: function(){
        showLoading('loading');
    }, 
    onLoaded: function(){ 
        loadingAutoCompleteList = false;
        //alert(loadingAutoCompleteList);
        unShowLoading('loading');
    } 
}
// daree field
var observeUserTextList = Behavior.create({
    initialize: function() {
        var daree_nickname_auto_completer = new Ajax.Autocompleter('daree_nickname', 'daree_nickname_auto_complete', '/dares/auto_complete_for_daree_nickname', autoCompleteOptions)
    }
});
Event.addBehavior({ 'body#create-dare input#daree_nickname.has-friends' : observeUserTextList});

// message recipient field
var observeUserTextList = Behavior.create({
    initialize: function() {
        var utlOptions = autoCompleteOptions;
        /* Don't want this (allowing multiple recipients) yet
        utlOptions['updateElement'] = function(el){
            var nickname = el.innerHTML;
            theInput = $('recipient');
            theInput.value = removeLastFromCommaSeparatedString(theInput.value);
            theInput.value = theInput.value + nickname;
        };*/
        var daree_nickname_auto_completer = new Ajax.Autocompleter('recipient', 'recipient_auto_complete', '/messages/auto_complete_for_recipient', utlOptions)
    }
});
Event.addBehavior({ 'body#inbox input#recipient.has-friends' : observeUserTextList});

// what next/TaF
var observeUserTextList = Behavior.create({
    initialize: function() {
        var utlOptions = autoCompleteOptions;
        utlOptions['updateElement'] = userTextListUpdate;
        var email_addresses_visible_auto_completer = new Ajax.Autocompleter('email_addresses_visible', 'email_addresses_visible_auto_complete', '/what_next/auto_complete_for_email_addresses_visible', utlOptions)
    }
});
Event.addBehavior({ 'body#what_next ul#user-text-list input' : observeUserTextList});


var tellFriends = Behavior.create({
    onsubmit: function() {
        // add the contents of the user-visible text field to the 'real' hidden one
        var hidden_field = $('email_addresses');
        var visible_field = $('email_addresses_visible');
        if (visible_field.value != '') {
            if (hidden_field.value == '') {
                hidden_field.value = visible_field.value;
            } else {
                hidden_field.value = hidden_field.value + ', ' + visible_field.value;
            }
        }
    }
});
Event.addBehavior({ 'form#tell-friends' : tellFriends});

var findFriendsToTell = Behavior.create({
    onclick: function() {
        new Ajax.Request(this.element.href, {method:'get'});
        return false;
    }
});
Event.addBehavior({ 'body#what_next li#my-friends a' : findFriendsToTell});
var chooseFriendToTell = Behavior.create({
    onclick: function() {
        userTextListUpdate(this.element);
        return false;
    },
    onmouseover: function() {
        this.element.addClassName('hover');
    },
    onmouseout: function() {
        this.element.removeClassName('hover');
    }
});
Event.addBehavior({ 'body#what_next ul#friends-list li' : chooseFriendToTell});

var selectContacts = Behavior.create({
     initialize: function() {
       this.defaultText = $('email_addresses_visible').value;
     },
     onclick: function() {
        var visible_input = $('email_addresses_visible');
        visible_input.value = visible_input.value.replace(this.defaultText, "");
        if (!visible_input.value.match(/,\s*$/) && visible_input.value != '') {
            visible_input.value = visible_input.value + ', ';
        }
        visible_input.value = visible_input.value + this.element.innerHTML + ', ';
        new Effect.Fade(this.element.up('li'), { duration: 0.5 });
        visible_input.focus();
        new Effect.Highlight(visible_input);
        
        return false;
    }
});
Event.addBehavior({ 'body#what_next ul#retrieved-emails li a' : selectContacts});
/* End user search auto-completer */

/* Brag->Group Recommendation Form */
var addToGroup = Behavior.create({
    onclick: function() {
        switch(this.element.id) {
            case 'add-to-group':
                this.element.addClassName('hide');
                $('group-selection').addClassName('show');
            break;
            case 'cancel-add-to-group':
                $('add-to-group').removeClassName('hide');
                $('group-selection').removeClassName('show');
            break;
        }
        return false;
    }
});
Event.addBehavior({ 'a#add-to-group' : addToGroup });
Event.addBehavior({ 'a#cancel-add-to-group' : addToGroup });

/* Dare Creation Page */
var chooseDareType = Behavior.create({
    onclick: function() {
        var parentList = $('dare-types');
        var listItems = parentList.childElements();
        var thisChoiceId = this.element.down('input').id;
        
        for (x = 1; x < listItems.length; x++) {
            if (listItems[x].id+'_true' == thisChoiceId) {
                listItems[x].addClassName('active');
                listItems[x].down('input').checked = true;
                $(listItems[x].id+'_form').addClassName('active');
            } else {
                listItems[x].removeClassName('active');
                listItems[x].down('input').checked = false;
                $(listItems[x].id+'_form').removeClassName('active');
            }
        }
    }
});
Event.addBehavior({ 'body#create-dare ul#dare-types label' : chooseDareType });

var chooseDareMediaType = Behavior.create({
    onmouseup: function() {
        media_option_fields = $('media_choice_'+this.element.rel);
        media_option_fields.value = this.element.id.replace(/dare-media-/, '');
        return;
    }
});
Event.addBehavior({ 'body#create-dare ul.dare-media-options a' : chooseDareMediaType });

// unobtrusive method = post for anchor tags
// use className method-post
var anchorTagPostMethod = Behavior.create({
    onclick: function() {
        var f = document.createElement('form');
        f.style.display = 'none';
        this.element.parentNode.appendChild(f);
        f.method = 'POST';
        f.action = this.element.href;
        if(AUTH_TOKEN) {
            var s = document.createElement('input'); 
            s.setAttribute('type', 'hidden'); 
            s.setAttribute('name', 'authenticity_token'); 
            s.setAttribute('value', AUTH_TOKEN); 
            f.appendChild(s);
        }
        f.submit();
        return false;
    }
});
Event.addBehavior({ 'a.method-post' : anchorTagPostMethod });

// make a lightwindow
function LightWindow() {
    this.options = arguments[0] || { content_type: "preloaded", content_id: null, close_button: true, lose_focus: true }
    this.name = name;
    this.lw_background = document.createElement('div');
    this.lw_background.className = "lightwindow-background";
    this.lw_container = document.createElement('div');
    this.lw_container.className = "lightwindow-container";
    this.lw_container.id = "lightwindow-container";
    this.preloaded_element;
    temp=navigator.appVersion.split('MSIE');
    ieVer=parseInt(temp[1]);
    var isIEup=(ieVer <= 6)?1:0;
    if(isIEup) {
        this.lw_background.style.height = document.body.clientHeight + "px";
    }
    document.body.appendChild(this.lw_container);
    document.body.appendChild(this.lw_background);
    if(this.options.lose_focus == true) {
        obj = this;
        this.lw_background.onclick = function() { obj.close(); }
    }
    if(this.options.close_button == true) {
        this.createCloseButton();
    }
    if(this.options.content_type == "preloaded") {
        this.insertPreloadedContent();
    } else if(this.options.content_type == "remote") {
        this.insertRemoteContent();
    }
}
LightWindow.prototype.insertPreloadedContent = function() {
    this.preloaded_content = $(this.options.content_id);
    this.preloaded_content.style.display = "block";
    this.lw_container.appendChild(this.preloaded_content);
    this.positionContent();
}
LightWindow.prototype.insertRemoteContent = function() {
    var content_url = this.options.content_url;
    var obj = this;
    new Ajax.Updater('lightwindow-container', content_url, {
                        method: 'get',
                        onComplete: function() {
                            obj.positionContent();
                        }
                     });
}
LightWindow.prototype.positionContent = function() {
    var ScrollTop = document.body.scrollTop;
    if(ScrollTop == 0) {
        if(window.pageYOffset) {
            ScrollTop = window.pageYOffset;
        } else {
            ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
        }
    }
    this.lw_container.style.left = Math.floor((document.body.clientWidth / 2) -  ($$('.lightwindow-container')[0].childElements()[0].offsetWidth / 2)) + "px";
    this.lw_container.style.top = Math.floor((document.documentElement.clientHeight / 2) - ($$('.lightwindow-container')[0].childElements()[0].offsetHeight / 2)) - 40 + ScrollTop + "px";
    if(this.options.close_button == true) {
        this.lw_container.appendChild(this.close_button);
    }
}
LightWindow.prototype.createCloseButton = function() {
    this.close_button = document.createElement('div');
    this.close_button.className = "lightwindow-close-button";
    this.close_button.innerHTML = "<a href='#' id='close-lightwindow' class='icon icon-close'>close</a>";
    obj = this;
    this.close_button.onclick = function () { obj.close(); return false; }
}
LightWindow.prototype.close = function() {
    this.lw_container.remove();
    $$('.lightwindow-background')[0].remove();
}

/* Inbox functions */
var viewConversation = Behavior.create({
    onclick: function() {
        if (!this.element.hasClassName('action')) {
            if (this.element.hasClassName('subject')) {
                window.location = this.element.down('a.conversation-link').href;
            } else {
                window.location = this.element.up('tr').down('a.conversation-link').href;
            }
        }
    }
});
Event.addBehavior({ 'body#inbox table#inbox-table tr td' : viewConversation });

var markAsReadUnread = Behavior.create({
    onchange: function() {
        if (this.element.value == 'mark_read') {
            theForm = $('inbox-mark-form');
            theForm.action = theForm.action + '/mark_all_as_read';
            theForm.submit();
        }
        if (this.element.value == 'mark_unread') {
            theForm = $('inbox-mark-form');
            theForm.action = theForm.action + '/mark_all_as_unread';
            theForm.submit();
        }
    }
});
Event.addBehavior({ 'body#inbox select#mark_as' : markAsReadUnread });

var markAsCancelled = Behavior.create({
    onclick: function() {
        theForm = $('inbox-mark-form') || $('outbox-mark-form');
        theForm.action = theForm.action + '/mark_all_as_cancelled';
        theForm.submit();
        return false;
    }
});
Event.addBehavior({ 'body#inbox a.delete-selected' : markAsCancelled });

var selectAllCheckboxes = Behavior.create({
    onclick: function() {
        checkboxes = $$('input.checkbox.toggle');
        for (var x = 0; x < checkboxes.length; x++) {
            checkboxes[x].checked = true;
        }
        return false;
    }
});
Event.addBehavior({ 'a.select-all-checkboxes' : selectAllCheckboxes });
var unselectAllCheckboxes = Behavior.create({
    onclick: function() {
        checkboxes = $$('input.checkbox.toggle');
        for (var x = 0; x < checkboxes.length; x++) {
            checkboxes[x].checked = false;
        }
        return false;
    }
});
Event.addBehavior({ 'a.unselect-all-checkboxes' : unselectAllCheckboxes });
var toggleAllCheckboxes = Behavior.create({
  onchange: function() {
    checkboxes = $$('input.checkbox.toggle');
    for(var i = 0; i < checkboxes.length; i++) {
      checkboxes[i].checked = this.element.checked;
    };
    return false;
  }
});
Event.addBehavior({ '.toggle-checkboxes' : toggleAllCheckboxes });

var selectInverseCheckboxes = Behavior.create({
    onclick: function() {
        checkboxes = $$('input.checkbox.toggle');
        for (var x = 0; x < checkboxes.length; x++) {
            checkboxes[x].checked = !checkboxes[x].checked;
        }
        return false;
    }
});
Event.addBehavior({ 'a.select-inverse-checkboxes' : selectInverseCheckboxes });
/* End Inbox functions */

/* Cancel Feed Notification */
var cancelFeedNotification = Behavior.create({
    onclick: function() {
        tr = $('notification-'+this.element.id);
        new Effect.Fade(tr.id, {queue: 'end', duration: 0.4});
        new Ajax.Request(this.element.href, {  
            method: "delete",
            parameters:'authenticity_token='+ AUTH_TOKEN
        });
        return false;
    }
});
Event.addBehavior({ 'a.remove-notification' : cancelFeedNotification });


/* Create brag extra options switcher */
var switchBragOptionDisplay = Behavior.create({
    onclick: function() {
        var targetId = this.element.href.gsub(/.*?#([a-z-]+)/, '#{1}');
        var part = $('brag-participants');
        var opt = $('brag-options');
        
        if (targetId == 'brag-participants') {
            if (part.style.display != 'none') { // already open, so close
                //alert('close it');
                new Effect.BlindUp('brag-participants', {duration: 0.3});
                $('extra-options').removeClassName('open');
                this.element.removeClassName('open');
            } else { // closed, so open
                //alert('open');
                $('extra-options').addClassName('open');
                this.element.addClassName('open');
                new Effect.BlindDown('brag-participants', {duration: 0.3, queue: 'end'});
                if (opt && opt.style.display != 'none') { // close options if already open first
                    new Effect.BlindUp('brag-options', {duration: 0.3, queue: 'front'});
                    $('options-link').down('a').removeClassName('open');
                }
            }
        } else if (targetId == 'brag-options') {
            if (opt.style.display != 'none') { // already open, so close
                //alert('close it');
                new Effect.BlindUp('brag-options', {duration: 0.3});
                $('extra-options').removeClassName('open');
                this.element.removeClassName('open');
            } else { // closed, so open
                //alert('open');
                $('extra-options').addClassName('open');
                this.element.addClassName('open');
                new Effect.BlindDown('brag-options', {duration: 0.3, queue: 'end'});
                if (part.style.display != 'none') { // close options if already open first
                    new Effect.BlindUp('brag-participants', {duration: 0.3, queue: 'front'});
                    $('participants-link').down('a').removeClassName('open');
                }
            }
        }
        
        return false;
    }
});
Event.addBehavior({ 'body#create-brag li#extra-options a' : switchBragOptionDisplay });

var hideTooltip = Behavior.create({
    onclick: function() {
        $$('div.'+this.element.id)[0].fade();
        if(this.element.href.match(/users/)) {
          this.method = 'put';
        } else {
          this.method = 'post';
        }
        new Ajax.Request(this.element.href, {
            method: this.method,
            parameters: 'hide_'+this.element.id+'_tooltip=true&authenticity_token='+AUTH_TOKEN
        });
        return false;
    }
})
Event.addBehavior({ 'a.close-tooltip' : hideTooltip });

var shareSubMenus;
var sharingToggle = Behavior.create({
    initialize: function() {
        shareSubMenus = $$('div.sub-sharing');
        for(var i = 0; i < shareSubMenus.length; i++) {
            shareSubMenus[i].style.display = "none";
        }
    },
    onclick: function() {
        this.toggled = this.element.id.split('share-')[1];
        subMenu = $(this.toggled);
        subMenu.style.display = (subMenu.style.display == "none" ? "block" : "none");
        for(var i = 0; i < shareSubMenus.length; i++) {
            if(shareSubMenus[i] != subMenu) {
                shareSubMenus[i].style.display = "none";
            }
        }
        return false;
    }
})
Event.addBehavior({ 'a.share-toggle' : sharingToggle });


/* Share a dare or brag on facebook */
var facebookShare = Behavior.create({
    onclick: function() {
        u=location.href;
        t=document.title;
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
        return false;
    }
})
Event.addBehavior({ 'a.facebook-share' : facebookShare });

/* Add new dare media from the DDP */
var newDareMedia = Behavior.create({
    onclick: function() {
        var new_media_lightwindow = new LightWindow({ content_type: "remote", 
                                                  content_url: this.element.href, 
                                                  lose_focus: true, 
                                                  close_button: true });
        return false;
    }
})
Event.addBehavior({ 'a.new-dare-media' : newDareMedia });

var checkDareMediaRadioInput = Behavior.create({
    onclick: function() {
        this.checkRadio();
    },
    onchange: function() {
        this.checkRadio();
    },
    onfocus: function() {
        this.checkRadio();
    },
    checkRadio: function() {
        if(radio_button = $('radio-'+this.element.id)) {
            radio_button.checked = true;
        }
    }
})
Event.addBehavior({ 'input.dare-media-field' : checkDareMediaRadioInput});

/* Picture gallery lightwindow */
var pictGallery = Behavior.create({
    onclick: function() {
        var new_media_lightwindow = new LightWindow({ content_type: "remote", 
                                                  content_url: this.element.href, 
                                                  lose_focus: true, 
                                                  close_button: true });
        return false;
    }
})
Event.addBehavior({ 'body#profile_pictures ul#user-profile-pictures li a.pic-link' : pictGallery });

/* Previewing & Enlarging Dare/Comment media */
var preview = null;
var displayMediaPreview = Behavior.create({
    initialize: function() {
        element = this.element.hasClassName('dare-media-thumb') ? 'div' : 'a';
    },
    onmouseover: function() {
        if(preview != null) {
            preview.style.display = "none";
        }
        if($$(element+'#'+this.element.id+'-preview').length == 0) {
            preview_thumb = this.element.next();
            preview_thumb_absolute = preview_thumb.cloneNode(true);
            preview_thumb_absolute.id = this.element.id + "-preview";
            document.body.appendChild(preview_thumb_absolute);
            Event.addBehavior({ 'a.enlargeable-media' : enlargeMedia });
        }
        preview = $(this.element.id + "-preview");
        thumb_coords = findPos(this.element);
        temp=navigator.appVersion.split('MSIE');
        ieVer=parseInt(temp[1]);
        var isIEup=(ieVer <= 7)?1:0;
            preview.style.left = thumb_coords[0] - 48 + "px";
        if(isIEup) {
            preview.style.top = thumb_coords[1] - 31 + "px";
        } else {
            preview.style.top = thumb_coords[1] - 75 + "px";
        }

        preview.style.display = "block";
        Element.extend(preview);
        preview.onmouseout = function(e) {
            if(!e) e = window.event;
            if (isMouseLeaveOrEnter(e, preview)) {
               preview.style.display = "none";
            }
        }
        if(this.element.next().next()) {
            preview.delete_media = this.element.next().next();
            preview.delete_media.style.display = "block";
        }
    }
})
Event.addBehavior({ 'body#dare-show a.dare-media-thumb' : displayMediaPreview });
Event.addBehavior({ 'div#comments-box a.comment-media-thumb' : displayMediaPreview });

var enlargeMedia = Behavior.create({
    onclick: function() {
        var enlarge_media_lightwindow = new LightWindow({ content_type: "remote", 
                                                  content_url: this.element.href, 
                                                  lose_focus: true, 
                                                  close_button: true });
        return false;
    }
})
Event.addBehavior({ 'a.enlargeable-media' : enlargeMedia });


/* Show dare details for new daree */
var revealDareDetails = Behavior.create({
    onclick: function() {
        this.element.hide();
        new Effect.BlindDown('dare-more-details', {duration: 0.3});
        new Effect.BlindDown('dare-more-extras', {duration: 0.3});
        return false;
    }
})
Event.addBehavior({ 'a#dare-show-full-page-link' : revealDareDetails });

var ie6hover = Behavior.create({
    onmouseover: function() {
        if(Prototype.Browser.IE6) this.element.addClassName('hover');
    },
    onmouseout: function() {
        if(Prototype.Browser.IE6) this.element.removeClassName('hover');
    }
})
Event.addBehavior({ 'li#user-dropdown' : ie6hover });


/* Generic Expand/Retract Description */
var expandRetractDescription = Behavior.create({
    initialize: function() { /* fofr IE */
        Element.extend(this.element.parentNode);
    },
    onclick: function() {
      toggleDisplay(this.element.parentNode, (this.element.parentNode.next() || this.element.parentNode.previous()));
      return false;
    }
})
Event.addBehavior({ 'a.description-control' : expandRetractDescription });

var profilePicForm = Behavior.create({
    onclick: function() {
        var theBlock = $('upload-picture');
        if (theBlock.style.display == 'none') {
            new Effect.BlindDown(theBlock, {duration:0.3});
        }
        else {
            new Effect.BlindUp(theBlock, {duration:0.3});
        }
    }
})
Event.addBehavior({ 'body#profile_pictures a#upload-picture-link' : profilePicForm });

/* Accept/Reject Friendship/Team invite */
var actionInvitation = Behavior.create({
    onclick: function() {
        if(this.element.disabled != true) {
            obj = this;
            new Ajax.Request(this.element.href, {
              method: 'post',
              parameters: 'authenticity_token='+AUTH_TOKEN,
              onLoading: obj.loading()
            });
        }
        return false;
    },
    loading: function() {
        this.sibling = (this.element.hasClassName('accept') ? this.element.next() : this.element.previous());
        this.sibling.style.backgroundImage = "url('/images/buttons.gif')";
        this.sibling.style.backgroundPosition = "-104px -112px";
        this.sibling.disabled = true;
        this.disabled = true;
        this.selected_background_colour = (this.element.hasClassName('accept') ? "green" : "red");
        this.element.style.backgroundImage = "url('/images/buttons.gif')";
        var backgroundPosition = (this.selected_background_colour == "green" ? "-104px -56px" : " -104px -84px" );
        this.element.style.backgroundPosition = backgroundPosition;
    }
})
Event.addBehavior({ 'div.invitation-information a.ajax-invite' : actionInvitation });

function hideInvitation(id, selected_button) {
    invitation = $('invitation-'+id);
    this.button = $$('div#invitation-'+id+' a.'+selected_button)[0];
    this.button.pulsate({ pulses: 3, duration: 1.6, afterFinish: function() { invitation.fade({duration: 0.4, afterFinish: function() { invitation.remove();checkInvitations(); } }) }});
}

function checkInvitations() {
    invitations = $$('div.single-invitation');
    if(invitations.length < 1) {
        $('no-invitations').className = "";
    }
}


var flashMessage = Behavior.create({
    initialize: function() {
        var el = this.element;
        window.setTimeout(function() {
            new Effect.Fade(el); }, 2000
        );
    }
});
Event.addBehavior({ 'div.error-flash' : flashMessage });
Event.addBehavior({ 'div.notice-flash' : flashMessage });

/* Toggle between embed / link_to brag */
var embedToggle = Behavior.create({
    initialize: function() {
        text_field = $('brag-sharing-codes');
        initial_value = text_field.value;
    },
    onclick: function() {
        if(this.element.id == 'toggle-link' ) {
            this.element.style.display = "none";
            this.element.next().style.display = "inline";
            text_field.value = this.element.href;
            $('toggle-embed').style.display = "inline";
            $('toggle-embed').next().style.display = "none";
        } else {
            this.element.style.display = "none";
            this.element.next().style.display = "inline";
            text_field.value = initial_value;
            $('toggle-link').style.display = "inline";
            $('toggle-link').next().style.display = "none";
        }
        return false;
    }
});
Event.addBehavior({ 'div#embed-brag a' : embedToggle });

var dareSettlementInfo = Behavior.create({
    initialize: function() {
        $('settlement-info').style.display = "none";
    },
    onclick: function() {
        var theBlock = $('settlement-info');
        if (theBlock.style.display == 'none') {
            new Effect.BlindDown(theBlock, {duration:0.3, queue: 'end' });
        }
        else {
            new Effect.BlindUp(theBlock, {duration:0.3, queue: 'end' });
        }
    }
})
Event.addBehavior({ 'a#settlement-info-slide' : dareSettlementInfo });

var remoteForumPostCreate = Behavior.create({
    onsubmit: function() {
        // if uploading a file, send a normal request: can't upload via Ajax
        if (($('uploaded_data') && $('uploaded_data').getValue() != "") || !this.element.hasClassName('sender-user')) {
            return true;
        } else {
            new Ajax.Request('/forum_posts', 
                {
                    asynchronous:true, 
                    evalScripts:true, 
                    parameters:Form.serialize(this.element)
                }
            );
            errors_present = $$('div#comments-box div.errors');
            if(errors_present.length > 0){ errors_present[0].hide() };
            $('new-forum-post').hide();
            $('attach-media').hide();
            $('attach-media').insert({after:'<div id="comment-loading"></div>'});
            showLoading('comment-loading');
            return false;
        }
    }
});
Event.addBehavior({ '#new-comment form' : remoteForumPostCreate });
Event.addBehavior({ '#new-forum-post form' : remoteForumPostCreate });

/* ComboBox */
function DropDown() {
  Element.extend(this); 
  var doRemote = this.hasClassName("remote-links");
  var options = this.down('ul');
  var loader = this.up().next("li.filter-loading");
  var toggleButton = this.immediateDescendants().last();
  options.toggled = false;

  function closeDropDown() {
    options.removeClassName('opened');
    options.toggled = false;
    document.body.onmousedown = null;
  }

  options.onmousedown = toggleButton.onmousedown = openDropDown;

  function openDropDown() {
    if(options.toggled === false) {
      options.addClassName('opened');
      options.toggled = true;
      setTimeout(function() {
        document.body.onmousedown = function() {
          closeDropDown();
        }
      }, 10);
    }
    return false;
  }
  
  var optionLinks = options.getElementsByTagName('a');
  for(var i = 0; i < optionLinks.length;i++) {
    var currentLink = optionLinks[i];
    (function() {
      currentLink.onmousedown =  function(e) {
          e = e || window.event;
          if(e && e.stopPropagation) {
            e.stopPropagation();         
          } else {
            e.cancelBubble = true;
          }
        }
      currentLink.onclick = function(event) {
        var e = event || window.event;
        var el = Element.extend(e.target || e.srcElement);
        if(options.toggled == false) {
          openDropDown();
          return false;
        } else if(doRemote) {
          new Ajax.Request(el.href, { method: "get", asynchronous:true, evalScripts:true });
          if(loader) loader.style.display = "block";
          return false;
        };
      }
    })();
  }
}
var doComboBox = Behavior.create({
  initialize: function() {
    DropDown.apply(this.element);
  }
});
Event.addBehavior({ 'body#brag-browse div.drop-down' : doComboBox });
Event.addBehavior({ 'body#dare-browse div.drop-down' : doComboBox });
Event.addBehavior({ 'body#group-browse div.drop-down': doComboBox });

function ExpandableList(ElementId, expandableTag) {
  var containerElement = document.getElementById(ElementId);
  if(typeof containerElement == "object") {
    var allDefinitionTitles = containerElement.getElementsByTagName(expandableTag);
    function getHashParam() {
      return window.location.href.gsub(/.*?#/, ''); 
    }
    var openedByDefault = getHashParam();
    for(var i = 0;i < allDefinitionTitles.length;i++) {
      var currentTitle = allDefinitionTitles[i];
      Element.extend(currentTitle);
      var titleAnchor = currentTitle.down();
      Element.extend(currentTitle);
      (function() {
        // hide all definitions, unless any have been set to remain open 
        var content = currentTitle.next();
        if(!content.hasClassName('opened') && titleAnchor.name != openedByDefault) {
          content.addClassName('closed');
          currentTitle.addClassName('closed');
        }
        // create the event handler for clicking these titles
        currentTitle.onclick = function() {
            if(content.hasClassName('closed')) {
              content.removeClassName('closed');
              content.previous().removeClassName('closed');
            } else {
              content.addClassName('closed');
              content.previous().addClassName('closed');
            }
        }
      })();
    }
  } else {
    throw "Element could not be found for the ID: " + ElementId;
  }
}

window.onload = function() {
  if(document.body.id == "faq") {
    new ExpandableList('faq-definitions', 'dt');
  } else if (document.body.id == "group-admin") {
    new ExpandableList('edit', 'h3');
  }
}

// modal windows
var Modal = function(id) {
    var modalId = id;
    this.element = null;
    this.shadow = null;

    if(window.modal) window.modal.close();

    function createModal() {
      var container = document.createElement('div');
      container = $(container);
      container.className = "modal";
      
      // IE stuff
      // TODO CSS3 feature detection
      if("\v" == "v") {
        container.addClassName("modal-alt");
        container.addClassName(modalId + "-alt");
      };
      
      container.id = modalId;
      container.innerHTML = "<p class=\"preloading\">Loading content...</p>";
      return container;
    }

    function insertModal() {
      var documentTopOffset = document.body.scrollTop;

      if(documentTopOffset === 0) {
        if(window.pageYOffset) {
          documentTopOffset = window.pageYOffset;
        } else {
          documentTopOffset = document.body.parentElement ? document.body.parentElement.scrollTop : 0;
        }
      }

      this.style.left =  Math.floor(document.body.clientWidth / 2) - 170 + "px";
      this.style.top  =  Math.floor((document.documentElement.clientHeight / 2) - (document.documentElement.clientHeight / 100) * 20) + documentTopOffset + "px";

      return document.body.appendChild(this);
    }

    // execute
    this.element = createModal();
    this.element = insertModal.call(this.element);
    window.modal = this;

  };

  Modal.prototype.retrieveContent = function(url, method) {
    var contentUrl = url;
    var httpMethod = method;
    var params = "";
    if(AUTH_TOKEN) params = 'authenticity_token=' + AUTH_TOKEN;

    // prototype.js class
    return new Ajax.Request(contentUrl, { method: (httpMethod || "get"),
                                          asynchronous:true,
                                          evalScripts:true,
                                          parameters:params
                                         });
    

  };

  Modal.prototype.close = function() {
    document.body.removeChild(this.element);
    window.modal = null;
  };

  Modal.prototype.setLoadStatus = function(bool) {
    Element.extend(this.element);      // prototype.js method
    var content = this.element.down(); // prototype.js method
    if(content) {
      var loadingMessage = content.next(); //prototype.js method
      if(loadingMessage) {
        if(bool === true) {
          content.style.display = "none";
          loadingMessage.style.display  = "block";
        } else {
          content.style.display = "block";
          loadingMessage.style.display  = "none";
        }
      }
    }

};
// end modal windows

/* Blocked user alerts */
var userBlockedAlert = Behavior.create({
  onclick: function() {
    this.ui = new Modal('blocked-alert');
    this.ui.retrieveContent('/main/blocked', 'get');
    return false;
  }
});
Event.addBehavior({ '.blocked' : userBlockedAlert });

var addthis_pub="bragster";
/* Load AddThis widget */
var addThisWidget = Behavior.create({
  initialize: function() {
    var e = document.createElement("script");
    e.src = "http://s7.addthis.com/js/200/addthis_widget.js";
    e.type="text/javascript";
    document.getElementsByTagName("head")[0].appendChild(e); 
    var anchor = document.getElementById('add-this-widget');
    anchor.innerHTML = '<img src="http://s7.addthis.com/static/btn/lg-addthis-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/>';
  }
});
Event.addBehavior({ 'body#brag' : addThisWidget });
Event.addBehavior({ 'body#dare-show' : addThisWidget });
Event.addBehavior({ 'body#campaign-show' : addThisWidget });

/* Confirm open-dare winner */
var confirmWinner = Behavior.create({
  onclick: function() {
    this.ui = new Modal('confirm-winner');    
    this.ui.retrieveContent(this.element.href, 'get');
    return false;
  }
});
Event.addBehavior({ '#settle-open-dare' : confirmWinner });

var triggerFacebookEmailApproval = Behavior.create({
  onclick: function() {
    if(this.element.checked) {
      this.element.next().down().onclick();
    };
    return false;
  }
});
Event.addBehavior({ 'input#use-fb-email' : triggerFacebookEmailApproval });

function fbEmailApproved() {
  $('use-fb-email').checked = true;
};

/** get window location for flash **/
function getLocation() {
  return window.location.href;
};
/** end get window location for flash **/
