window.addEvent('load', function(){
// to visually show the status of the job request
var contextMorph = new Fx.Morph('info', {duration: 100, transition: Fx.Transitions.linear});

// the information that will be filled in by the demo button goes here:
var predefined_motifs = {
    '1ADY':{
    'pdbid' : '1ADY',
    'chainid' :  'A',
    'epsilon': '7',
	'backgrounddb': 'nrpdb',
    'points' : [
      {'resid':'81','alt':['D','E']},
      {'resid':'83','alt':['T']},
      {'resid':'112','alt':['R','S']},
      {'resid':'130','alt':['D','E']},
      {'resid':'264','alt':['L','Y']},
      {'resid':'311','alt':['K','N','Q','R']}
               ]
    },
    '1DWW':{
    'pdbid' : '1DWW',
    'chainid' :  'A',
    'epsilon': '7',
	'backgrounddb': 'nrpdb',
    'points' : [
      {'resid':'194','alt':['C']},
      {'resid':'346','alt':['V']},
      {'resid':'366','alt':['W']},
      {'resid':'367','alt':['F','Y']},
      {'resid':'371','alt':['E']},
      {'resid':'376','alt':['D','N']}
               ]
    },
    '7MHT':{
    'pdbid' : '7MHT',
    'chainid' :  'A',
    'epsilon': '7',
	'backgrounddb': 'nrpdb',
    'points' : [
      {'resid':'80','alt':['P']},
      {'resid':'81','alt':['C']},
      {'resid':'85','alt':['S','T']},
      {'resid':'119','alt':['E','L']},
      {'resid':'163','alt':['R']},
      {'resid':'165','alt':['R']},
               ]
    },
    '1JG1':{
	'pdbid': '1JG1',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'97','alt':['D','E','N','Q']},
{'resid':'99','alt':['G']},
{'resid':'101','alt':['A','G','L']},
{'resid':'160','alt':['D','N','S']},
{'resid':'179','alt':['I','L','V']},
{'resid':'183','alt':['E','G','N']}
		   ]
    },
    '1KPG':{
	'pdbid': '1KPG',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'17','alt':['D']},
{'resid':'72','alt':['G']},
{'resid':'74','alt':['G']},
{'resid':'75','alt':['W']},
{'resid':'76','alt':['G']},
{'resid':'200','alt':['F']}
		   ]
    },
    '1UCN':{
	'pdbid': '1UCN',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'12','alt':['K']},
{'resid':'13','alt':['P']},
{'resid':'92','alt':['G']},
{'resid':'105','alt':['R']},
{'resid':'115','alt':['N']},
{'resid':'118','alt':['G']}
		   ]
    },
    '1ANI':{
	'pdbid': '1ANI',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'51','alt':['A','D']},
{'resid':'101','alt':['D','E']},
{'resid':'102','alt':['S']},
{'resid':'166','alt':['C','R','S']},
{'resid':'331','alt':['G','H']},
{'resid':'412','alt':['H','N','Q']}
		   ]
    },
    '1CZF':{
	'pdbid': '1CZF',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'178','alt':['N']},
{'resid':'180','alt':['D']},
{'resid':'201','alt':['D']},
{'resid':'256','alt':['H','R']},
{'resid':'258','alt':['K']},
{'resid':'291','alt':['Y']}
		   ]
    },
    '8TLN':{
	'pdbid': '8TLN',
	'chainid': 'E',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'120','alt':['L','M','W']},
{'resid':'143','alt':['A','E']},
{'resid':'144','alt':['I','L','V']},
{'resid':'157','alt':['L','S','Y']},
{'resid':'231','alt':['H','L']},
		   ]
    },
    '1LBF':{
	'pdbid': '1LBF',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'51','alt':['E']},
{'resid':'56','alt':['S']},
{'resid':'57','alt':['P']},
{'resid':'89','alt':['F']},
{'resid':'91','alt':['G']},
{'resid':'112','alt':['F']},
{'resid':'159','alt':['E']},
{'resid':'180','alt':['N']},
{'resid':'211','alt':['S']},
{'resid':'233','alt':['G']}
		   ]
    },
    '1AYL':{
	'pdbid': '1AYL',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'249','alt':['L']},
{'resid':'250','alt':['S']},
{'resid':'251','alt':['G']},
{'resid':'253','alt':['G']},
{'resid':'254','alt':['K']},
{'resid':'255','alt':['T']}
		   ]
    },
    '2AHJ':{
	'pdbid': '2AHJ',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'53','alt':['P']},
{'resid':'120','alt':['L']},
{'resid':'127','alt':['Y']},
{'resid':'190','alt':['V']},
{'resid':'193','alt':['D']},
{'resid':'196','alt':['I']}
		   ]
    },
    '2AHJ':{
	'pdbid': '2AHJ',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'53','alt':['P']},
{'resid':'120','alt':['L']},
{'resid':'127','alt':['Y']},
{'resid':'190','alt':['V']},
{'resid':'193','alt':['D']},
{'resid':'196','alt':['I']}
		   ]
    },
    '1EP0':{
	'pdbid': '1EP0',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'53','alt':['A','S','T']},
{'resid':'61','alt':['A','R']},
{'resid':'64','alt':['H']},
{'resid':'73','alt':['K']},
{'resid':'90','alt':['R']},
{'resid':'172','alt':['D']}
		   ]
    },
    '1DID':{
	'pdbid': '1DID',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'25','alt':['F']},
{'resid':'53','alt':['H']},
{'resid':'56','alt':['D']},
{'resid':'93','alt':['F']},
{'resid':'136','alt':['W']},
{'resid':'182','alt':['K']}
		   ]
    },
    '1GGM':{
	'pdbid': '1GGM',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'188','alt':['E','T']},
{'resid':'311','alt':['L','R']},
{'resid':'239','alt':['E','T']},
{'resid':'241','alt':['E']},
{'resid':'359','alt':['E','S']},
{'resid':'361','alt':['A','S']}
		   ]
    },
    '1B7Y':{
	'pdbid': '1B7Y',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'149','alt':['A','G','W']},
{'resid':'178','alt':['H','Q']},
{'resid':'180','alt':['S','T']},
{'resid':'206','alt':['D','E','R']},
{'resid':'218','alt':['Q']},
{'resid':'258','alt':['F','N','Y']},
{'resid':'260','alt':['F','Y']}
		   ]
    },
    '1KP3':{
	'pdbid': '1KP3',
	'chainid': 'A',
	'epsilon': '7',
	'backgrounddb': 'nrpdb',
	'points': [
{'resid':'106','alt':['R']},
{'resid':'139','alt':['F']},
{'resid':'202','alt':['E','S']},
{'resid':'286','alt':['K']},
{'resid':'288','alt':['R']},
{'resid':'331','alt':['Y']}
		   ]
    }
}
// var logger = new Log; logger.enableLog(); // logger.log('logging enabled...');

var motif_selector = {
    element: $('motif_select'),
    init: function(){
	this.element.addEvent('change',function(event){
		event = new Event(event)
		event.stopPropagation()
		//alert()
	    })
	this.element.addEvent('blur',function(event){
		// call same function as change
		//alert(motif_selector)
	    })
	//this.element.addEvent('click',function(event){alert('click')})
	return this
    }
}.init()


// fetch alt aa checkbox and check it
var checkAlternate = function(motif_point_row,alt_aa){
    // motif_point_row.getElement('input[value='+alt_aa+']').setProperty('checked','true')
    var el = motif_point_row.getElement('.alt_aas')
    el.set('html', el.get('html') + alt_aa)
}

var uncheckAllAlternates = function(){
    $$('#motif_table > tr').each(function(el){ el.getElement('.alt_aas').set('html','')})
    //     alert('TODO: update clear alts'); return;
    //     $('motif_table').getElements('.motifPoint').each(function(row){
    //     row.getElements('input[type=checkbox]').each(function(check_box){
    //      check_box.setProperty('checked','')
    //  })
    // })
}
var clearMotifForm = function(){
    // get all <input type=text> elements and clear them
    $('motif_form').getElements('input[type=text]').each(function(current_text_box){ 
	    current_text_box.value='' // clear the current text box
	})
    uncheckAllAlternates() // uncheck the text boxes
}


var clearAltAAsButton = {
    element: $('clear_alts_btn'),
    init: function(){
	this.element.addEvent('click',function(event){
		event = new Event(event)
		event.stopPropagation()
        uncheckAllAlternates() // uncheck the text boxes
	    })
	return this
    }
}.init()

var clearMotifFormButton = {
    element: $('clear_form_btn'),
    init: function(){
	this.element.addEvent('click',function(event){
		event = new Event(event)
		event.stopPropagation()
		clearMotifForm()
	    })
	return this
    }
}.init()

/**
    Populate all of the fields attributes of the form with the 
    given motif data.
**/
var populate_motif_form = function(motif_data){
    // logger.log('populating the form with the following motif data object: '); logger.log(motif_data);
    
	clearMotifForm() // clear the form
	
    $('pdbid').value = motif_data['pdbid'] // set the PDB ID
	$('chainid').value = motif_data['chainid'] // set the chain id
	// get the radio button with specified epsilon value and check it
	// this will break if there is no matching epsilon button for the specified value
	$('epsilon_selector').getElement('input[value='+motif_data['epsilon']+']').setProperty('checked','true')
	// get the radio button with specified backgrounddb value and check it
	// this will break if there is no matching backgrounddb button for the specified value
	$('backgrounddb_selector').getElement('input[value='+motif_data['backgrounddb']+']').setProperty('checked','true')
	var motif_point_rows = $('motif_table').getElements('.motifPoint')
	var point_index = 0
	motif_data['points'].each(function(current_point){
	    // make sure there are enough points in the form, add more if not
	    if(point_index == MotifPointsManager.current_num_points){
	        MotifPointsManager.add_point();
	        motif_point_rows = $('motif_table').getElements('.motifPoint');
	    }
		current_row = motif_point_rows[point_index]
		current_row.getElement('input[type=text]').value = current_point['resid']
		current_point['alt'].each(function(alt_aa){
			checkAlternate(current_row,alt_aa)
		    })
		point_index = point_index + 1
	});
	// remove any extra points from the form
	while(MotifPointsManager.current_num_points > point_index){
	    MotifPointsManager.remove_point();
	}
	$('motif_table').fireEvent('change');
}

// the demo button code
var demoButton = {
    element: $('run_demo_btn'),
    init: function(){
	this.element.addEvent('click', function(event){
		event = new Event(event);  
		event.stopPropagation();
		
		var demo_motif = predefined_motifs[motif_selector.element.value]
		populate_motif_form(demo_motif);
		
	});// end click event
	return this
    }
}.init();

// the submit button code for the form
var submitButton = {
	element: $('submitButton'), // reference to the button dom object
	init: function(){ // set up event listeners
//		this.element.addEvents({
		$('submitButton').addEvent(
			'click' , function(event){
				
				// catch the event and stop it from bubbling
				event = new Event(event);
				event.stopPropagation();

				$('status').empty().adopt(new Element('p',{}).set('text', 'Processing your request'));
				// grab all of the form data
				var formData = buildFormObject();
				var ajaxSubmit = buildSubmitAjaxRequest(formData);
                // logger.log(formData);
///				contextMorph.start({'background-color': ['#0099FF', '#FFFF66']});
				ajaxSubmit.send();
				// create ajax request and submit form
				
			}// end click event		
		);// end add event
		return this
	}// end init function
}.init();// end submit button and initialize



//contextMorph.start('failure');
/*
var radiusRadios = {
	all: $$('.radiusRadios'),
	selected : 3,
	init: function(){
		this.all.each(function(radio){
			radio.addEvent('click',function(event){
				event = new Event(event);
				event.stopPropagation();
				this.selected = radio.value;
			});
		});
		return this
	}
}.init();
*/

var radiusRadios = {
	all: $$('.radiusRadios'),
	get: function(){
		var selected = null;
		this.all.each(function(radio){
			if(radio.checked == true){
				selected =  radio.value;
			}
		});
		return selected;
	}
}
var backgrounddbRadios = {
	all: $$('.backgrounddbRadios'),
	get: function(){
		var single_target_structure = $('single_target_id').value;
		var selected = null;
		this.all.each(function(radio){
			if(radio.checked == true){
				selected =  radio.value;
				// append the name of the single target pdbid to the value
    			if(radio.get('value') == "single"){
    			    selected += "_" + single_target_structure;
    			}
			}
		});
		return selected;
	}
}

/* Select the single structure radio if the correspondin text box is selected */
$('single_target_id').addEvent('focus', function(e){
    backgrounddbRadios.all.each(function(radio){
        if (radio.get('value') == "single"){
            radio.checked = true;
        }
    });
});

/* Clear the single structure text box if any other radio is selected */
backgrounddbRadios.all.each(function(radio){
    radio.addEvent('click', function(e){
        if (radio.get('value') !== "single"){
            $('single_target_id').set('value', '');
        }
    });
});

var motifPointRows = {
    // all: $$('.motifPoint'),
	get: function(){
		var motifPoints = [];
		$$('#motif_table .motifPoint').each(function(row){
			motifPoints.push(buildMotifPoint(row));
		});
		return motifPoints;
	}
};


// grabs all of the checked alternates and puts them in an array
var buildMotifPoint = function(motifPointRow){
	// get the child nodes
	var children = motifPointRow.getChildren();

	var motifPoint = {resid : null, alt: [] };
	var counter = 0;
	children.each(function(child){
		//if ==0 do nothing, this is the label
		if(counter == 1){ // this is the resid	
			motifPoint.resid = child.getFirst().value;
		}
		if(counter == 2){
		    motifPoint.alt = child.get('html').split('');
		}
        // if(counter > 1){// this is an alternate amino acid
        //  if(child.getFirst().checked == true){
        //      //alert(child.getFirst().value + " checked!");
        //      motifPoint.alt.push(child.getFirst().value);
        //  }
        // }
		counter++;
	});
	return motifPoint;
}

// grab all of the form data and stuff it into an object
var buildFormObject = function(){
	return {
		pdbid : $('pdbid').value, 
		chainid: $('chainid').value,
		radius: radiusRadios.get(),
		backgrounddb: backgrounddbRadios.get(),
		// now get the value of each motif point
		points: motifPointRows.get(),
		email: $('email').value
		};
}

// build an AJAX request object for submitting the form
var buildSubmitAjaxRequest = function(formData){
	var ajaxSubmit = new Request(
		{
		    url: 'php/submitJob.php',
			method: 'post',
			data: JSON.encode(formData),
			onComplete: function(request) {
				var status = request.split('\n');
				var response = 'Your job has been submitted';
				if (status[0]=='Error') {
					response = status[1];
					contextMorph.start({
						'background-color' : '#FBE3E4', 
						'color' : '#8a1f11', 
						'border-color' : '#FBC2C4'}
					);
				} else {
				    response = 'Your job has been submitted. Your results will appear here:<br><a href="' + status[2] + '">' + status[2] + '</a><br>You will receive an email when the results are ready.';
					contextMorph.start({
						'background-color' : '#E6EFC2',
						'color' : '#264409',
						'border-color' : '#C6D880'}
					);
				}
				$('status').empty().adopt(new Element('p',{}).set('html', response));
			},
			onFailure: function(){
				contextMorph.start({
					'background-color' : '#FBE3E4', 
					'color' : '#8a1f11', 
					'border-color' : '#FBC2C4'}
				);
				$('status').empty().adopt(new Element('p',{}).set('text', 'Failed to process your job submission'));
			}
		}
	);// end ajax object
	return ajaxSubmit;
}

// any form validation code goes here
var validate = function(){
	return true;
}


// Label Picker code
$('label_picker').hide(); // html for the label picker widget is hidden
/* Modal selection box for picking amino acid alternates.

    The modal selection box consumes the original page element 
    (clones the content i think) containing the markup.  Apply events 
    to this object, not the id = 'label_picker' element.
  
**/
var label_picker = new StickyWin.Modal({
  content: $('label_picker').get('html'),
  // relativeTo: $('motif_table'),
  // /*upper left corner of fxTarget */
  // position: 'upperLeft',
  // offset: {
  //   x: 0,
  //   y: -200
  // },
  modalOptions: {
    modalStyle:{
        // these options currently not taking any affect
      // 'background-color': '#d6e1b9',
      // 'opacity': 0.1
    }
  },
  zIndex: 10000, // TODO: the drop-down menus have some incredibly large z-index or something (they're always on top)
  className: 'modal', // this is the CSS class that controls all of the styling of the modal window
  showNow: false, // i.e., show when object is init'd
  useIframeShim: false
});

// $('bookmark_window').hide();
// bookmark_window = new StickyWin({
//   content: $('bookmark_window').get('html'),
//   // relativeTo: $('motif_table'),
//   /*upper left corner of fxTarget */
//   // position: 'upperLeft',
//   // offset: {
//   //   x: 0,
//   //   y: 200
//   // },
//   modalOptions: {
//     modalStyle:{
//         // these options currently not taking any affect
//       // 'background-color': '#d6e1b9',
//       // 'opacity': 0.1
//     }
//   },
//   zIndex: 9999, // TODO: the drop-down menus have some incredibly large z-index or something (they're always on top)
//   className: 'infowindow', // this is the CSS class that controls all of the styling of the modal window
//   showNow: false, // i.e., show when object is init'd
//   useIframeShim: false
// });

// bookmark_window = new StickyWin({
//   content: StickyWin.ui('the caption', 'this is the body', {
//     width: '400px',
//     buttons: [{
//       text: 'okey-dokey', 
//       onClick: function(){alert('ok!')}
//     }]
//   })
// });

/**  Creates a new edit button that will be tied to the given motif point.
    
    params:
        alts_aas_el = the element containing all of the motif point alternate AAs html
    
    returns:
        btn = a new button element for editting the given alternate AAs element
**/
var edit_button_factory = function(alt_aas_el){
    var btn = new Element('input', {
        type: 'button',
        name: 'edit_alts_btn',
        value: 'edit'
    });
    btn.addEvent('click', function(e){
        var event = new Event(e);
        event.stopPropagation();
        label_picker.show();
        labels = alt_aas_el.get('html').split(''); // split alternates string into individual letters
        labels.each(function(label){
           label_picker.element.getElement('input[value={label}]'.substitute({'label': label})).set('checked', true);
        });
        // callback function to transfer the label picker selections to the given motif point on the form
        label_picker.addEvent('close', apply_labels_factory(alt_aas_el, label_picker));
    });
    return btn;
};

/**Create and return an anoymous function that applies changes in labels to the
    given label picker.
    
    params:
        alt_aas_el = the alternate AAs element to which modifications should be written
        label_picker_obj = the modal window containing the alt aa label selections
    
    returns:
        function that applies the label selections to the given element
**/
var apply_labels_factory = function(alt_aas_el, label_picker_obj){
    /** Anonymous function to apply all of the label selections to the 
    form upon closing the window.  This function is meant to be attached
    as an event listener.
    
    params:
        e = the event that triggered this function
    **/
    return function(e){
        var labels = '';
        // gather all of the labels from the label picker
        label_picker_obj.element.getElements('input:checked').each(function(el){
            labels += el.get('value');
            el.set('checked', false); // clear the checkbox in the label picker
        });
        // overwrite previous label data with new labels
        alt_aas_el.set('html', labels);
        
        // logger.log('removing all close events from target window...');
        label_picker_obj.removeEvents('close');
        
        $('motif_table').fireEvent('change');
    }
};

var MotifPointsManager = {
    min_num_points: 3,
    max_num_points: 10,
    current_num_points: 0, // should be initialized
    el: $('motif_table'),
    init: function(){
        // logger.log('initializing motif point manager');
        for(var i = 0; i < this.min_num_points; i++){
            this.add_point();
            // logger.log('adding initial point number ' + i);
        }
        return this;
    },
    add_point: function(){
        if(this.current_num_points >= this.max_num_points){
            alert('Maximum of 10 points currently.');
            return;
        }
        this.current_num_points += 1;
        var row = new Element('tr', {
            'class': 'motifPoint' + (this.current_num_points % 2 ? '' : ' even'), 
            'id': 'motifPoint' + this.current_num_points
        });
        
        var label_cell = new Element('td', {'class': 'rightalign'});
        var label = new Element('label', {
            'for': 'resid' + this.current_num_points, 
            'html': this.current_num_points + ': '
        });
        label_cell.grab(label);
        
        var resid_cell = new Element('td');
        var resid = new Element('input', {
            'id': 'resid' + this.current_num_points, 
            'type': 'text', 
            'name': 'resid' + this.current_num_points, 
            'class': 'resid'
        });
        resid_cell.grab(resid);
        
        var edit_cell = new Element('td');
        var alts_cell = new Element('td', {'class': 'alt_aas'});
        edit_cell.grab(edit_button_factory(alts_cell));
        
        row.grab(label_cell); row.grab(resid_cell); row.grab(alts_cell); row.grab(edit_cell);
        this.el.grab(row);
        
        $('motif_table').fireEvent('change');
    },
    remove_point: function(){
        if(this.current_num_points <= this.min_num_points){
            alert('Minimum of 3 points required');
            return;
        }
        this.current_num_points -= 1;
        // delete the last row
        document.getElement('table > tr:last-child').destroy();
        
        $('motif_table').fireEvent('change');
    }
}.init();


/**
 Interface buttons for the motif point manager
**/
$('add_motif_point_btn').addEvent('click', function(e){
    MotifPointsManager.add_point();
});
$('remove_motif_point_btn').addEvent('click', function(e){
    MotifPointsManager.remove_point();
});

$('bookmarkButton').hide();
$('bookmarkButton').addEvent('click', function(e){
    // logger.log('updated the link href');

   var motif_data = buildFormObject(); // grab all of the form data
   delete motif_data.email; // remove the attribute
   motif_data.epsilon = motif_data.radius; // alias the value
   var json_motif_data = JSON.encode(motif_data);
   var bookmark = new URI(window.location);
   bookmark.clearData();
   bookmark.set('data', {motif: json_motif_data});

   var bookmark_url = $('bookmark_url');
   bookmark_url.set('href', bookmark.toString());
   bookmark_url.show();
});

var apply_bookmark = function(){
    var the_uri = new URI(window.location);
    var json_form_data = JSON.decode(the_uri.get('data').motif);
    if(json_form_data != null){
        // logger.log("populating form with bookmarked data...");
        populate_motif_form(json_form_data);
    }
}
// apply the bookmarked data if it is present
apply_bookmark();
$('bookmark_url').hide();


// hide the bookmark when a change occurs because it is no longer valid
$('motif_table').addEvent('change', function(e){
    $('bookmark_url').hide();
    $('bookmarkButton').fireEvent('click');
});


/**
    Add listeners for change events on the form to update the bookmark link
**/
document.getElements('#motif_form input[type=radio]').extend([$('pdbid'), $('chainid')]).each(function(el){ 
    el.addEvent('change', function(e){ 
        $('bookmarkButton').fireEvent('click');
        // logger.log('input data changed... regenerating link');
    });
});


/**
  Special label selection buttons.
**/

label_picker.element.getElement('ul[id=label_categories]').getElements('input').each(function(el){
    var labels = [];
    switch(el.get('name')){    
        case 'aromatic':
            labels = ['F', 'Y', 'W'];
            break;
        case 'aliphatic':
            labels = ['V', 'I', 'L', 'M', 'C', 'A'];
            break;
        case 'positive':
            labels = ['K', 'R', 'H'];
            break;
        case 'negative':
            labels = ['D', 'E'];
            break;
        // default:
            // logger.log('the ' + el.get('name') + ' label button has no label definition...');
    }
    el.addEvent('click', function(e){
        // logger.log('adding labels ' + labels.join(''));
        labels.each(function(label){
           label_picker.element.getElement('input[value={label}]'.substitute({'label': label})).set('checked', true);
        });
    });
    // logger.log('added event to the ' + el.get('name') + ' button');
});

label_picker.element.getElement('input[name=clear]').addEvent('click', function(e){
    label_picker.element.getElements('input[type=checkbox]').each(function(el){el.set('checked', false)});
});

// label_picker.element.getElement('input[name=ok]').addEvent('click', function(e){
//     label_picker.fireEvent('close');
// });

var advanced_options_Slide = new Fx.Slide('advanced_options');
var advanced_options_toggle_icon = $('advanced_options_toggle_icon');
advanced_options_Slide.hide();
advanced_options_toggle_icon.store('state', 'closed'); // 0 = closed, 1 = open
$('advanced_options_toggle').addEvent('click', function(e){
	e.stop();
	advanced_options_toggle_icon.store('state', advanced_options_toggle_icon.retrieve('state') == 'closed' ? 'open' : 'closed');
	// toggle the image src
    $('advanced_options_toggle_icon').set('src', 'images/menu-{state}-triangle.png'.substitute({'state': advanced_options_toggle_icon.retrieve('state')}));
    // logger.log(advanced_options_toggle_icon.get('src'));
	advanced_options_Slide.toggle();
});

});/// end window.onload()	


    



// window.addEvent('error', function(e){
//     logger.log('window.onerror()');
//     alert('window.onerror() was called');
//     printStackTrace(e);
// });
