var ODE = {};
(function() {
 _ODE=this;
 this.readOnly=false;

 this.redirect = function(url) {
	 window.location.href=url;
 };

 this.select_all = function(check, input_name, container) {
	 list = $(':input[name="'+input_name+'"]', container);
	 list.each( function(){this.checked=check;} );
	 return false;
 };

 this.toggle = function(selector) {
	 $(selector).each(function(){$(this).toggle();});
	 return false;
 };

 this.toggle_enabled = function(selector, en, andclear) {
	 $(selector).each(function(){ this.disabled=!en; if(!en && andclear) this.value=''; });
	 return false;
 };

 this.update_deprecated = function(project_id, gs_id) {
	 var url="index.php";
	 var params="ajax_req=analyze&cmd=fixdeprecated&pj_id="+project_id+"&gs_id="+gs_id;

	 pdiv = $('#project_'+project_id+'_deprecated');
	 if( pdiv && gs_id==0)
		 pdiv.hide();

	 if( $('#'+project_id+"TABLE") == null ) {
		 $('#'+project_id+"ahref").after('<div id="'+project_id+'TABLE"></div>');
	 }
   $('#'+project_id+'TABLE').load(url, params);
	 return false;
 };

 this.help_init = function() {
	 numhelps=0;
	 $('.content-help').each(function(){$(this).toggle();numhelps++;});
	 if( numhelps==0 ) $('content-meta-help').hide();
 };

 this.multi_action = function(inputsel) {
	 var act = inputsel.options[ inputsel.selectedIndex ].value;
	 inputsel.selectedIndex=0;
	 if( act=='' ) return;

	 var gs_ids='';
	 var gs_count=0;

	 var gsets = $('#my_genesets :input[name="gs_id[]"]').each(
		 function() {
		 if( this.checked ) {
			 if( gs_ids != "") gs_ids+=",";
			 gs_ids+=this.value;

			 gs_count++;
		 }
	 });

	 if( gs_count==0 ) {
		 return;
	 }

	 switch( act ) {
		 case 'del_checked':
			 if( confirm('Are you sure you wish to delete these '+gs_count+' GeneSets?') ){
				 this.redirect('index.php?action=manage&cmd=listgenesets&dellist='+gs_ids);
			 }
			 break;
		 case 'batch_edit':
			 this.redirect('index.php?action=manage&cmd=batcheditgeneset&gs_ids='+gs_ids);
			 break;
		 case 'change_owner':
			 new_email=prompt('Enter the email address of the user you want to give these '+gs_count+' GeneSets:');
			 if( new_email ) {
				 this.redirect('index.php?action=manage&cmd=listgenesets&change_owner='+escape(new_email)+'&gs_ids='+gs_ids);
			 }
			 break;
	 } 
 };

 this.save_pref = function(pref_var, value) {
	 $.get('index.php', 'ajax_req=analyze&cmd=save_prefs&'+pref_var+'='+value);
 };

 this.toggle_tool = function(tool,e) {
	 imgicon=$(e).children('img');
	 if(imgicon.attr('src').substr(-17) === "images/expand.png") 
		 imgicon.attr('src', "images/contract.png"); 
	 else imgicon.attr('src', "images/expand.png"); 
	 $('#tool_params-'+tool).toggle();
	 return false;
 };

 this.copy_field = function(start, from_id) {
	 var input=$(':input[name="'+start+'_'+from_id+'"]')[0];
	 inps = $('#batch_editor :input');

	 //TODO: doesn't work in IE
	 if( input.options ) {
		 for( n=0; n<inps.length; n++ ) {
			 if( inps[n].name.indexOf(start)==0 ) {
				 for( o in input.options )
					 inps[n].options[o].selected = input.options[o].selected;
			 }
		 }
	 } else {
		 var value=input.value;
		 for( n=0; n<inps.length; n++ ) {
			 if( inps[n].name.indexOf(start)==0 ) inps[n].value=value;
		 }
	 }
	 return false;
 };

 this.update_multigroup = function(sel) {
	 var gsel = $(sel).val() || [];
	 if( gsel.length==0 || $.inArray('-1', gsel)!=-1 ) gsel=['-1'];
	 if( $.inArray('0', gsel)!=-1 ) gsel=['0'];
	 $(sel).val(gsel);
	 $('#gs_groups').val(gsel.join(","));
	 return true;
 };

 this._add_to_project_complete = function (resp) {
   var sel = $('#projectAJAXDiv');

   htmltop='<select name="addToProject" onchange="return ODE.add_to_project(this);">';
   htmltop+='<option value="-1">Add Selected to Project...</option>';
   htmlbottom='</select>';

   sel.html(htmltop+resp+htmlbottom);

   // <!-- OK ## -->
   // <!-- DUPE ## OF ## -->
   // <!-- ERROR -->
   end=resp.indexOf("-->");
   if( end==-1 ) alert("An Error occurred.  Please try again.");
   else {
      msg = resp.substring(resp.indexOf("<!--")+5, end-1);
      if( msg=="ERROR" )
         alert("An Error occurred.  Please refresh the page and try again.");
      else if( msg.substring(0,5)=="DUPE " ) {
         ndupe=parseInt(msg.substring(5,msg.indexOf(" OF ")));
         total=parseInt(msg.substring(msg.indexOf(" OF ")+4));
         if( ndupe==total ) 
            alert("All "+total+" GeneSet(s) already exist in that Project.");
         else {
            sel_msg = "Successfully added "+(total-ndupe)+" GeneSet(s) to the Project '"+sel_project+"',\n";
            sel_msg+= "but "+ndupe+" GeneSet(s) were already in it.";
            alert(sel_msg);
            if( !window.event.shiftKey )
               window.location='index.php?action=analyze&project='+sel_project;
         }
      } else if( msg.substring(0,3)=="OK " ) {
         total=parseInt(msg.substring(3));
         alert("Successfully added "+total+" GeneSet(s) to Project '"+sel_project+"'.");
         if( !window.event.shiftKey )
            window.location='index.php?action=analyze&project='+sel_project;
      }
   }
}

 this.add_to_project = function(sel, container) {
   var url="index.php";
   var params="ajax_req=analyze&cmd=addToProject&name=";
   var gs_ids="";
   var sel_message="";
   var gs_count=0;
   var project_name = sel.options[ sel.selectedIndex ].value;
   if( project_name == -1 ) return false;

   $(':input[name="gs_id[]"]', container).each(function() {
			 if( this.checked ) {
				 if( gs_ids!="") gs_ids+=',';
				 gs_ids+=this.value;
				 gs_count++;
			 }
	 });

   if( gs_count==0 ) {
      alert("Please select GeneSet(s) to add first"); 
			sel.selectedIndex=0;
      return true;
   }

   if( project_name == -2 ) {
      var name = prompt("Enter a name for the new Project");
      if( name == null ) {
				 sel.selectedIndex=0;
         return true;
			}

      // create new project named 'name' with the form
      params+=name+"&gs_ids="+gs_ids;
      sel_message = gs_count+" GeneSets to new Project '"+name+"'";
      sel_project = name;
   } else {
      // add to project from form to
      params+=project_name+"&gs_ids="+gs_ids;
      sel_message = gs_count+" GeneSets to Project '"+project_name+"'";
      sel_project = project_name;
   }
   $('#projectAJAXDiv').load(url, params, this._add_to_project_complete );
	 sel.selectedIndex=0;
	 return true;
 };

 this.ode_share_pj_id=0;
 this.ode_share_group='';
 this._share_project_complete = function(resp) {
   var sel = $('#projectShareAJAXDiv');

   htmltop='Share with: <select name="shareWithGroup" onchange="return ODE.share_project('+ode_share_pj_id+', this);">';
   htmltop+='<option value="-1">Private</option><optgroup label="Groups">';
   htmlbottom='</optgroup></select><span id="shared_pj_saved" style="background-color: #ffff00; padding: 2px;">Saved!</span>';

   sel.html(htmltop+resp+htmlbottom);

	 if(ode_share_group!="") { 
		 if( !$('#'+ode_share_pj_id+'share').length )
			 $('#'+ode_share_pj_id+'ahref').append('<span id="'+ode_share_pj_id+'share" style="font-size: small; font-weight: normal;"></span>');
		 $('#'+ode_share_pj_id+'share').html( "(Shared With "+ode_share_group+")" );
	 } else {
		 $('#'+ode_share_pj_id+'share').remove();
	 }
	 $('#shared_pj_saved').fadeOut(1500);
 }
 this.share_project = function(pj_id, sel, container) {
   if( container == undefined ) container='listform';
   var grp_id = sel.options[ sel.selectedIndex ].value;
   var grp_name = grp_id==-1?"":sel.options[ sel.selectedIndex ].text;
   var url="index.php";
   var params="ajax_req=analyze&cmd=shareWithGroup&pj_id="+pj_id+"&grp_id="+grp_id;
   ode_share_pj_id=pj_id;
   ode_share_group=grp_name;

   $.get(url, params, this._share_project_complete );
 };

 this.remove_ontology = function(gs_id, ont_id, noblacklist) {
	 var url="index.php";
	 var params="action=manage&cmd=updategenesetontologies&gs_id="+gs_id+"&remove="+ont_id;
	 if( noblacklist ) params+='&noblack=yes';
	 $.get(url, params, function(resp){
		 $('#ont_'+ont_id).remove();
		 $('#ontology_list').append(resp);
	 });
	 return false;
 };
 
 this.add_ontology = function(gs_id, ont_id) {
	 var url="index.php";
	 var params="action=manage&cmd=updategenesetontologies&gs_id="+gs_id+"&add="+ont_id;
	 $.get(url, params, function(resp){
		 $('#ontology_adder').after(resp);
	 });
	 $('#add_ontology').val('');
	 return false;
 };
 
 this.confirm_ontology = function(gs_id, ont_id) {
	 var url="index.php";
	 var params="action=manage&cmd=updategenesetontologies&gs_id="+gs_id+"&add="+ont_id;
	 $.get(url, params, function(resp){
		 $('#ont_'+ont_id).replaceWith( resp ); 
	 });
	 return false;
 };

 this.upload = {
	 manual_pub: function() {
			 $('.pub_field').each(function(){$(this).show();});
			 $('#manual_pub_link').hide();
			 return false;
		 },
	 pastebox: function() {
			 this.pastewin = window.open("pastebox.php","ODE Upload: Pastebox", "menubar=no,width=430,height=360,toolbar=no" );
			 this.pastewin.pCallback = this.paste_callback;
			 this.pastewin.focus();
			 return false;
		 },
	 paste_callback: function(filename) {
			 ht  = '<input type="hidden" name="file" id="file" value="'+filename+'">';
			 ht += '<input type="text" style="width: auto;" disabled="disabled" value="Using Pasted File" />';
			 ht += '<input type="button" style="width: auto;" value="clear" onclick="$(\'#uploaderDiv\').html(\'<input type=file id=file name=file />\'); return false;" />';
			 $('#uploaderDiv').html(ht);
			 return false;
		 },
	 help: function(topic) {
			 this.helpwin = window.open("docs/gsedit_popup.html#"+wh,"ODE Help: Edit/Upload GeneSet", 
					 "menubar=no,width=430,height=360,toolbar=no,scrollbars=yes" );
			 this.helpwin.focus();
			 return false;
		 },
	 chk_groups: function (grps) {
		 var glist="";
		 // TODO: check works in IE
		 for(i=0; i<grps.length; i++) {
				if( grps[i].selected ) {
					 if( glist!="" ) glist+=',';
					 glist+=grps[i].value;
				}
		 }

		 // if nothing is selected, make it private
		 if( glist=="" ) glist=-1;

		 $('#gs_groups').val(glist);
	 },
	 chk_avail: function(radioBtn) {
		 if( radioBtn.value=="Group" ) {
				$('.groupsRow').each(function(){$(this).show();});
		 } else if( radioBtn.value=="Private" ) {
				$('#gs_groups').val('-1');
				$('.groupsRow').each(function(){$(this).hide();});
		 } else if( radioBtn.value=="Public" ) {
				$('#gs_groups').val('0');
				$('.groupsRow').each(function(){$(this).hide();});
		 }
	 },
	 validate: function() {
		 // check required fields
		 req="";
		 if( $('#gs_name').val() == '' ) req+="GeneSet Name is required.\n";
		 if( $('#gs_abbreviation').val() == '' ) req+="GeneSet Abbreviation is required.\n";
		 if( $('#gs_description').val() == '' ) req+="GeneSet Description is required.\n";
		 if( $("#file").val() == "" && $("#file_text").val() == "" ) req+="Input File is required.\n";
		 if( req=="" ) return true;

		 window.alert(req);
		 return false;
	 }
 };

 //////////////////
 this.analyze = {
	 validate: function() {
			 var have=0;
			 $(':input[name="projectIDList[]"]').each(function(){ if(this.checked) have++; });
			 if(have>0) return true;
			 $(':input[name="gs_id[]"]').each(function(){ if(this.checked) have++; });
			 if(have>1) return true;
			 alert('Please select at least one Project or two GeneSets.');
			 return false;
		 },
	 toggle_project: function(project_id) {
		 if( $('#'+project_id+"TABLE").length ) {
				if( $('#'+project_id+"ICON")[0].src.substr(-17)==="images/expand.png" ) {
					$('#'+project_id+"TABLE").show();
					$('#'+project_id+"ICON")[0].src="images/contract.png";
				} else {
					$('#'+project_id+"TABLE").hide();
					$('#'+project_id+"TABLE :input[name=\"gs_id[]\"]").disabled=true;
					$('#'+project_id+"ICON")[0].src="images/expand.png";
				}
		 } else {
			 // list needs loaded
				var url="index.php";
				var params="ajax_req=analyze&cmd=getgenesets&prjid="+project_id;
				if( _ODE.readOnly ) params+="&readonly=true";
				$('#'+project_id+"ahref").after('<div id="'+project_id+'TABLE"><img src="images/spinner.gif" /> Loading ...</div>');
				curSel=project_id;

				$('#'+project_id+'TABLE').load(url, params);
				$('#'+project_id+"ICON")[0].src="images/contract.png";
		 }
		 return false;
	 },
	 check_project: function(selID, whatchanged) {
		 var p_chk = $('#'+selID+"_chk")[0].checked;
		 if( whatchanged && whatchanged.name=='gs_id[]' ) {
				var chk = whatchanged.checked;
			  if(chk==false) {
					$('#'+selID+"_chk")[0].checked=false;
				} else {	
					not_all=0;
					$("#sel_"+selID+' :input[name="gs_id[]"]').each(function(){
						if( !this.checked ) not_all++;
					});
					if( !not_all )
						$('#'+selID+"_chk")[0].checked=true;
				}
		 } else if( $("#sel_"+selID).length ) {
			 $("#sel_"+selID+' :input[name="gs_id[]"]').each(function(){
				 this.checked=p_chk;
			 });
		 }
	 },
	 rename_project: function(project_id) {
		 var url="index.php";
		 var newName = window.prompt("Rename Project to:");
		 if( newName!="" && newName!=null ) {
				var params="ajax_req=analyze&cmd=renameProject&prjid="+project_id+"&to="+newName;
				$.get(url, params);
		 }
		 return false;
	 },
	 delete_project: function(project_id, project_name) {
		 if( confirm('Are you sure you wish to delete the entire Project "'+project_name+'"?') ) {
				var url="index.php";
				var params="ajax_req=analyze&cmd=deleteProject&prjid="+project_id;
				$('#'+project_id+"DEL").load(url,params);
		 }
	 },
	 remove_from_project: function(project_id, project_name, gs_list,x) {
		 var url="index.php";
		 var gs_ids=gs_list;
		 if( gs_list instanceof Array ) {
			 if( !confirm('Are you sure you wish to remove these '+gs_list.length+' GeneSet(s) from the Project "'+project_name+'"?') )
				 return false;
			 gs_ids="";
			 for( i=0; i<gs_list.length; i++) {
				 if( i!=0 ) gs_ids+=',';
				 gs_ids+=gs_list[i];
			 }
		 } 
		 var params="ajax_req=analyze&cmd=removeFromProject&prjid="+project_id+"&gs_id="+gs_ids;
		 $('#'+project_id+"TABLE").load(url,params);
		 return false;
	 },
	 remove_selected_from_project: function(project_id, project_name) {
		 var gs_list=[];
		 $('#'+project_id+'TABLE :input[name="gs_id[]"]').each(function(){
				 if( this.checked )
					 gs_list.push(this.value);
		 });
		 this.remove_from_project(project_id, project_name, gs_list);
	 }
 };

}).call(ODE);

