var PokeRep = {};

PokeRep.StickyHeader = function(container) {
  var self = this;
  
  self.initialize = function(container) {
    self.container = container;
    /* header is the sticky element */
    self.header = self.container.select('tr:first-child');
    if (!self.header) return;
    self.header = self.header[0];
    if (!self.header) return;
    
    self.stuck = false;
    self.headerOffsetY = self.header.cumulativeOffset()[1];
    /* set up future adjustment of container for smooth transition
     * need to set "position: 'relative'" to activate this */
    self.container.setStyle({ top: self.header.getHeight() + 'px' });
    /* set up future position of header
     * need to set "position: 'fixed'" to activate this */
    self.header.setStyle({ top: '0', 'z-index': '99' });
    
    /* sticky/unsticky when scrolling */
    Event.observe(document, 'scroll', function() {
      var scrollOffsetY = document.viewport.getScrollOffsets()[1];
      if (scrollOffsetY >= self.headerOffsetY) {
        self.stick();
      } else {
        self.unstick();
      }
    });
    
    /* resize stickied header when resizing */
    Event.observe(window, 'resize', function() {
      if (self.stuck) {
        self._syncWidths();
      }
    })
  }
  
  /** 
   * Stick header onto top of screen. 
   */
  self.stick = function() {
    if (self.stuck) return;
    
    self._syncWidths();
    /* make sticky */
    self.header.setStyle({ position: 'fixed' });
    self.container.setStyle({ position: 'relative' });
    self.stuck = true;
  }
  
  /**
   * Sets widths of each header cell equal to a sample data row.
   */
  self._syncWidths = function() {
    var sampleRow = self.header.next();
    if (!sampleRow) return;
    var sampleCells = sampleRow.select('td');
    var headerCells = self.header.select('th');
    /* fix current data cells width, otherwise will deform when header cells get stickied */
    self._syncCellsWidths(sampleCells, sampleCells);
    /* sync widths of header cells to widths of cells of a sample data row */
    self._syncCellsWidths(headerCells, sampleCells);
  }
  
  /**
   * Set widths of fooCells to corresponding widths of barCells.
   */
  self._syncCellsWidths = function(fooCells, barCells) {
    if ((fooCells.length != barCells.length) || (fooCells.length == 0)) return;
    var padding = (fooCells[0].getStyle('padding-left').match(/(\d+)px/)[1] * 2) + 1;
    var cell = null;
    for (var i = 0; i < fooCells.length; i++) {
      cell = fooCells[i];
      fooCells[i].setStyle({ width: (barCells[i].getWidth() - padding) + 'px' });
    }
  }
  
  self.unstick = function() {
    if (!self.stuck) return;
    
    self.header.setStyle({ position: '' });
    self.container.setStyle({ position: '' });
    self.stuck = false;
  }
  
  self.initialize(container);
}

document.observe('dom:loaded', function() {
  var main_menu = $('main_menu');
  if (main_menu) {
    new PokeRep.StickyHeader(main_menu);
  }
});


/* OLD */

/* Displays information specified by sURL asynchronously inside sLocation */
function displayInfo(sUrl, sLocation) {
	Ajax(sUrl, sLocation, 'GET');
}

/* Triggers a Pokemon's cry given its padded ID number */
function pokemonCry (pidpad) {
	// displays code for playing sound file inside the "pokerep" div element
	displayContent('<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab"><param name="src" value="/pokerep/images/cries/' + pidpad + '.mp3" /><param name="hidden" value="true" /><param name="autoplay" value="true" /><!--[if !IE]>--><object type="audio/mpeg" data="/pokerep/images/cries/' + pidpad + '.mp3"><param name="autoplay" value="true" /><param name="hidden" value="true" /></object><!--<![endif]--></object>', 'pokecry');
}

/* Advanced Search functions */
function resetForm (form) {
	if (form) {
		resetSelect(form.generation);
		form.name.value = '';
		resetSelect(form['type1[]']);
		resetSelect(form['type2[]']);
		resetChecked(form.types_boolean);
		resetSelect(form['eggs[]']);
		resetSelect(form.ability);
		resetSelect(form.move);
		resetChecked(form['move_types[]']);
	}
}

function resetChecked (radio) {
	if (radio) {
		for (i = 0; i < radio.length; i++)
			radio[i].checked = false;
	}
}

function resetSelect (selection) {
	if (selection) {
		selection.selectedIndex = -1;
	}
}

/* Advanced Search - gather inputs in form and send data */
function searchAjax (form) {
	var q = 'submit=1&';
	q += makeParamText(form['name']);
	q += makeParamSelect(form.generation);
	q += makeParamSelect(form['type1[]']);
	q += makeParamSelect(form['type2[]']);
	q += makeParamChecked(form.types_boolean);
	q += makeParamSelect(form['eggs[]']);
	q += makeParamSelect(form.ability);
	q += makeParamSelect(form.move);
	q += makeParamChecked(form['move_types[]']);
	displayInfo('/pokerep/library/search_ajax.php?' + q, 'search_results');
}

function makeParam (variable, value) {
	return encodeURIComponent(variable) + '=' + encodeURIComponent(value) + '&';
}

function makeParamSelect (selection) {
	var q = '';
	if (selection.selectedIndex != -1) {
		var length = selection.length;
		for (var i = 0; i < length; i++) {
			if (selection.options[i].selected && selection.options[i].value != '-') {
				q += makeParam(selection.name, selection.options[i].value);
			}
		}
	}
	return q;
}

function makeParamChecked (radio) {
	var q = '';
	var length = radio.length;
	for (i = 0; i < length; i++) {
		if (radio[i].checked) {
			q += makeParam(radio[i].name, radio[i].value);
		}
	}
	return q;
}

function makeParamText (text) {
	return (text.value != '') ? makeParam(text.name, text.value) : '';
}