var MAXPDBS = 500000;
var MAXSEQS = 5000;
var waitWindow;

///////////////////////////////////////////////////////////
function Validate_Num(obj, lowboundary, highboundary)
///////////////////////////////////////////////////////////

{
   	if(parseFloat(obj.value) != obj.value || obj.value < lowboundary || obj.value > highboundary) {
      		alert ("Invalid value! " + obj.value + "   try value in the range of " + lowboundary + " ~ " + highboundary);
      		obj.focus();
      		obj.select();
      		return false;
   	}

   	return true;
}

///////////////////////////////////////////////////////////
function Check_Num(value, lowboundary, highboundary)
///////////////////////////////////////////////////////////

{
   	if(isNaN(value) || parseFloat(value) != value || value < lowboundary || value > highboundary) {
      		alert ("Invalid value! " + value + "   try value in the range of " + lowboundary + " ~ " + highboundary);
      		return -1;
   	}

   	return 1;
}

//////////////////////////////
function validEmail(email)
//////////////////////////////

{
	// define most common illegal characters in email
	var i;
	var badChar;
	var atPos, periodPos;
	var invalidChars = " /:,;'\"`"

	if (email.value == "") {
		alert ("Invalid email address! " + email.value);
		email.focus();
		email.select();
		return false;
	}

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (email.value.indexOf(badChar,0) > -1) {
			alert ("Invalid email address! " + email.value);
			email.focus();
			email.select();
			return false;
		}
	}

	// check existance of "@" and make sure only one exist
	atPos = email.value.indexOf("@",1)
	if (atPos == -1) {
		alert ("Invalid email address! " + email.value);
		email.focus();
		email.select();
		return false;
	}
	if (email.value.indexOf("@",atPos+1) > -1) {
		alert ("Invalid email address! " + email.value);
		email.focus();
		email.select();
		return false;
	}

	// check existance of "." and make sure there are at least two chars sfter it
	periodPos = email.value.indexOf(".",atPos)
	if (periodPos == -1) {
		alert ("Invalid email address! " + email.value);
		email.focus();
		email.select();
		return false;
	}
	if (periodPos+3 > email.length)	{
		alert ("Invalid email address! " + email.value);
		email.focus();
		email.select();
		return false;
	}

	return true
}

/////////////////////////
function round(x)
/////////////////////////

{
    	return Math.round(x*100)/100;
}

//////////////////////////////////////
function ChainCullSet(ChainCull)
//////////////////////////////////////

{
	var i;

	if (ChainCull.checked) {
		for (i=0; i<document.SetParams.CullChains.length; i++) {
			if (document.SetParams.CullChains[i].value == "No") {
				document.SetParams.CullChains[i].checked = true
			}
		}

		// document.SetParams.chain_id.disabled = true;
	}
}

/////////////////////////////
function ActiveMail(lnk)
/////////////////////////////

{
  	if (lnk.style) lnk = lnk.style;

  	lnk.color = "blue";
	lnk.style = "italic";
  	lnk.fontWeight = "bold";
}

///////////////////////////
function InactiveMail(lnk)
///////////////////////////

{
  	if (lnk.style) lnk = lnk.style;

  	lnk.color = "blue";
	lnk.style = "italic";
  	lnk.fontWeight = "normal";
}


/////////////////////////////
function HighlightLink(lnk)
/////////////////////////////

{
  	if (lnk.style) lnk = lnk.style;

  	lnk.color="red";
  	lnk.fontWeight="bold";
}

///////////////////////////
function NormalLink(lnk)
///////////////////////////

{
  	if (lnk.style) lnk = lnk.style;

  	lnk.color="yellow";
  	lnk.fontWeight="normal";
}

///////////////////////////////
function PopHelp(content)
///////////////////////////////

{
	helpwindow = window.open(content, 'help','width=400, height=200, scrollbars=yes');
	helpwindow.focus();

}


///////////////////////////////
function PopHelp(content)
///////////////////////////////

{
	helpwindow = window.open(content, 'help','width=400, height=200, scrollbars=yes');
	helpwindow.focus();

}

///////////////////////////////
function PopInfo(content)
///////////////////////////////

{
	infowindow = window.open(content, 'info','width=400, height=300, scrollbars=yes, resizable=yes');
	infowindow.focus();

}

///////////////////////////////
function VerifyFileName(file)
///////////////////////////////

{
	var i;
	var badChar;
	var invalidChars = ",;`"

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (file.value.indexOf(badChar,0) > -1) {
			alert ("Invalid file name! " + file.value);
			file.focus();
			file.select();
			return false;
		}
	}
}

///////////////////////////////
function PopError(Message)
///////////////////////////////

{
	errorwindow = window.open(Message, 'error','width=400, height=100, scrollbars=yes');
	errorwindow.focus();

}

////////////////////////////////
function CheckString(string)
////////////////////////////////

{
	var i;
	var invalidChars = "/:,;'\"`"
  	var badChar;

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (string.indexOf(badChar,0) > -1) return -1;
	}

	return 1;
}

////////////////////////////////
function ValidStrLen(string)
////////////////////////////////

{
	var i;
 	var validChars = "-_|.";
	var len = 0;
	var ThisChar;

	if(string.length == 0) return 0;

	for (i=0; i<string.length; i++) {
		ThisChar = string.charAt(i);
		if(validChars.indexOf(ThisChar,0) > -1)
			len ++;
		else if(ThisChar <= '9' && ThisChar >= '0')
			len ++;
		else if(ThisChar <= 'z' && ThisChar >= 'a')
			len ++;
		else if(ThisChar <= 'Z' && ThisChar >= 'A')
			len ++;

		if(len >= 4) break;
	}

	// alert ("char len " + len);

	return len;
}

////////////////////////////////
function GetPureName(string)
////////////////////////////////

{
	var i;
	var len = 0;
	var ThisChar;
	var badChar;
	var invalidChars = "/:,;'\"`"
	var purename = "";
	var field = string.split(/\s+/);

	// purename = new String("");

	for (i=0; i<invalidChars.length; i++) {
		badChar = invalidChars.charAt(i)
		if (string.indexOf(badChar,0) > -1) return "-1";
	}

	for (i=0; i<field[0].length; i++) {
		// ThisChar = new String( "string.charAt(i)" );
		ThisChar = string.charAt(i);
		// alert ("ThisChar " + ThisChar);
		if(ThisChar <= '9' && ThisChar >= '0') {
			// purename.concat(ThisChar);	
			purename += ThisChar;	
			// purename(len) = ThisChar;	
			len ++;
		}
		else if(ThisChar <= 'z' && ThisChar >= 'a') {
			purename += ThisChar;	
			len ++;
		}
		else if(ThisChar <= 'Z' && ThisChar >= 'A') {
			purename += ThisChar;	
			len ++;
		}
	}

	// alert (" in sub  name " + purename);

	return purename;
}
////////////////////////////////
function submitIt0(thisform)
////////////////////////////////

{
	var i;
	var validLines;
	var lines;
	var name;
 	var field;

	// alert ("pasted " + thisform.pasted.value);

	if(Check_Num(thisform.id.value,5,100) == -1)  return false;
	if(thisform.minres.value && Check_Num(thisform.minres.value,0,100) == -1) return false;
	if(thisform.resolution.value && Check_Num(thisform.resolution.value,0,100) == -1) return false;
	if(thisform.Rfactor.value && Check_Num(thisform.Rfactor.value,0,1) == -1) return false;
	if(Check_Num(thisform.minlen.value,40,10000) == -1) return false;
	if(Check_Num(thisform.maxlen.value,40,10000) == -1) return false;
	if(thisform.chain_id.value && Check_Num(thisform.chain_id.value,5,100) == -1) return false;

	return true;
}


////////////////////////////////
function submitIt(thisform)
////////////////////////////////

{
	var i;
	var len = ValidStrLen(thisform.pasted.value);
	var validLines;
	var lines;
	var name;
 	var field;

	// alert ("pasted " + thisform.pasted.value);

	if(Check_Num(thisform.id.value,5,100) == -1)  return false;
	if(thisform.minres.value && Check_Num(thisform.minres.value,0,100) == -1) return false;
	if(thisform.resolution.value && Check_Num(thisform.resolution.value,0,100) == -1) return false;
	if(thisform.Rfactor.value && Check_Num(thisform.Rfactor.value,0,1) == -1) return false;
	if(Check_Num(thisform.minlen.value,40,10000) == -1) return false;
	if(Check_Num(thisform.maxlen.value,40,10000) == -1) return false;
	if(thisform.chain_id.value && Check_Num(thisform.chain_id.value,5,100) == -1) return false;

	if((thisform.upload_file.value == null || thisform.upload_file.value == "") && len < 4) {
		alert ("You haven't provided data for culling!!!");
		thisform.upload_file.focus();
		return false;
	}

	// alert ("upload_file name: " + thisform.upload_file.value);

	if(thisform.upload_file.value != null && thisform.upload_file.value != "" && len >= 4) {
		alert ("You should either upload a file or input your data in paste area, but not both!");
		thisform.upload_file.focus();
		return false;
	}

	if(len >= 4) {
		lines = thisform.pasted.value.split(/\n/);
		// alert ("Total lines " + lines.length);
		// lines = thisform.pasted.split(pattern);
		validLines = 0;
		for (i=0; i<lines.length; i++) {
			// alert(i + " is " + lines[i] + " option " + thisform.option.value);
			if(thisform.option.value == "D") {
				if(lines[i].indexOf(">",0) < 0) continue;
				// if(ValidStrLen(lines[i]) > 4) validLines ++;
				field = lines[i].split(/\s+/);
				if(CheckString(field[0]) == -1) {
					alert ("You have input invalid protein name: " + field[0] + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				}

				if(ValidStrLen(field[0]) > 0) validLines ++;
			} else if(thisform.option.value != "C") {
				name = GetPureName(lines[i]);
				// alert ("name " + name);
				if(name.length == 0) {
					continue;
				} else if(name == "-1") {
					alert ("You have input invalid PDB chain(entry) name: " + lines[i] + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				} else if(name.charAt(0).match(/\D/)) {
					alert ("You have input invalid PDB chain(entry) name: " + name + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				} else if(thisform.type.value == "entry" &&  name.length != 4) {
					alert ("You have input invalid PDB entry name: " + name + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				} else if(name.length > 5 || name.length < 4) {
					alert ("You have input invalid PDB chain(entry) name: " + name + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				} else {
					// alert ("validLines " + validLines);
					validLines ++;
				}
			} else {
				field = lines[i].split(/\s+/);
				if(CheckString(field[0]) == -1) {
					alert ("You have input invalid protein name: " + field[0] + "!");
					thisform.pasted.focus();
					thisform.pasted.select();
					return false;
				}

				if(ValidStrLen(lines[i]) > 0) validLines ++;
			}
		}

		// alert ("MAXPDBS " + MAXPDBS);

		if(validLines < 2) {
			alert ("You only input " + validLines + " valid entries, the minimum number should be 2");
			thisform.pasted.focus();
			thisform.pasted.select();
			return false;
		} else if( (thisform.option.value == "D" || thisform.option.value == "C") && validLines > MAXSEQS) {
			alert ("You have input too much entries " + validLines + ", we can only process " + MAXSEQS + " entries per request!");
			thisform.pasted.focus();
			thisform.pasted.select();
			return false;
		} else if (validLines > MAXPDBS) {
			alert ("You have input too much entries " + validLines + ", we can only process " + MAXPDBS + " entries per request!");
			thisform.pasted.focus();
			thisform.pasted.select();
			return false;
		}
	}

	// alert ("return value = true " + thisform.pasted.value); 

	return true;
}

///////////////////////////////////////
function OpenWaitingWindow()
///////////////////////////////////////

{
	var leftPos = 0;
	var topPos = 0;

	if(screen) {
		leftPos = screen.width-850;
		topPos = screen.height-550;
	}

	waitWindow = window.open('','OnWaiting','width=400,height=50, left='+leftPos+', top='+topPos+'');
	// waitWindow = window.open('','help','width=400,height=50, left='+leftPos+', top='+topPos+'');
	waitWindow.document.write("Please wait, we are checking your input queries ...");
	waitWindow.document.close();
	waitWindow.focus();
}

///////////////////////////////////////
function CloseWaitingWindow()
///////////////////////////////////////

{
	waitWindow.close();
}

///////////////////////////////////////
function DeployInputPage(OptionForm)
///////////////////////////////////////

{
	var option = OptionForm.option.value;

	switch (option) {
		case "A":
			document.location = "PISCES_InputA.php";
			break;
		case "B":
			document.location = "PISCES_InputB.php";
			break;
		case "C":
			document.location = "PISCES_InputC.php";
			break;
		case "D":
			document.location = "PISCES_InputD.php";
			break;
		case "E":
			// document.location = "http://www.pdb.org";
			document.location = "NotReady.php";
	}
}

///////////////////////////////////////
function VerifyPDBParams(PDB_params)
///////////////////////////////////////

{
	var id = PDB_params.id.value;
	var minres = PDB_params.minres.value;
	var resolution = PDB_params.resolution.value;
	var Rfactor = PDB_params.Rfactor.value;
	var minlen = PDB_params.minlen.value;
	var maxlen = PDB_params.maxlen.value;
	var Xray = PDB_params.Xray.value;
	var CAonly = PDB_params.CAonly.value;
	var type = PDB_params.type.value;
	var chain_id = PDB_params.chain_id.value;
	var CullChains = PDB_params.CullChains.value;

	var key;
	var value;

	if(Xray == "Yes") Xray = "exclude"; else Xray = "include";
	if(CAonly == "Yes") CAonly = "exclude"; else CAonly = "include";

        key(0) = "Sequence percentage identity";
	key(1) = "Sequence chain length";
	key(2) = "Resolution";
        key(3) = "R-factor value";
        key(4) = "Non-X-ray entries";
        key(5) = "CA-only entries";
	key(6) = "Cull PDB by";

	value(0) = "<= " + id + "%";
	value(1) = minlen + " ~ " + maxlen;
	value(2) = minres + " ~ " + resolution;
	value(3) = Rfactor;
	value(4) = Xray;
	value(5) = CAonly;
	value(6) = type;

	if(type == "entry") {
	    key[7] = "Cull chains within entry";
	    value[7]= CullChains;

	    if(CullChains == "Yes") {
		key[8] = "Chain Seq. ID. threshold";
		value[8] = chain_id;
	    }
	}	

	document.write("<table border=\"1\" bgcolor=\"white\" cellpadding=5 cellspacing=0>");
	
	for (var i=0; i<key.length; i++) {
	    document.write("<tr><td align='left' color='black'>" + key[i] + "</td>");
	    document.write("<td align='left' color='yellow'>" + value[i] + "</td></tr>");
	}

	document.write("</table>");
}
