/*--------------------------------------------------------*/
/* PublicSquare Public Javascript Library                 */
/*--------------------------------------------------------*/

var PublicSquare = { global: {}, user: {}, feedback: {}, comment: {}, idea: {}, topic: {}, rating: {} };
  
/*--------------------------------------------------------*/
/* GLOBAL                                                 */
/*--------------------------------------------------------*/

Object.extend(PublicSquare.global, {
  error500: function() {
    alert('Something went wrong. We are sorry. We have been notified already, and will take a look shortly')
  },
  popup: function(url, width, height) {
    window.open(this.href, 'ps_popup', 'width=' + width + ',height=' + height + ',status=0,scrollbars=0,resizable=1,location=0,toolbar=0');
  }  
});

/*--------------------------------------------------------*/
/* USER                                                   */
/*--------------------------------------------------------*/
  
Object.extend(PublicSquare.user, {
  role: function() {
    var match = document.cookie.match(/role=([\w]+)/);
    return match ? match[1] : false;
  },
  isStaff: function() {
    return this.role() && this.role() != 'none';
  },
  id: function() {
    var match = document.cookie.match(/logged_in=([\d]+)/);
    return match ? match[1] : false;
  },
  isLoggedIn: function() {
    return this.id() != false;
  }
});

/*--------------------------------------------------------*/
/* FEEDBACK ON COMMENTS, IDEAS, FORUM TOPICS              */ 
/*--------------------------------------------------------*/

Object.extend(PublicSquare.feedback, {
  renderPoints: function(sum) {
    sum = parseInt(sum);
    return (sum >= 0 ? "+" : "-") + Math.abs(sum) + " " + (Math.abs(sum) == 1 ? "vote" : "votes");;
  },
  setup: function(content) {      
    if (PublicSquare.user.isStaff() && $('content_' + content["id"] + '_admin')) $('content_' + content["id"] + '_admin').show();
    if (PublicSquare.user.isLoggedIn() && $('content_' + content["id"] + '_feedback')) $('content_' + content["id"] + '_feedback').show();
    if ($('content_' + content["id"] + '_points')) $('content_' + content["id"] + '_points').innerHTML = this.renderPoints(content["points"]);    
  },    
  kill: function(content_id) {
    if (confirm("Are you sure you want to delete this entry?")) {
      this.killLoading(content_id);
      new Ajax.Request('/contents/delete/' + content_id, {asynchronous:true, evalScripts:true});
    }
  },
  ban: function(content_id) {
    if (confirm("Delete this entry AND ban the user who posted it?")) {
      this.killLoading(content_id);
      new Ajax.Request('/contents/ban/' + content_id, {asynchronous:true, evalScripts:true});
    }
  },
  positive: function(content_id) {
    new Ajax.Request('/contents/vote/' + content_id + '/positive', {
      asynchronous:true, evalScripts:true, 
      onComplete: function(transport) { PublicSquare.feedback.voteComplete(content_id, transport); }
    }); 
  },
  negative: function(content_id) {
    new Ajax.Request('/contents/vote/' + content_id + '/negative', {asynchronous:true, evalScripts:true, 
      onComplete: function(transport) { PublicSquare.feedback.voteComplete(content_id, transport); }
    }); 
  },
  flag: function(content_id) {
    this.flagLoading(content_id);
    new Ajax.Request('/contents/vote/' + content_id + '/flag', {asynchronous:true, evalScripts:true}); 
  },
  killLoading: function(content_id) {
    new Effect.Fade('content_' + content_id);
  },
  voteComplete: function(content_id, transport) {
    $('content_' + content_id + '_points').innerHTML = PublicSquare.feedback.renderPoints(transport.responseText);
    $('content_' + content_id + '_points').visualEffect('highlight', { duration: 5 });
  },
  flagLoading: function(content_id) {
    new Effect.Fade('content_' + content_id);
  }
});

/*--------------------------------------------------------*/
/* TOPIC                                                  */ 
/*--------------------------------------------------------*/

Object.extend(PublicSquare.topic, PublicSquare.feedback);
Object.extend(PublicSquare.topic, {
  edit: function(content_id) {
    window.location.href = '/topics/edit/' + content_id;
  },
  kill: function(content_id) {
    if (confirm("Are you sure you want to delete this topic?")) {
      window.location.href = '/topics/delete/' + content_id;
    }
  },
  ban: function(content_id) {
    if (confirm("Delete this entry AND ban the user who posted it?")) {
      window.location.href = '/topics/ban/' + content_id;
    }
  },
  flagLoading: function(content_id) {   
    $('content_' + content_id + '_flagging').innerHTML = 'Thank you!'
  }
});
  
/*--------------------------------------------------------*/
/* COMMENT                                                */ 
/*--------------------------------------------------------*/

Object.extend(PublicSquare.comment, PublicSquare.feedback);
Object.extend(PublicSquare.comment, {
  setupAllComments: function(content_id) {
    // No-op
  },
  submit: function(form, comment_id) {
    if (form.elements['comment[body]'].value == '') {
      alert('Please enter something for the body.');
      return false;
    }
    new Ajax.Request(form.action, {
      asynchronous:true, evalScripts:true, parameters:Form.serialize(form),
      onLoading:function(transport) {
        $('comment_' + comment_id + '_submit').disabled = true;
        if ($('comment_' + comment_id + '_busy')) $('comment_' + comment_id + '_busy').show();
        if ($('comment_' + comment_id + '_edit_actions')) $('comment_' + comment_id + '_edit_actions').hide();
      }, 
      onComplete:function(transport) {
        if (comment_id == '') {
          new Insertion.Bottom('comments', transport.responseText);
          $('comment__body').value = '';
          $('comment__submit').disabled = false;
          if ($('comment__busy')) $('comment__busy').hide();
          if ($('comment_' + comment_id + '_edit_actions')) $('comment_' + comment_id + '_edit_actions').show();
        } else {
          $('content_' + comment_id).replace(transport.responseText)
        }
      }
    });       
  },
  edit: function(comment_id) {
    var display = $('comment_' + comment_id + '_inner');
    $('content_' + comment_id)['publicsquare:saved_inner'] = display.innerHTML;
    new Ajax.Updater(display, '/comment/edit/' + comment_id, { asynchronous: true });
  },
  cancel_edit: function(comment_id) {
    $('comment_' + comment_id + '_inner').innerHTML = $('content_' + comment_id)['publicsquare:saved_inner']
  }
});

/*--------------------------------------------------------*/
/* IDEA                                                   */ 
/*--------------------------------------------------------*/

Object.extend(PublicSquare.idea, PublicSquare.feedback);
Object.extend(PublicSquare.idea, {
  renderCount: function(count) {
    count = parseInt(count);
    if (count == 1) {
      return "1 person";        
    } else {
      return count + " people";
    }
  },
  vote: function(vote, idea_id) {
    new Ajax.Request('/idea/vote/' + idea_id + '/' + vote, {
      asynchronous:true, evalScripts:true, 
      onComplete: function(transport) { PublicSquare.idea.votingComplete(vote, idea_id, transport); }
    }); 
  },
  votingComplete: function(vote, idea_id, transport) {
    if (vote != 'flag') {
      var elm = $('idea_' + idea_id + '_' + vote + 's_count');
      if (elm) {
        elm.innerHTML = PublicSquare.idea.renderCount(PublicSquare.idea.info[vote + "s_count"]);
        elm.visualEffect('highlight', { duration: 5 });
      }
    }
  },
  flagLoading: function(content_id) {
    if ($("idea_" + content_id + "_flagging")) $("idea_" + content_id + "_flagging").innerHTML = "Thank you!";
  }
});
  
/*--------------------------------------------------------*/
/* RATING                                                 */
/*--------------------------------------------------------*/
  
Object.extend(PublicSquare.rating, {
  timeout: null,
  LABELS: ["Yuck!", "You can do better", "Pretty decent", "Quite useful", "Outstanding"],
  over: function(num) {
    clearTimeout(this.timeout);
    for (var i = 0; i < 5 ; i++)
      Element.addClassName('rater_' + i, "in");
    for (var i = 0; i < num ; i++)
      Element.addClassName('rater_' + i, "over");
    for (var i = num; i < 5 ; i++)
      Element.removeClassName('rater_' + i, "over");
    $('rating_label').innerHTML = "&ldquo;" + this.LABELS[num - 1] + "&rdquo;";
  },
  click: function(num, url) {
    new Ajax.Request(
      url, {
        asynchronous:true,
        parameters:'rating=' + encodeURIComponent(num)
      }
    );
    for (var i = 0; i < num ; i++)
      Element.addClassName('rater_' + i, "selected");
    for (var i = num; i < 5 ; i++)
      Element.removeClassName('rater_' + i, "selected");
    for (var i = 0; i < 5 ; i++)
      Element.removeClassName('rater_' + i, "in");
    $('rating_label').innerHTML = '&nbsp;';
  },
  widgetOut: function() {
    clearTimeout(this.timeout);
    this.timeout = setTimeout(function() {
      for (var i = 0; i < 5 ; i++)
        Element.removeClassName('rater_' + i, "in");
      $('rating_label').innerHTML = '&nbsp;';
    }, 1);
  }
});

/*--------------------------------------------------------*/
/* Extensions to prototype.js                             */
/*--------------------------------------------------------*/

Element.PublicSquareMethods = {
  toggleActive: function(element) {
    element = $(element);
    if (element.active()) {
      element.deactivate();
    } else {
      element.activate();
    }    
    return element;
  },
  active: function(element) {
    return element['publicsquare:active'];
  },
  activate: function(element) {
    element = $(element)
    if (element.active()) return element;
    element['publicsquare:inactive_text'] = element.innerHTML;
    element['publicsquare:inactive_class'] = element.className;
    element.innerHTML = element.getAttribute('publicsquare:active_text');
    element.className = element.getAttribute('publicsquare:active_class') || element.className;
    element['publicsquare:active'] = true;
    return element;
  },
  deactivate: function(element) {
    element = $(element)
    if (!element.active()) return element;
    element.innerHTML = element['publicsquare:inactive_text'];
    element.className = element['publicsquare:inactive_class'];
    element['publicsquare:active'] = false;
    return element;
  }
}

Object.extend(Element, Element.PublicSquareMethods);
Object.extend(Element.Methods, Element.PublicSquareMethods);

Element.addMethods();


