//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// POSTEROUS GLOBAL JS FOR SITES
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
var Posterous = Class.create({
  _posterousDefaultAnimationDurationLong:  0.5,
  _posterousDefaultAnimationDurationShort: 0.2,
  
  modalWindow:  null,
  posts:        {},
  postIds:      [],
  
  // Initialize a Posterous site. This includes loading content via Ajax, and looking for 
  // elements that require dynamic stuff (like show_on_click).
  initialize: function() {
    this.registerProtomenus();
    if (!$$('meta[name="generator"]').first()) {
      return;
    }
    // Initialize any OJS that has been defined on the page
    try {
      this.registerShowOnClickActions();
      this.registerShowOnHoverActions();
      this.registerSearchBoxes();
      this.registerComment();
      this.registerRetweetButtons();
      this.parseCodeBlocks();
      this.initializeEditBoxes();
      this.fillAllTimeAgoFields();
    } catch(err) { }
    var deferredContentUrl = null;
    if (deferredContentUrl = $$('[data-posterous-deferred-content="true"]').first()) {
      // Do Ajax request for deferred content
      this.requestDeferredContent(deferredContentUrl.readAttribute('data-posterous-deferred-content-url'), [
        this.setAuthenticityToken.bind(this),
        this.registerPosterousBar.bind(this), 
        this.registerSubscribeLinks.bind(this), 
        this.createFavorite.bind(this),
        this.replaceViewCounts.bind(this),
        this.createNewCommentForm.bind(this),
        this.initializeCommentForm.bind(this),
        this.insertAdminBox.bind(this),
        this.removeUnauthorizedEditBoxes.bind(this),
        this.fixDeleteLinks.bind(this),
        this.registerProtomenus.bind(this)
      ]);
    }
  },
  
  //=============================
  // Deferred content
  //=============================
  
  requestDeferredContent: function(url, callbacks) {
    var postData = $$('[data-post-data-container="true"]').first();
    this.postParams = postData ? Object.toJSON(unescape(postData.readAttribute('data-post-data').gsub('+', ' ')).evalJSON()) : null;
    
    var postsData = $$('[data-posterous-post-list="true"]').first();
    this.posts = postsData ? Object.toJSON(unescape(postsData.readAttribute('data-post-data').gsub('+', ' ')).evalJSON()) : null;

    new Ajax.Request(url, {
      parameters: {
        authenticity_token: window._token,
        referrer: window.location.href,
        post: this.postParams,
        posts: this.posts
      },
      onSuccess: function(request) {
        callbacks.each(function(c) {
          c(request.responseJSON);
        }, this);
      }.bind(this)
    });
  },
  
  //=============================
  // Posterous Bar initialization
  //=============================
  
  // Register the "My Posterous" menu
  registerProtomenus: function() {
    if (!Prototype.Browser.IE) {
      $$('[data-posterous-protomenu="true"]').each(function(e) {
        e.href = '#';
        e.down('img').show();
        items = $(e.readAttribute('data-posterous-items-list-id')).select('li a').map(function(m) {
          return {
            'href': m.href,
            'name': m.innerHTML,
            'icon': m.readAttribute('data-icon')
          };
        });
        new Proto.Menu({
          selector:   '#' + e.id,
          position:   'relative',
          location:   e,
          click:      'left',
          width:      200,
          className:  'menu desktop',
          menuItems:  items
        });
      });
    }
  },
  
  
  //=============================
  // Theme-related initialization
  //=============================
  
  // Uses data- attributes to OJS-ify our {block:ShowOnClick}
  registerShowOnClickActions: function() {
    $$('[data-posterous-show-on-click="true"]').each(function(e) {
      var elementToHideOnClick = $(e.readAttribute('data-posterous-hide-on-click-id'));
      var actionTriggerElement = $(e.readAttribute('data-posterous-action-trigger-id'));
      var elementToShowOnClick = $(e.readAttribute('data-posterous-id-to-show-on-click'));
      
      if (actionTriggerElement && elementToShowOnClick) {
        actionTriggerElement.observe('click', function(event) {
          event.stop();
          if (elementToHideOnClick) {
            elementToHideOnClick.hide();
          }
          Effect.toggle(elementToShowOnClick, 'slide', { duration: this._posterousDefaultAnimationDurationLong });
        }.bindAsEventListener(this)); 
      }
    }, this);
  },
  
  // OJS version of {block:ShowOnHover}
  registerShowOnHoverActions: function() {
    $$('[data-posterous-show-on-hover="true"]').each(function(e) {
      var actionTriggerElement = $(e.readAttribute('data-posterous-action-trigger-id'));
      var elementToShowOnHover = $(e.readAttribute('data-posterous-id-to-show-on-hover'));
      if (actionTriggerElement && elementToShowOnHover) {
        actionTriggerElement.observe('mouseover', function() {elementToShowOnHover.show();});
        actionTriggerElement.observe('mouseout', function() {elementToShowOnHover.hide();});
      }
    });
  },
  
  // OJS version of {block:SubscriptionSubscribed} and {block:SubscriptionUnsubscribed}
  registerSubscribeLinks: function(deferredContent) {
    $$('[data-posterous-subscribe-link="true"]').each(function(e) {
      var actionTriggerElement  = $(e.readAttribute('data-posterous-action-trigger-id'));
      var elementToBeReplaced   = $(e.readAttribute('data-posterous-id-to-be-replaced'));
      var loadingElement        = $(e.readAttribute('data-posterous-loading-element'));
      var actionToTake          = e.readAttribute('data-posterous-subscription-action').strip() == 'addsub' ? 'addsub' : 'removesub';
      var siteId                = e.readAttribute('data-posterous-site-id');
      
      if (actionToTake == 'addsub') {
        deferredContent.subscribed_to_this_site == true ? e.hide() : e.show();
      } else {
        deferredContent.subscribed_to_this_site == true ? e.show() : e.hide();
      }
      
      actionTriggerElement.observe('click', function(event) {
        event.stop();
        new Ajax.Updater(
          elementToBeReplaced,
          '/posts/' + actionToTake + '?authenticity_token=' + window._token,
          {
            evalScripts: true,
            parameters: {
              site: siteId,
              authenticity_token: window._token
            },
            onLoading: function() {
              loadingElement.show();
              actionTriggerElement.hide();
              elementToBeReplaced.update();
            },
            onComplete: function() {
              loadingElement.hide();
            }
          }
        );
      });
    });
  },
  
  registerSearchBoxes: function() {
    $$('[data-posterous-search-box="true"]').each(function(e) {
      var searchButton = $(e.readAttribute('data-posterous-search-button-id'));
      var searchBox = $(e.readAttribute('data-posterous-search-box-id'));
      var currentlyHoveringOverButton = false;
      
      searchButton.observe('mouseover', function() { currentlyHoveringOverButton = true; });
      searchButton.observe('mouseout', function() { currentlyHoveringOverButton = false; });
      searchBox.observe('focus', function() { searchButton.show(); });
      searchBox.observe('blur', function() { if (!currentlyHoveringOverButton) { searchButton.hide(); }});
    });
  },
  
  registerPosterousBar: function(deferredContent) {
    $$('[data-posterous-bar="true"]').each(function(e) {
      $(e.readAttribute('data-posterous-action-id') || e.id).insert({bottom: deferredContent.posterous_bar});
      new PosterousHeader($(e.readAttribute('data-posterous-action-id') || e.id), { direction: e.readAttribute('data-posterous-direction') || 'left', clearDefault: e.readAttribute('data-posterous-translucent') || 'false'});
    });
    
    $$('[data-posterous-bar-legacy="true"]').each(function(e) {
      e.update(deferredContent.posterous_bar_legacy).show();
    }, this);
  },

  createFavorite: function(deferredContent) {
    if (deferredContent.logged_in == false) {
      return;
    }
    var postFavorited = null;
    $$('[data-posterous-favorite="true"]').each(function(e) {
      postFavorited = deferredContent.post_favorited[parseInt(e.readAttribute('data-posterous-identifier'), 10)];
      new PFavorite(e.readAttribute('data-posterous-hover'), e.readAttribute('data-posterous-position'), e.readAttribute('data-posterous-identifier'), postFavorited == true);
    });
  },
  
  registerComment: function() {
    $$('[data-posterous-comment="true"]').each(function(e) {
      if ($(e.readAttribute('data-posterous-comment-link'))) {
        window[e.readAttribute('data-posterous-comment-var')] = new PComment($(e.readAttribute('data-posterous-comment-link')), e.readAttribute('data-posterous-post-identifier'), $(e.readAttribute('data-posterous-post-div')));
      }
    });
  },
  
  registerRetweetButtons: function() {
    $$('[data-posterous-retweet="true"]').each(function(e) {
      new PModal(e.id, '/posts/retweet', {post_id: e.readAttribute('data-posterous-post-id'), authenticity_token: window._token}, { width: 500, height: 160, identifier: 'retweet_modal_' + e.readAttribute('data-posterous-post-id')});
    });
  },
  
  parseCodeBlocks: function() {
    if ($$('[data-posterous-parse-code="true"]').length > 0) {
      dp.SyntaxHighlighter.ClipboardSwf = '/javascripts/syntaxhighlighter/clipboard.swf';
    	dp.SyntaxHighlighter.HighlightAll('code', false);
    }
  },
  
  replaceViewCounts: function(deferredContent) {
    $$('[data-posterous-view-count="true"]').each(function(e) {
      var postId = parseInt(e.readAttribute('data-posterous-post-id'), 10);
      if (deferredContent && deferredContent.post_views && deferredContent.post_views[postId]) {
        e.replace(deferredContent.post_views[postId]);
      }
    });
  },
  
  fillAllTimeAgoFields: function() {
    var fromDate = null;
    $$('[data-posterous-time-ago="true"]').each(function(e) {
      fromDate = parseInt(e.readAttribute('data-posterous-pubdate'), 10);
      e.replace(this._timeAgoInWords(fromDate) + ' ago');
    }, this);
  },
  
  insertAdminBox: function(deferredContent) {
    $$('[data-posterous-admin-box="true"]').each(function(e) {
      e.replace(deferredContent.admin_box);
    });
  },
  
  //=============================
  // Comments initialization
  //=============================

  initializeCommentForm: function(deferredContent, id) {
    var postId = null;
    var showFacebookOptions = false;
    var facebookLoginButton = null;
    var facebookLogoutButton = null;
    var twitterLoginButton = null;
    var posterousBodyTextarea = null;
    var emailNotifyToast = null;
    var twitterComment = null;
    var twitterOauthRedirect = null;
    
    var commentForms = id ? [$(id)] : $$('[data-posterous-comment-form="true"]');
    
    $$('[data-posterous-user-setting-toggle="true"]').each(function(e) {
      e.observe('click', function() {
        if (e.checked) {
          new Ajax.Request('/user_settings/set/' + e.readAttribute('data-posterous-user-setting-attribute'), {method: 'get'});;
        } else {
          new Ajax.Request('/user_settings/unset/' + e.readAttribute('data-posterous-user-setting-attribute'), {method: 'get'});;
        }
      });
    });
    
    commentForms.each(function(e) {
      postId = e.readAttribute('data-posterous-post-id');
      showFacebookOptions = e.readAttribute('data-posterous-facebook') == 'true';
      
      if (posterousBodyTextarea = $('pcomment_newbody_' + postId)) {
        new Texpand(posterousBodyTextarea);
      }
      
      e.select('.facebook_login_button').each(function(f) {
        f.observe('click', function(event) {
          event.stop();
          FB.login(function(response) { window.location.href = f.href; });
        });
      });

      if (facebookLogoutButton = e.down('.facebook_logout_button')) {
        facebookLogoutButton.observe('click', function(event) {
          event.stop();
          FB.logout(function(response) { window.location.reload(true); });
        });
      }
      
      if (twitterOauthRedirect = $$('[data-posterous-twitter-oauth="true"]').first()) {
        this.posts = unescape(twitterOauthRedirect.readAttribute('data-posterous-post-ids').gsub('+', ' ')).evalJSON();
      }
      
      e.select('.twitter_login_button').each(function(t) {
        t.observe('click', function(event) {
          event.stop();
          this.modalWindow = window.open('', '_blank', 'height=400,width=800,left=300,top=200,resizable=yes', true); 
          this._initOauthAndRedirectToPost('1', this.posts[parseInt(postId, 10)]);
        }.bindAsEventListener(this));
      }, this);
      
      if (emailNotifyToast = $('comment_email_notify_toast_' + postId)) {
        $('comment_email_notify_' + postId).observe('click', function() {
          this._refreshToast(postId, true);
        });
        this._refreshToast(postId, false);
      }
      
      if (twitterPreview = $('twitter_preview_' + postId)) {
        twitterComment = new PTwitterComment(
          'push_twitter_comment_' + postId, 
          'pcomment_newbody_' + postId,
          'twitter_body_' + postId,
          'twitter_preview_' + postId,
          twitterPreview.readAttribute('data-posterous-twitter-username'),
          twitterPreview.readAttribute('data-posterous-short-url'),
          twitterPreview.readAttribute('data-posterous-show-lin')
        );
        twitterComment.updateAll();
      }

      e.observe('submit', function(event) {
        event.stop();
        if ($('push_fbfeed_' + postId) && $('push_fbfeed_' + postId).checked && FB.getSession() == null) {
          FB.login(Prototype.empty);                
        }
        new Ajax.Updater('pcomment_comments_new_' + postId, e.action, {
          asynchronous: true,
          evalScripts: true,
          insertion: 'bottom',
          parameters: Form.serialize(this),
          onComplete: function() {            
            $('pcomment_submit_loading_' + postId).hide(); 
            $('posterous_submit_' + postId).show(); 
            $('pcomment_newbody_' + postId).value = ''; 
            if ($('first_comment_' + postId)) {
              $('first_comment_' + postId).hide();
            }
            if ($('twitter_body_' + postId)) {
              $('twitter_body_' + postId).value = '';
            }
            $('pcomment_comments_new_' + postId).highlight();
            
            if (showFacebookOptions) {
              window['fb_comment_' + postId] = $('pcomment_newbody_' + postId).value;
              window['push_fbfeed_' + postId] =  $('push_fbfeed_' + postId).checked;
              if (window['push_fbfeed_' + postId]) { 
                if (window['fb_comment_attachment_' + postId] == undefined) window['fb_comment_attachment_' + postId] = null;
                if (window['fb_comment_action_link_' + postId] == undefined) window['fb_comment_action_link_' + postId] = null;
                if (window.fbid_site_owner == undefined) window.fbid_site_owner = 1;
                new PeriodicalExecuter(function (pe) {
                  if (FB.getSession() != null) {
                    FB.ui({
                      method: 'stream.publish',
                      message: window['fb_comment_' + postId],
                      user_message_prompt: 'What are your comments?',
                      attachment: window['fb_comment_attachment_' + postId],
                      action_links: window['fb_comment_action_link_' + postId]
                    });
                    pe.stop();
                  }
                }, 1.0);
              }
              FB.XFBML.parse();
            }
          },
          onLoading: function() {
            $('pcomment_submit_loading_' + postId).show(); 
            $('posterous_submit_' + postId).hide();
          }
        });
      });
    }, this);
  },
  
  createNewCommentForm: function(deferredContent) {
    // Replace some placeholder with the new comment form we rendered
    if (!deferredContent.new_comment_form) {
      return;
    }
    $$('[data-posterous-new-comment-form="true"]').each(function(e) {
      e.replace(deferredContent.new_comment_form);
    });
  },
  
  initializeEditBoxes: function() {
    $$('[data-posterous-tag-modal="true"]').each(function(e) {
      new PModal(e.id, '/tag/edittags', {post_id: e.readAttribute('data-posterous-post-id')}, {height: 210});
    });
    
    $$('[data-posterous-autopost-modal="true"]').each(function(e) {
      new PModal(e.id, '/autopost/crosspost', {post_id: e.readAttribute('data-posterous-post-id')}, {width: 300, height: 300});
    });
  },
  
  removeUnauthorizedEditBoxes: function(deferredContent) {
    $$('[data-posterous-edit-box="true"]').each(function(e) {
      if (!deferredContent.edit_boxes[parseInt(e.readAttribute('data-posterous-post-id'), 10)]) {
        e.remove();
      } else {
        e.removeClassName('posterous_edit_box_hidden');
      }
    });
  },
  
  setAuthenticityToken: function(deferredContent) {
    if (deferredContent.authenticity_token) {
      window._token = deferredContent.authenticity_token;
    }
  },
  
  fixDeleteLinks: function() {
    $$('[data-posterous-delete-link="true"]').each(function(e) {
      e.observe('click', function(event) {
        Event.stop(event);
        if (confirm(e.readAttribute('data-posterous-confirm'))) { 
          var f = document.createElement('form'); 
          f.style.display = 'none'; 
          e.parentNode.appendChild(f); 
          f.method = 'POST'; 
          f.action = e.href;
          var m = document.createElement('input'); 
          m.setAttribute('type', 'hidden'); 
          m.setAttribute('name', '_method'); 
          m.setAttribute('value', 'delete'); 
          f.appendChild(m);
          var s = document.createElement('input'); 
          s.setAttribute('type', 'hidden'); 
          s.setAttribute('name', 'authenticity_token'); 
          s.setAttribute('value', window._token); 
          f.appendChild(s);
          f.submit(); 
        }
      });
    });
  },
  
  _refreshToast: function(postId, doFocus) {
    if ($('comment_email_notify_' + postId).checked) {
      $('comment_email_notify_toast_' + postId).value = 'Please enter your email address here';
      $('comment_email_notify_toast_' + postId).show();
      if (doFocus) {
        $('comment_email_notify_toast_' + postId).focus();
        $('comment_email_notify_toast_' + postId).select();                  
      }
    } else {
      $('comment_email_notify_toast_' + postId).value = '';
      $('comment_email_notify_toast_' + postId).hide(); 
    }
  },
  
  //=============================
  // Twitter OAuth Windows
  //=============================
  
  _initOauthAndRedirectToPost: function(providerType, redirectUrl) {
    this.modalWindow.location.href = $$('[data-posterous-twitter-oauth="true"]').first().readAttribute('data-posterous-redirect-url') + providerType;
    new PeriodicalExecuter(function(pe) {
      if (this.modalWindow.closed) {
        window.location.href = redirectUrl;
        pe.stop();
      }
    }.bind(this), 0.25);
  },
  
  //=============================
  // Time ago in words
  //=============================
  
  _timeAgoInWords: function(from) {
    var now = Math.floor((new Date().getTime()) / 1000);
    return this._distanceOfTimeInWords(now, from);
  },
  
  _distanceOfTimeInWords: function(to, from) {
    secondsAgo = (to - from);
    minutesAgo = Math.floor(secondsAgo / 60);

    if(minutesAgo == 0) { return 'less than a minute'; }
    if(minutesAgo == 1) { return '1 minute ago'; }
    if(minutesAgo < 45) { return minutesAgo + ' minutes'; }
    if(minutesAgo < 90) { return ' 1 hour'; }
    hoursAgo  = Math.floor(minutesAgo / 60);
    if(minutesAgo < 1440) { return hoursAgo + ' hours'; }
    if(minutesAgo < 2880) { return '1 day'; }
    daysAgo  = Math.floor(minutesAgo / 1440);
    if(minutesAgo < 43200) { return daysAgo + ' days'; }
    if(minutesAgo < 86400) { return '1 month'; }
    monthsAgo  = Math.floor(minutesAgo / 43200);
    if(minutesAgo < 525960) { return monthsAgo + ' months'; }
    if(minutesAgo < 1051920) { return '1 year'; }
    yearsAgo  = Math.floor(minutesAgo / 525960);
    return 'over ' + yearsAgo + ' years';
  }
  
  
});

document.observe('dom:loaded', function() { p = new Posterous(); });