// Run on document ready
$(function() { 
  // Activate event table actions
  enableTable();
}); 

// Activate the table
function enableTable()
{ 
  // Invoke tablesorter
  //addTableSorter();
  //addDateParser();
  //$("#event_cal").tablesorter({
  //  sortList:[[0,0]],
  //  widgets:['zebra','eventTable'], 
  //  headers:{
  //    1:{sorter:"eventdate"},
  //    2:{sorter:false},
  //    3:{sorter:false}
  //  }
  //});

  // Hide the filter boxes by default
  $("#filterbox div.content").css("display","none");

  // Attach click behaviors
  bindBehaviors(); 

  // Enable Thickbox links (only necessary if they're generated dynamically)
  //tb_init("#event_cal a.thickbox");//pass where to apply thickbox 

} 


// Add event handlers after ajax load
var bindBehaviors = function() {
  // Header row initial state
  $('tr.eventHead').click(function() {
    $(this).addClass('eventActive'); 
    var rowId = $(this).attr('alt');
    $('tr.eventBody[alt='+rowId+']').show();
    $(this).unbind('click');
    bindClose( $(this) );

    // Fix scroll panel
    $('.scroll-pane').jScrollPaneRemove();
    activate_scrollpanels();
  });

  // Hover on table row
  $('tr.eventHead').hover(function() {
    var rowId = $(this).attr('alt');
    $('tr.eventHead[alt='+rowId+']').addClass('eventOver');
  }, function() {
    var rowId = $(this).attr('alt');
    $('tr.eventHead[alt='+rowId+']').removeClass('eventOver');
  }); 

  // Close buttons
  bindCloseBtns();
  // Link to 'open all'
  bindAllOpen();
  // Link to 'close all'
  bindAllClosed();
}

// Set the filter click function to 'close'
var bindFilterClose = function(oHead, oBody) {
  oHead.removeClass('closed');
  oHead.addClass('open');
  oBody.slideDown(); // was show();
  // Rebind for open
  oHead.click(function() {
    oHead.unbind('click');
    bindFilterOpen( oHead, oBody );
  }); 
};

// Set the filter click function to 'open'
var bindFilterOpen = function(oHead, oBody) {
  oHead.removeClass('open');
  oHead.addClass('closed');
  oBody.slideUp(); // was hide();
  // Rebind for close
  oHead.click(function() {
    oHead.unbind('click');
    bindFilterClose( oHead, oBody );
  }); 
}


// Reset the table header click function to 'close'
var bindClose = function(obj) {
    obj.click(function() {
      var rowId = $(this).attr('alt');
      $('tr.eventBody[alt='+rowId+']').hide();
      $('tr.eventHead[alt='+rowId+']').removeClass('eventActive'); 
      obj.unbind('click');
      bindOpen( obj );

      // Fix scroll panel
      $('.scroll-pane').jScrollPaneRemove();
      activate_scrollpanels();
    }); 
};

// Reset the table header click function to 'open'
var bindOpen = function(obj) {
  obj.click(function() {
    obj.addClass('eventActive'); 
    var rowId = obj.attr('alt');
    $('tr.eventBody[alt='+rowId+']').show();
    obj.unbind('click');
    bindClose( obj );

    // Fix scroll panel
    $('.scroll-pane').jScrollPaneRemove();
    activate_scrollpanels();
  }); 
}


// Close button
var bindCloseBtns = function() {
  $("a.closeBtn").click(function() {
    rowId = $(this).attr('rel');
    $('tr.eventBody[alt='+rowId+']').hide();
    $('tr.eventHead[alt='+rowId+']').removeClass('eventActive'); 
    // Reset the header click  function to 'open'
    $('tr.eventHead[alt='+rowId+']').unbind('click');
    bindOpen( $('tr.eventHead[alt='+rowId+']') );
    return false;
  });
}


// Bind all open
var bindAllOpen = function() {
  $("a.openAllEvents").click(function() {
    $("tr.eventHead").click();
    return false;
  });
}

// Bind all closed
var bindAllClosed = function() {
  $("a.closeAllEvents").click(function() {
    $("a.closeBtn").click();
    return false;
  });
}



// Returns true if a value is in an array
Array.prototype.in_array = function ( obj ) {
  var len = this.length;
  for ( var x = 0 ; x <= len ; x++ ) {
    if ( this[x] == obj ) return true;
  }
  return false;
} 

// Display a string or simple array in an alert box
function dump_var( v ) {
  if(typeof v === 'string') {
    alert(v);
  } else {
    var txt='';
    for( var i in v ) {
      txt += '[' + i + '] = [' + v[i] + ']\n';
    }
    alert(txt);
  } 
} 

// open a popup window
var newwin='';
function popWindow(theUrl,width,height,full) {
    // use defaults if width and height were not supplied
    var ismoz = navigator.userAgent.indexOf("Gecko");
    var isie = navigator.userAgent.indexOf("MSIE");
    var default_width = 600;
    var default_height = 450;
    var offset_width = (isie != -1) ? 4 : 0;
    var offset_height = (isie != -1) ? 4 : 0;
    var popType = (full) ? ",scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes,directories=yes" : ",scrollbars=no,resizable=yes,status=no";
    
    var popWidth = (width) ? width + offset_width : default_width + offset_width;
    var popHeight = (height) ? height + offset_height : default_height + offset_height;
    var popLeft = self.screen.availWidth/2 - popWidth/2;
    var popTop = self.screen.availHeight/2 - popHeight/2;
    
    if(theUrl) {
        if(newwin)
            newwin.close();
        newwin = window.open(theUrl,'newwin','left='+popLeft+',top='+popTop+',width='+popWidth+',height='+popHeight+popType);
    }

    return;
}

// TableSorter Widget to keep data rows attached to header rows
/*
function addTableSorter()
{
  var dr_htm = [];
  var dr_num = [];
  var sep_htm = '<tr class="separator"><td colspan="4"><img src="images/events/event_separator.gif" alt="" width="580" height="5" /></td></tr><tr class="null"><td colspan="4"></td></tr>';
  var rowId = 0;
  $.tablesorter.addWidget({ 
    // Give the widget a id 
    id: "eventTable", 
    // Format is called on init and when a sorting has finished 
    format: function(table) { 
      // Collect all eventBody rows (only once)
      $("tr.eventBody").each(function() { 
        rowId = $(this).attr('alt');
        if( !dr_num.in_array(rowId) ) {
          dr_num.push( rowId );
          dr_htm.push( $(this).clone() ); 
        };
      }); 
      
      // Remove eventBody, separator, and null rows
      $("tr.eventBody").remove(); 
      $("tr.separator").remove(); 
      $("tr.null").remove(); 

      // Replace eventBody and separator rows in the proper place
      for(var i=0; i<dr_num.length; i++) {
        rowId = dr_num[i];
        // Restore eventBody row
        $('tr.eventHead[alt='+rowId+']').after(dr_htm[i]);
        // Remove 'odd' class from event body
        $('tr.eventBody[alt='+rowId+']').removeClass("odd");
        // Add class 'odd' to event body if the event head has it
        if( $('tr.eventHead[alt='+rowId+']').hasClass("odd") ) {
          $('tr.eventBody[alt='+rowId+']').addClass("odd");
        }
        // Append separator row
        $('tr.eventBody[alt='+rowId+']').after(sep_htm);
      }
      
      // Close button
      //$('tr.eventBody img[alt=Close Detail]').click(function() {
      $('a.closeBtn').click(function() {
        rowId = $(this).attr('rel');
        $('tr.eventBody[alt='+rowId+']').hide();
        $('tr.eventHead[alt='+rowId+']').removeClass('eventActive'); 
        // Reset the header click  function to 'open'
        $('tr.eventHead[alt='+rowId+']').unbind('click');
        bindOpen( $('tr.eventHead[alt='+rowId+']') );
        return false;
      });
    }
  });
}


// Add tablesorter parser for our date format
function addDateParser()
{
  $.tablesorter.addParser({ 
    // set a unique id 
    id: 'eventdate', 
    is: function(s) { 
      // return false so this parser is not auto detected 
      return false; 
    }, 
    format: function(s) { 
      // Trim anything after a <br> or <BR>
      if(s.indexOf('<br') != -1) 
          s = s.substr(0, s.indexOf('<br') );
      if(s.indexOf('<BR') != -1) 
          s = s.substr(0, s.indexOf('<BR') );

      // Disregard 'ending date', then use "usLongDate" processing
      if(s.indexOf(' - ') != -1) {
        // Fixes most multi-day events
        s = s.replace(/ - .+,/,','); 
        // Special case for year-spanning events
        if(s.lastIndexOf(',') > 6) {
          s = s.substr(0, s.lastIndexOf(',') );
        }
      }
      return $.tablesorter.formatFloat(new Date(s).getTime());
    }, 
    // set type, either numeric or text 
    type: 'numeric' 
  });
}
*/

