var HelpDesk = {
  viewingTicket:null,
  closedMode: false,
  initialized: false,
  
  initialize: function(options){
    if ( this.initialized ) return;
    this.initialized = true;
    this.options = Object.extend({
      selectedClass: 'selected',
      evenStripeClass: 'stripe0',
      oddStripeClass: 'stripe1',
      rowSelector: '#user_ticket_list tbody tr',
      activeRowSelector: '#user_ticket_list tbody tr.selected',
      effectsDuration: 0.75
    }, options || {});

    this.disabledPanel = $('disabled');
    this.newTicketPanel = $('new_ticket');
    if (this.disabledPanel && this.newTicketPanel) this.disabledPanel.setStyle( { height: (this.newTicketPanel.getHeight() + 10) + 'px' } );

    this.scrollCommentsDown(); // scroll to the most recent comment
    this._setup();
    
    if (this.viewingTicket){
      var t = $('ticket_' + this.viewingTicket);
      t.scrollTo(t.up('div.tickets'));
    }
  },

  checkBrowser: function(){
    if ( this._checkCookieSupport()){
      $('portal_login_wrapper').show();
      $('browser_requirements').hide();
      $('login_user_email').focus();
    }
  },
  
  ticketClick: function(event){
    var clicked = event.element();
    if ( clicked.tagName.toString().toLowerCase() != 'a' ){
      var row = event.findElement('tr');
      this._showIndicator(row);

      var ticket_id = row.getAttribute('ticket_id');
      var postBody = 'id=' + ticket_id + '&closed_mode=' + this.closedMode;
      new Ajax.Request('/help_desk/tickets/show', {asynchronous:true, evalScripts:true, parameters:postBody});
    }
  },
  ticketMouseOver: function(event){
    var row = event.findElement('tr');
    row.addClassName('hover');
  },
  ticketMouseOut: function(event){
    var row = event.findElement('tr');
    row.removeClassName('hover');
  },
  addTicket: function(options){
    // called from RJS after a new ticket is created
    var ticket_id = options['ticket_id'];
    this._refresh();
    this._observeRow('ticket_' + ticket_id);
  },
  showTicket: function(options){
    // called from RJS after a row is clicked

    var ticketID = options.ticketID;
    var latestCommentID = options.latestCommentID;
    var row = $('ticket_' + ticketID);
    $$(this.options.activeRowSelector).invoke('removeClassName', 'selected');
    row.addClassName('selected');
    this._hideIndicator(row);
    
    if ( !this.closedMode ) this.pollForComments(options);
  },
  pollForComments: function(options){
    this.showingTicketID = options.ticketID;
    this.lastCommentID = options.lastCommentID || 0;

    this.stopPollingForComments();
    this.commentPoller = setInterval(function(){
      new Ajax.Request('/helpdesk/tickets/refresh_comments', {parameters:{id:this.showingTicketID, last_comment_id:this.lastCommentID}});
    }.bind(this), 30000);
  },
  updateLastCommentId: function(id){ this.lastCommentID = id; },
  stopPollingForComments: function(){
    if (this.commentPoller) clearInterval(this.commentPoller);
  },
  removeTicket: function(options){
    // called from RJS after a ticket is closed
    var ticket_row = $('ticket_' + options['ticket_id']);
    ticket_row.removeClassName('selected').removeClassName('hover').addClassName('removed');
    this._hideIndicator(ticket_row);
    window.setTimeout(function(){
      ticket_row.remove();
      this._ticketRemoved();
    }.bind(this), 1000);
  },
  scrollCommentsDown: function() {
    var viewingTicket = $('viewing_ticket');
    if (!viewingTicket) return;
    var ol = viewingTicket.down('ol'), latestComment = ol.select('li').last();
    if (latestComment) Element.scrollTo.delay(0.25, latestComment, ol);
  },
  showCreateTicket: function(dont_show_button){
    $$('#new_ticket div.content').first().blindDown( {duration: this.options.effectsDuration } );
    $('show_new_request').blindUp( { duration: this.options.effectsDuration } );

    if (dont_show_button)
      $('new_ticket_cancel').hide();
    else
      $('new_ticket_cancel').show();

    window.setTimeout(function(){
      $('new_ticket_summary').focus();
      new Effect.ScrollTo('new_ticket', { duration: this.options.effectsDuration } );
    }.bind(this), 1000);

  },
  hideCreateTicket: function(){
    $$('#new_ticket div.content').first().blindUp( { duration:this.options.effectsDuration } );
    $('show_new_request').blindDown( { duration:this.options.effectsDuration } );
    $('new_ticket_cancel').hide();
  },

  _showIndicator: function(row){
    var indicator = $(row.getElementsByTagName('img')[0]);
    indicator.show();
  },
  _hideIndicator: function(row){
    var indicator = $(row.getElementsByTagName('img')[0]);
    indicator.hide();
  },
  _setup: function(){
    this.tickets_table = $('ticket_list');
    this.tickets = $$(this.options.rowSelector);
    
    this.tickets.each(function(row){
      this._observeRow(row);
    }.bind(this));
    this.view_panel = $('viewing_ticket');
    this.selected_ticket = null;
  },
  _observeRow: function(row){
    row = $(row);
    Event.observe(row, 'click', this.ticketClick.bindAsEventListener(this));
    if (Browser.ie6){
      Event.observe(row, 'mouseover', this.ticketMouseOver.bindAsEventListener(this));
      Event.observe(row, 'mouseout', this.ticketMouseOut.bindAsEventListener(this));
    }
  },
  _ticketRemoved: function(){ this._refresh(); },
  _refresh: function(){ this.tickets = $$(this.options.rowSelector); },
  _checkCookieSupport:function(){ return this._hasCookie('compatibility_test'); },
  _hasCookie:function(name){ return (document.cookie.indexOf(name) > -1); }
};

Event.register( HelpDesk );