function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function dont_keep_all_fields_expanded(){
	keep_all_fields_expanded(false);
}

function keep_all_fields_expanded(expand){
	//defaults
	if( expand == 'cookie' ){
		if( readCookie('earmark_keep_all_fields_expanded') ) expand = true;
		else expand = false;
	}
	if( expand == null || typeof(expand) == 'object' ) expand = true;
	
	//get our element
	var element = document.getElementById('keep_all_fields_expanded');
	if( expand == true ){
		createCookie('earmark_keep_all_fields_expanded', 'true', 365);
		element.innerHTML = 'Allow fields to collapse';
		element.onclick = dont_keep_all_fields_expanded;
		element.className = 'earmark_locked';
	}else{
		eraseCookie('earmark_keep_all_fields_expanded');
		element.innerHTML = 'Keep all fields expanded';
		element.onclick = keep_all_fields_expanded;
		element.className = 'earmark_unlocked';
	}
	
	collapse_form();
}

function getSelectedRadio(buttonGroup) {
	if (buttonGroup[0]) {
		for (var i=0; i<buttonGroup.length; i++) {
			if (buttonGroup[i].checked) return i;
		}
	}
	if (buttonGroup.checked) return 0;
	return false;
}

function getSelectedRadioValue(buttonGroup) {
	var i = getSelectedRadio(buttonGroup);
	if ( i === false ) return false;

	if (buttonGroup[i]) return buttonGroup[i].value;
	else return buttonGroup.value;
}

function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

function collapse_form(){
	var tables = new Array();
	tables['lawmaker'] = new Array('lawmaker_id', 'lawmaker_state', 'lawmaker_affiliation', 'lawmaker_chamber');
	tables['beneficiary'] = new Array('beneficiary_name', 'beneficiary_city', 'beneficiary_state');
	tables['earmark'] = new Array('earmark_title', 'earmark_category', 'earmark_heading', 'earmark_service', 'earmark_description', 'earmark_budget', 'earmark_house', 'earmark_senate', 'earmark_conference');

	var selectedTable = getSelectedRadioValue(document.forms['earmark_search'].search_type);
	
	//if we don't have a radio button selected, choose the top one and try again.
	if( selectedTable === false ){
		document.forms['earmark_search'].search_type[0].checked = true;
		collapse_form();
	}else{
		//we have a table selected.
		//go through each table, collapse/expand it and change the label
		for(var table in tables){
			//Upper case the first letter of the table name
			var currTableUCF = table.substr(0,1).toUpperCase() + table.substr(1, table.length -1);
			//see if we have any fields filled out for this table
			var emptyFieldset = true;
			for( var field in tables[table] ){
				var str = tables[table][field];
				if( document.getElementById(str).value.length > 0 && document.getElementById(str).value != 'any' ){
					//alert(table + "\n" + document.getElementById(str).value + "\n" + document.getElementById(str).value.length);
					emptyFieldset = false;
				}
			}
			
			//if this not the selected table (ie: a related table)collapse it
			if( selectedTable != table ){
				//if there are no fields filled out, we can collapse it
				if( emptyFieldset ) toggle_fieldset('earmark_' + table + '_criteria_button', 'earmark_' + table + '_criteria_fieldset', 'none');
				//change the label
				document.getElementById('earmark_' + table + '_criteria_title').innerHTML = 'Related ' + currTableUCF + ' Criteria';
				//if this is not the selected table, we want to force it to the bottom
				document.getElementById('earmark_search_criteria').appendChild(document.getElementById('earmark_' + table + '_criteria_box'));
			}else{
				toggle_fieldset('earmark_' + table + '_criteria_button', 'earmark_' + table + '_criteria_fieldset', 'block');
				document.getElementById('earmark_' + table + '_criteria_title').innerHTML = currTableUCF + ' Criteria';
			}
		}
	}
}

function toggle_fieldset(buttonId, fieldsetId, override){
	if( readCookie('earmark_keep_all_fields_expanded') ) display = 'block';
	else{
		if( override ) display = override;
		else display = (document.getElementById(fieldsetId).style.display == 'none') ? 'block' : 'none';
	}
	
	var buttonText = (display == 'block') ? 'Collapse' : 'Expand';
	var buttonClass = (display == 'block') ? 'earmark_expanded' : 'earmark_collapsed';
	document.getElementById(buttonId).innerHTML = buttonText;
	document.getElementById(buttonId).className = buttonClass;
	document.getElementById(fieldsetId).style.display = display;
}

/************************************************************************************************************
(C) www.dhtmlgoodies.com, November 2005

This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.	

Terms of use:
You are free to use this script as long as the copyright message is kept intact. However, you may not
redistribute, sell or repost it without our permission.

Thank you!

www.dhtmlgoodies.com
Alf Magne Kalleland

************************************************************************************************************/
	
var tableWidget_okToSort = true;
var tableWidget_arraySort = new Array();
tableWidget_tableCounter = 1;
var activeColumn = new Array();
var currentColumn = false;

function sortNumeric(a,b){
	
	a = a.replace(/,/,'.');
	b = b.replace(/,/,'.');
	a = a.replace(/[^\d\.\/]/g,'');
	b = b.replace(/[^\d\.\/]/g,'');
	if(a.indexOf('/')>=0)a = eval(a);
	if(b.indexOf('/')>=0)b = eval(b);
	return a/1 - b/1;
}


function sortString(a, b) {

  if ( a.toUpperCase() < b.toUpperCase() ) return -1;
  if ( a.toUpperCase() > b.toUpperCase() ) return 1;
  return 0;
}
	
function sortTable()
{
	if(!tableWidget_okToSort)return;
	tableWidget_okToSort = false;
	/* Getting index of current column */
	var obj = this;
	var indexThis = 0;
	while(obj.previousSibling){
		obj = obj.previousSibling;
		if(obj.tagName=='TD')indexThis++;		
	}
	
	if(this.getAttribute('direction') || this.direction){
		direction = this.getAttribute('direction');
		if(navigator.userAgent.indexOf('Opera')>=0)direction = this.direction;
		if(direction=='ascending'){
			direction = 'descending';
			this.setAttribute('direction','descending');
			this.direction = 'descending';	
		}else{
			direction = 'ascending';
			this.setAttribute('direction','ascending');		
			this.direction = 'ascending';		
		}
	}else{
		direction = 'ascending';
		this.setAttribute('direction','ascending');
		this.direction = 'ascending';
	}
	
	var tableObj = this.parentNode.parentNode.parentNode;
	var tBody = tableObj.getElementsByTagName('TBODY')[0];
	
	var widgetIndex = tableObj.getAttribute('tableIndex');
	if(!widgetIndex)widgetIndex = tableObj.tableIndex;
	
	if(currentColumn)currentColumn.className='';
	document.getElementById('col' + widgetIndex + '_' + (indexThis+1)).className='earmark_selected_column';
	currentColumn = document.getElementById('col' + widgetIndex + '_' + (indexThis+1));

		
	var sortMethod = tableWidget_arraySort[widgetIndex][indexThis]; // N = numeric, S = String
	if(activeColumn[widgetIndex] && activeColumn[widgetIndex]!=this){
		if(activeColumn[widgetIndex])activeColumn[widgetIndex].removeAttribute('direction');			
	}

	activeColumn[widgetIndex] = this;
	
	var cellArray = new Array();
	var cellObjArray = new Array();
	for(var no=1;no<tableObj.rows.length;no++){
		var content= tableObj.rows[no].cells[indexThis].innerHTML+'';
		cellArray.push(content);
		cellObjArray.push(tableObj.rows[no].cells[indexThis]);
	}
	
	if(sortMethod=='N'){
		cellArray = cellArray.sort(sortNumeric);
	}else{
		cellArray = cellArray.sort(sortString);
	}
	
	if(direction=='descending'){
		for(var no=cellArray.length;no>=0;no--){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');	
					tBody.appendChild(cellObjArray[no2].parentNode);				
				}				
			}			
		}
	}else{
		for(var no=0;no<cellArray.length;no++){
			for(var no2=0;no2<cellObjArray.length;no2++){
				if(cellObjArray[no2].innerHTML == cellArray[no] && !cellObjArray[no2].getAttribute('allreadySorted')){
					cellObjArray[no2].setAttribute('allreadySorted','1');	
					tBody.appendChild(cellObjArray[no2].parentNode);				
				}				
			}			
		}				
	}
	
	for(var no2=0;no2<cellObjArray.length;no2++){
		cellObjArray[no2].removeAttribute('allreadySorted');		
	}

	tableWidget_okToSort = true;
	
	
}
function initSortTable(objId,sortArray)
{
	var obj = document.getElementById(objId);
	obj.setAttribute('tableIndex',tableWidget_tableCounter);
	obj.tableIndex = tableWidget_tableCounter;
	tableWidget_arraySort[tableWidget_tableCounter] = sortArray;
	var tHead = obj.getElementsByTagName('THEAD')[0];
	var cells = tHead.getElementsByTagName('TD');
	for(var no=0;no<cells.length;no++){
		if(sortArray[no]){
			cells[no].onclick = sortTable;	
		}else{
			cells[no].style.cursor = 'default';	
		}
	}		
	for(var no2=0;no2<sortArray.length;no2++){	/* Right align numeric cells */
		if(sortArray[no2] && sortArray[no2]=='N')obj.rows[0].cells[no2].style.textAlign='right';
	}		
	
	tableWidget_tableCounter++;
}

function prefill_form(){
	qs2get();
	for( var key in $_GET ){
		var element = document.getElementById(key);
		if( element ) element.value = unescape($_GET[key].replace(/\+/g, " "));
	}
	//special case.  freaking radio buttons
	if( $_GET['search_type'] ) setCheckedValue(document.forms[0].search_type, $_GET['search_type']);
}

function qs2get(){
	$_GET = new Array;
	var $parameters = location.search.substring(1).split('&');
	for( var $i = 0; $i < $parameters.length; $i++ ) {
		var $pos = $parameters[$i].indexOf('=');
		if ($pos > 0){
			var $key = unescape($parameters[$i].substring(0,$pos));
			var $value = unescape($parameters[$i].substring($pos+1));
			$_GET[$key] = $value;
		}
	}
}

function validate_search_form(){
	fields = new Array('lawmaker_id', 'lawmaker_state', 'lawmaker_affiliation', 'lawmaker_chamber', 'beneficiary_name', 'beneficiary_city', 'beneficiary_state', 'earmark_title', 'earmark_category', 'earmark_heading', 'earmark_service', 'earmark_description', 'earmark_budget', 'earmark_house', 'earmark_senate', 'earmark_conference');
	var empty = true;
	for( var field in fields ){
		if( document.getElementById(fields[field]).value.length > 0 && document.getElementById(fields[field]).value != 'any' ) empty = false;
	}
	if( empty ){
		alert('You must specify at least one search parameter.');
		return false;
	}
	else return true;
}

function validate_beneficiary_name_search_form(){
	var fieldElement = document.getElementById('beneficiary_name');
	if( fieldElement ){
		if( fieldElement.value.length == 0 ) return false;
	}
	return true;
}

/*
 * Copyright 2005 Matthew Eernisse (mde@fleegix.org)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Original code by Matthew Eernisse (mde@fleegix.org), March 2005
 * Additional bugfixes by Mark Pruett (mark.pruett@comcast.net), 12th July 2005
 * Multi-select added by Craig Anderson (craig@sitepoint.com), 24th August 2006
 *
 * Version 1.3
*/

/**
 * Serializes the data from all the inputs in a Web form
 * into a query-string style string.
 * @param docForm -- Reference to a DOM node of the form element
 * @param formatOpts -- JS object of options for how to format
 * the return string. Supported options:
 *    collapseMulti: (Boolean) take values from elements that
 *    can return multiple values (multi-select, checkbox groups)
 *    and collapse into a single, comman-delimited value
 *    (e.g., thisVar=asdf,qwer,zxcv)
 * @returns query-string style String of variable-value pairs
 */
function formData2QueryString(docForm, formatOpts) {
  
  var opts = formatOpts || {};
  var str = '';
  var formElem;
  var lastElemName = '';
  
  for (i = 0; i < docForm.elements.length; i++) {
    formElem = docForm.elements[i];
    
    switch (formElem.type) {
      // Text fields, hidden form elements
      case 'text':
      case 'hidden':
      case 'password':
      case 'textarea':
      case 'select-one':
        str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        break;
        
      // Multi-option select
      case 'select-multiple':
        var isSet = false;
        for(var j = 0; j < formElem.options.length; j++) {
          var currOpt = formElem.options[j];
          if(currOpt.selected) {
            if (opts.collapseMulti) {
              if (isSet) {
                str += ',' + encodeURI(currOpt.value);
              }
              else {
                str += formElem.name + '=' + encodeURI(currOpt.value);
                isSet = true;
              }
            }
            else {
              str += formElem.name + '=' + encodeURI(currOpt.value) + '&';
            }
          }
        }
        if (opts.collapseMulti) {
          str += '&';
        }
        break;
      
      // Radio buttons
      case 'radio':
        if (formElem.checked) {
          str += formElem.name + '=' + encodeURI(formElem.value) + '&'
        }
        break;
        
      // Checkboxes
      case 'checkbox':
        if (formElem.checked) {
          // Collapse multi-select into comma-separated list
          if (opts.collapseMulti && (formElem.name == lastElemName)) {
            // Strip of end ampersand if there is one
            if (str.lastIndexOf('&') == str.length-1) {
              str = str.substr(0, str.length - 1);
            }
            // Append value as comma-delimited string
            str += ',' + encodeURI(formElem.value);
          }
          else {
            str += formElem.name + '=' + encodeURI(formElem.value);
          }
          str += '&';
          lastElemName = formElem.name;
        }
        break;
        
    }
  }
  // Remove trailing separator
  str = str.substr(0, str.length - 1);
  return str;
}

//RPC grabs an external js file (which is really a dynamic page) and loads it
//into the head
function RPC(url){
	var scriptObj = document.createElement("script");
	scriptObj.setAttribute("type", "text/javascript");
	scriptObj.setAttribute("charset", "utf-8");
	scriptObj.setAttribute("src", url);
	document.getElementsByTagName("head").item(0).appendChild(scriptObj);	
}

function get_search_results_count(){
	if( window.navigator.userAgent.indexOf("MSIE") == -1 ){
		document.getElementById('earmark_search_submit').textContent = '';
	} else {
		document.getElementById('earmark_search_submit').innerText = 'Search';
	}
	
	var queryString = formData2QueryString( document.getElementById('earmark_search') );
	RPC('/favorfactory/favorfactory_2008/include/get_search_results_count.php?' + queryString);
}

function go_to_lawmaker(lawmakerId){
	if( lawmakerId ){
		location.href = '/favorfactory/favorfactory_2008/lawmaker.php?id=' + lawmakerId;
	}
}

function browse_lawmakers_by_state(element){
	if( element.value.length > 0 ){
		location.href = '/favorfactory/favorfactory_2008/searchresults.php?search_type=lawmaker&start=0&limit=20&order_by=lawmaker_name&order_by_direction=ASC&lawmaker_state=' + element.value;
	}
}

function browse_beneficiaries_by_state(element){
	if( element.value.length > 0 ){
		location.href = '/favorfactory/favorfactory_2008/searchresults.php?search_type=beneficiary&start=0&limit=20&order_by=beneficiary_name&order_by_direction=ASC&beneficiary_state=' + element.value;
	}
}

function toggle_long_earmark_type(){
	var truncatedDiv = document.getElementById('earmark_page_type_truncated');
	var fullDiv = document.getElementById('earmark_page_type_full');
	var toggleLink = document.getElementById('earmark_page_type_toggle_link');
	if( fullDiv && truncatedDiv && toggleLink ){
		if( fullDiv.style.display != 'block' ){
			fullDiv.style.display = 'block';
			truncatedDiv.style.display = 'none';
			toggleLink.innerHTML = 'Show partial description';
		}else{
			fullDiv.style.display = 'none';
			truncatedDiv.style.display = 'block';
			toggleLink.innerHTML = 'Show full description';
		}
	}
}