// debug alerts through # 7

var pepsurf_url_base = "http://pepitope.tau.ac.il";
var pepsurf_url_results = pepsurf_url_base + "/results/";

// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
// DESIGN NOTES:

// ALL ARRAYS' first occupied position is 1, not 0.
//		(except for rare ones generated with .split())

// Defined here:

//		EVERY script calls make_label_pepsurf_alignments_spt()
//			in s2j() in top.js

//		Radio buttons call toggle_pepsurf_show_alignment(alignment_index);

//		Center & list links call center_cluster(cluster_index);

// Defined in cs_key.js:

//		Checkboxes call ps_key(cluster_index);

// Note that centering is done smoothly with a zoomTo command, not a
// center command.

// = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =

var pepsurf_cluster_count;

var pepsurf_peptide_count; // in PDB file (?) but NOT used
var pepsurf_peptide = new Array();

var pepsurf_alignment_count = 0;
var pepsurf_alignment_cluster = new Array();
var pepsurf_alignment_peptide = new Array();
var pepsurf_alignment_path = new Array();
var pepsurf_alignment_list = new Array();

var pepsurf_alignment_shown = -1; // first alignment is 1. Value 0 unused.
var pepsurf_cluster_zoomed = false;

var translucentMode = false;

var currently_centered_cluster = 0; // no cluster centered

var all_in_cluster = true;
var any_mismatch = false;
var any_nomatch = false;

var color_white = "ffffff";
var color_mismatch = "ffff00";
var color_no_match = "ffc0ff";
var color_not_in_cluster = "ffb0b0";

//var pepsurf_cluster_echo_spt = "";

//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function setup_pepsurf()
{
	// initialize consurf variables used by pepsurf code
	consurf_pdb_id = pepsurf_pdb_id;
	consurf_chain = pepsurf_chains;
	if (typeof(pepsurf_identical_chains) != "undefined")
		consurf_identical_chains = pepsurf_identical_chains;
	else
		consurf_identical_chains = "";
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function make_peptide_checklist(clustn)
{
	var ipa, pepn;
	var pph = "";
	var firsthit = false;

	// for each peptide aligned to clustn
	for (ipa = 1; ipa <= pepsurf_alignment_count; ipa++)
	{
		if (pepsurf_alignment_cluster[ipa] == clustn)
		{
			var ck = "";
			if (pepsurf_alignment_shown == ipa)
				ck = " checked";

			if (firsthit)
				pph += "<br>\n";

			pph += "&nbsp; &nbsp;\n";

			pph += "<input type='radio' name='alignlabel' value=" + ipa + 
"\n onClick='toggle_pepsurf_show_alignment()'" +
ck + ">\n";

			pepn = pepsurf_alignment_peptide[ipa];
			pph += pepn + ". " + "<tt><big><b>" +
				pepsurf_peptide[pepn] + "</b></big></tt>";

			firsthit = true;
		}
	}

	return pph;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// called by PDB file header lines.
// sets up arrays with pepsurf alignments.
function pepsurf_record_alignment(clusn, peptn, path, list)
{
	var ipa = pepsurf_alignment_count + 1;
	pepsurf_alignment_count++;

	pepsurf_alignment_cluster[ipa] = clusn;
	pepsurf_alignment_peptide[ipa] = peptn;
	pepsurf_alignment_path[ipa] = path;
	pepsurf_alignment_list[ipa] = list;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function toggle_pepsurf_show_alignment()
{
//	alert("pepsurf.js #1: currentView = " + currentView +
//		"\n pepsurf_alignment_shown = " +
//		pepsurf_alignment_shown);

		var radval = parseInt(getRadioValue(document.cgrades.alignlabel));

		pepsurf_alignment_shown = radval;

		var spt = "";

		if (radval == -1)
		{
			// turn off "reveal"
			translucentMode = false;
// help will be redisplayed, obeying translucentMode, so this is unnecessary:
//			document.cgrades.togtrans.checked = false;

				spt += make_cluster_echo_spt(0); // 0 means hide cluster echo
				currently_centered_cluster = 0;
		}

		spt += make_alignment_echo_spt(radval);

		if (radval != -1)
		{
			var cnum = pepsurf_alignment_cluster[radval];
			spt += "@spt select_cluster" + cnum + "\n" +
				"define ~pepsurf_cluster selected\n";
		}
		expand_spts(spt);
		spt = spt_expanded;

//		do_spt(spt); // spt = echo only; labels done by s2j
		reDisplay(spt, "");
		showHelp("makeConsurfHelp()"); // refresh checkboxes
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// called by s2j()
function make_label_pepsurf_alignments_spt()
{
	var spt = make_label_pepsurf_alignment_spt(pepsurf_alignment_shown);
	// above function guarantees correct cluster echo

	expand_spts(spt);
	spt = spt_expanded;

//	alert("pepsurf.js #3:\n" + spt);
	return spt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// called by make_label_pepsurf_alignments_spt() [s2j]
function make_label_pepsurf_alignment_spt(iap)
{
	var spt =
"select ~cluster1,~cluster2,~cluster3\n\
labels off\n\
color labels white\n\
font label 15 monospaced bold\n\
";

	if (cssf_grade[pepsurf_alignment_cluster[iap]]
		&& !translucentMode)
		spt += "set labelGroup\n"; // label in front of all atoms in group
	else
		spt += "set labelAtom\n"; // label in front of labeled atom only

	spt += make_label_alignment_path(iap); // guarantees correct cluster list

// For reasons unclear, when Jmol was updated to 11.3.11, the labels
// appeared about 5 spacefill atom diameters to the right of the atoms.
// I could not duplicate this in a simple example (see jmol/tests/labels).
// But it could be worked around by applying the "labeloffset 0 0" AFTER
// the labels were written. So the lines below (formerly in the initial
// block above) were simply moved to here.

	spt +=
"select ~cluster1,~cluster2,~cluster3\n\
set labeloffset 0 0\n\
set labelalignment left\n\
";

// labelalignment defaults to center; left avoids the number labels
// being hidden by large backbones, where one does want labelAtom.

	return spt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// called by make_label_pepsurf_alignment_spt(iap)
function make_label_alignment_path(iap)
{
	if (iap == -1) // no alignment selected
	{
		return "";
	}

	// ELSE

	var apath = new Array();
	apath = pepsurf_alignment_path[iap].split(",");

	var cnum = pepsurf_alignment_cluster[iap];
	var spt = "@spt select_cluster" + cnum + "\n" +
		"define ~pepsurf_cluster selected\n";

	if (currently_centered_cluster != cnum)
		spt += zoomto_cluster();
	currently_centered_cluster = cnum;

	// GUARANTEE CORRECT CLUSTER ECHO
	spt += make_cluster_echo_spt(cnum);

	// label each alpha carbon in the alignment path
	// use of .split() forces use of 0th array member!
	var ipath;
	for (ipath = 0; ipath < apath.length; ipath++)
	{
		if (apath[ipath] == "")
			continue;
		spt += "select " + apath[ipath] + " and *.ca\n" + // ".ca\n" +
			"label " + (ipath + 1) + "\n";
	}

	return spt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function make_alignment_echo_spt(iap)
{
	var alist, iaa, acnt;
	var spt = "";
	var sptend = "";
	var yup_start = 35;
	var yup = yup_start;
	var ydel = 18;
	var horiz = "70%";

 // BLANK ALIGNMENT ECHO
	var ibl;

	// max peptide is 15 + 2 lines at top, + 4 lines at bottom.
	for (ibl = 0; ibl <= 20; ibl++)
	{
		spt += echoAt(ibl, horiz, yup, color_white, "");
		yup += ydel;
	}
	if (iap == -1)
	{
		return spt;		
	}
	yup = yup_start;

	// ELSE (see return above)
	// MAKE ECHO

		alist = pepsurf_alignment_list[iap];
		aalist = alist.split(",");
		acnt = aalist.length;

		// leave room for color keys at bottom, 3 lines
		yup += 4 * ydel;

//		sptend += echoAt(0, horiz, yup, color_white, "    " + acnt + " AA.");
// changed and moved to below 

		var iaa;
		all_in_cluster = true;
		any_mismatch = false;
		any_nomatch = false;
		// when acnt is 15, iaa goes from 14 to 0, first param from 1 to 15.
		for (iaa = (acnt - 1); iaa >= 0; iaa--)
		{
			var eco = ecoColor(aalist[iaa]);
			yup += ydel;
			sptend += echoAt(acnt - iaa, horiz, yup, eco, aalist[iaa]);
		}

		yup += ydel;
		sptend += echoAt(acnt + 1, horiz, yup, color_white, "  Peptide " +
			 pepsurf_alignment_peptide[iap] + ":");
		yup += ydel;
		sptend += echoAt(acnt + 2, horiz, yup, color_white, " Alignment of");

	yup = yup_start + (4 * ydel);
	if (any_mismatch || !all_in_cluster || any_nomatch)
	{
		spt += echoAt(0, horiz, yup, color_white, "  -- Key --");
		yup -= ydel;
		spt += echoAt(acnt + 3, horiz, yup, color_white, "    Match.");
		yup -= ydel;
	}
	if (any_mismatch)
	{
		spt += echoAt(acnt + 4, horiz, yup, color_mismatch, "   Mismatch.");
		yup -= ydel;
	}
	if (any_nomatch)
	{
		spt += echoAt(acnt + 5, horiz, yup, color_no_match, "   No Match.");
		yup -= ydel;
	}
	if (!all_in_cluster)
	{
		spt += echoAt(acnt + 6, horiz, yup, color_not_in_cluster, "Not in Cluster.");
	}
	spt += sptend;

	return (spt);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function echoAt(cnt, horiz, vert, ecolor, msg)
{
	var ename = "peptidealignment" + cnt;
	var spt = "set echo " + ename + " " + horiz + " " + vert + "\n";
	spt +=
"set echo " + ename + " left\n\
font echo 16 monospaced bold\n\
color echo [x" + ecolor + "]\n\
echo \"" + msg + "\"\n\
";

	return spt;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function ecoColor(pepline) 
{
	var aa1, aa2;
	var eco = color_white;
	var ispace = pepline.indexOf(" ");
	var idash = pepline.indexOf("-");
	if (idash == -1)
	{
		eco = color_no_match;
		any_nomatch = true;		
	}
	else
	{
		aa1 = pepline.substring(ispace + 1, ispace + 4);
		aa2 = pepline.substring(idash + 1, idash + 4);
		if (aa1 != aa2)
		{
			eco = color_mismatch;
			any_mismatch = true;		
		}
	}

	if (notInCluster(pepline, pepsurf_alignment_shown)) 
	{
		eco = color_not_in_cluster;
		all_in_cluster = false;		
	}

	return eco;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function notInCluster(pepline, ialig)
{
	var idash = pepline.indexOf("-");
	var aa2;

	if (idash == -1)
		return false;

	aa2 = pepline.substring(idash + 1); // include chain if present

	var iaaclus = pepsurf_alignment_cluster[ialig];
	var aaclus = get_cluster_list(iaaclus);

//	alert("pepsurf.js #5:\n" + "|" + aa2 + "|" +
//		"\n ialig=" + ialig +
//		"\n iaaclus=" + iaaclus +
//		"\n aaclus=" + aaclus);

	if (aaclus.indexOf(aa2) == -1)
		return true;
	else return false;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function make_cluster_echo_spt(cnum)
{
	var locclist = "";

	if (cnum > 0)
	{
		locclist = get_cluster_list(cnum);
		var ccnt = locclist.split("|").length;

		locclist = "Cluster|  " + cnum + ":|" + locclist + "| " + ccnt + " AA";
	}

	var echoColor = top.getEchoColor();

	var fontsize = 16;
	if (ccnt > 15)
		fontsize = 12;
	if (ccnt > 20)
		fontsize = 11;
	if (ccnt > 25)
		fontsize = 10;

	var spt =
"set echo clusterlist 0% 8%\n\
set echo clusterlist left\n\
font echo " + fontsize + " monospaced bold\n\
color echo " + echoColor + "\n\
echo \"" + locclist + "\"\n";

	return (spt);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function center_cluster(cnum)
{
//	alert("pepsurf.js #6: entering center_cluster(" + cnum + ") with\n" +
//		"currently_centered_cluster = " + currently_centered_cluster);

	if (currently_centered_cluster == cnum && pepsurf_alignment_count > 0)
	{
		alert("Cluster " + cnum + " is already centered and listed.")			
		return;
	}

	currently_centered_cluster = cnum;

	if (pepsurf_alignment_count > 0)
	{
		// if a radio button is centering another cluster, check the NONE radio button.
		var radval = parseInt(getRadioValue(document.cgrades.alignlabel));
//	alert("pepsurf.js #7: radval = " + radval);
		// if no button checked, radval is NaN
		if (radval != -1 && !isNaN(radval))
		{
			var radCluster = pepsurf_alignment_cluster[radval];
			if (radCluster != cnum)
			{
				document.cgrades.alignlabel[0].checked = true;
				toggle_pepsurf_show_alignment(); // in center_cluster(), to clear
			}
		}
		// centering a cluster lists it, so hide button goes unchecked
		document.cgrades.alignlabel[0].checked = false;
	}

	var spt = "";

	spt += make_cluster_echo_spt(cnum);

	spt += "@spt select_cluster" + cnum + "\n" +
		zoomto_cluster() +
		"define ~pepsurf_cluster selected\n";

//	alert("pepsurf.js #2:\n" + spt);

	do_spt(spt);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function get_cluster_list(cnum)
{
	expand_spts("@spt select_cluster" + cnum + "\n");
	var locclist2 = spt_expanded;

	// remove first line "#name ... and "select "
	var ifl = locclist2.indexOf("\n");
	locclist2 = locclist2.substring(ifl + 8); // 8 to skip leading "select "

	// remove "select selected or "
	locclist2 = locclist2.replace(/\nselect selected or /g, ", ");

	// replace ", " with "|"
	locclist2 = locclist2.replace(/\,\ /g, "|");

	// remove terminal (all) newlines
	locclist2 = locclist2.replace(/\n/g, "");

	return locclist2;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function toggle_translucent()
{
	if (pepsurf_alignment_shown == -1)
	{
//		document.cgrades.togtrans.checked = false;
		alert("Please select a peptide first.");
		return;
	}

	translucentMode = !translucentMode;

	reDisplay("", "");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
// Makes all pepsurf view changes, based on flag settings!
// Main reDisplay() function.
// But not the "reset" function, which is "view01".
// Reset guarantees everything (e.g. when coming from FG control panel).
// Assumes properties of the view that are in the PDB file header scripts,
// but are duplicated here (not taken from those scripts).
// 
// All colors are taken from the values in the PDB header.
function make_pepsurf_display_spt()
{
	var pvs = "";

// At this point, chain and cluster coloring are not varied, so they do not
// need to be recolored.
//
// Also, the chains not containing clusters are always gray backbone,
// changing only translucent/opaque, so they don't need to be re-rendered.
//
// Only the cluster-containing chains need to be re-rendered (but not
// re-colored).

	// CHAIN(S): BACKBONE, CARTOON, OR SPACEFILL?
	pvs +=
"select (protein or nucleic)\n\
wireframe off\n\
backbone off\n\
cartoon off\n\
spacefill off\n\
backbone 0.4\n\
";

	switch (consurf_chain_display_mode)
	{
		case "none":
			break;
		case "cartoon":
			pvs += "select ~pepsurf_chains\nbackbone off\ncartoon\n";
			break;
		case "all":
			pvs += "select ~pepsurf_chains\nspacefill\n";
			break;
		case "allall":
			pvs += "spacefill\n";
	}

	// CLUSTERS: BACKBONE OR SPACEFILL?
	var icc;
	for (icc = 1; icc <= pepsurf_cluster_count; icc++)
	{
		pvs += "@spt select_cluster" + icc + ";\n";
		
		if (cssf_grade[icc])
		{
			pvs += "spacefill;\n";
		}
		else
			pvs += "spacefill false;\n";
	}

	pvs += make_select_aligned_spt(); // defines ~pepsurf_aligned
	// which may include some residues NOT in the cluster!

	// TRANSLUCENT?
	if (translucentMode)
		pvs +=
"select not (~cluster1,~cluster2,~cluster3)\n\
color atoms translucent -1\n\
color backbone translucent -1\n\
select ~pepsurf_cluster or ~pepsurf_aligned\n\
spacefill off\n\
backbone off\n\
wireframe 0.4\n\
#color bonds translucent\n\
color atoms opaque\n\
select ~pepsurf_cluster and *.ca\n\
spacefill 1.0\n\
";

	else
		pvs += 
"select all\n\
color atoms opaque\n\
select ~pepsurf_cluster\n\
wireframe off\n\
";

	// SPACEFILL PATH ALPHA CARBONS
	if (pepsurf_alignment_shown != -1 && translucentMode)
	{
		// REMOVE EMPTY MEMBERS (",," -> ",")
		var apath = pepsurf_alignment_path[pepsurf_alignment_shown];
		// next "while" added in FGiJ 1.38 
		while(apath.indexOf(",,") != -1) // to handle ",,," and possibly ",,,,"
			apath = apath.replace(/\,\,/g, ",");
		
		pvs += "select (" + apath +	") and *.ca\n" +
			"spacefill\n";
	}

	pvs = "# BEGIN make_pepsurf_display_spt()\n" + pvs +
		"# END make_pepsurf_display_spt()\n";

	expand_spts(pvs);
	pvs = spt_expanded;

	return pvs;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function zoomto_cluster()
{
	var zval = "300";
	if (pepsurf_cluster_zoomed)
		zval = "+0";

	pepsurf_cluster_zoomed = true;

	return ("zoomTo (selected) " + zval + "\n");
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function make_select_aligned_spt()
{
	var sas = "";

	if (pepsurf_alignment_shown != -1)
	{
		sas = pepsurf_alignment_path[pepsurf_alignment_shown];
		while (sas.indexOf(",,") != -1)
			sas = sas.replace(/,,/g, ",");
		sas = "select " + sas + "\n";
		sas += "define ~pepsurf_aligned selected\n";
	}

	return sas;
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
function hide_cluster_list()
{
	var spt = make_cluster_echo_spt(0);
	do_spt(spt);
}
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 
//- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 

