var MixedBaseNames = ''
var MixedBaseArray = [1];
var _MixedBaseArray = [];


function storeCaret(ftext) {


	if (ftext.createTextRange ) {
		selectedRange = document.selection.createRange().duplicate();
		selectedInputArea = ftext;
	}
}
// -->

function sethasFocus(ftext) 
{
    var theForm = document.forms['frmMain'];
    if (!theForm) {
        theForm = theForm;
    }

	for (i=0;i<theForm.length;i=i+1) 
		{
			if (theForm.elements[i].type == 'textarea') 
			{
				if (theForm.elements[i].name == ftext.name )
				{
					theForm.elements[i].hasFocus = true;
				}
				else
				{
					theForm.elements[i].hasFocus = false;
				}
			}
		}
}
// -->

//store the selected area of the last selected input 

function storeCaretImproved(textE1) {

	if (textE1.createTextRange ) {
		selectedRange = document.selection.createRange().duplicate();
		selectedInputArea = textE1;
	}
	
		
}
// -->

//put text infto the last selected place

function InsertAtCursor(txtToInsert) {

		var retval;
		//set default textarea, in case no cursor exists
		retval = 'OligoAnalyzer_SequenceSettingsControl_tbSequence';
		
		var theForm = document.forms['frmMain'];
        if (!theForm) {
            theForm = theForm;
        }

		
		for (i=0;i<theForm.length;i=i+1) 
			{
			
				if (theForm.elements[i].type == 'textarea') 
				{
					if (theForm.elements[i].hasFocus  )
					{
						retval = theForm.elements[i].id;
					}
				}
			}
		var vtext;
		vtext = eval('theForm.' + retval);
		//alert (txtToInsert.substring(0,2));
		//check for 5 prime
		//insert at front
		if (txtToInsert.substring(0,2) == '/5')
		{
		    if(vtext.value.substring(0,2) == '/5')
		    {
		        alert("Unable to add 5' Mod. Please verify that a 5' Mod is not already added to the Sequence.");
		    }
		    else
		    {
		        vtext.value = txtToInsert + vtext.value;
				vtext.focus();
		    }
				
		}
		//check for 3 prime
		//insert at end
		else if (txtToInsert.substring(0,2) == '/3')
		{
		    if(vtext.value.indexOf('/3') > 0)
		    {
		        alert("Unable to add 3' Mod. Please verify that a 3' Mod is not already added to the Sequence.");
		    }
		    else
		    {
		        vtext.value = vtext.value + txtToInsert;
			    vtext.focus();
		    }
			
		}
		//internal or unknown
		//insert at cursor position or at the end of the sequence
		else
		{
			if (vtext.createTextRange && vtext.caretPos) 
			{
				var caretPos = vtext.caretPos;
				caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? txtToInsert + ' ' : txtToInsert;
				vtext.focus();
			}
			else
			{
				vtext.value+=txtToInsert;
				vtext.focus();
			} 
		}	
}
// -->

function InsertMixedBase(txtToInsert, MixedBase) {

	var retval;
	//set default textarea, in case no cursor exists
	retval = 'OligoAnalyzer_SequenceSettingsControl_tbSequence';
	
	var theForm = document.forms['frmMain'];
    if (!theForm) {
        theForm = theForm;
    }

	
	for (i=0;i<theForm.length;i=i+1) 
		{
		
			if (theForm.elements[i].type == 'textarea') 
			{
				if (theForm.elements[i].hasFocus )
				{
					retval = theForm.elements[i].id;
				}
			}
		}
	var vtext;
	vtext = eval('theForm.' + retval);
	var caretPos = vtext.caretPos;
	

	//check if mixed base already exsists


//alert('before insert');

	if (vtext.createTextRange && vtext.caretPos) 
	{
	    //alert('if insert ' + vtext.caretPos + ' ' + vtext.value);
		var caretPos = vtext.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? txtToInsert + ' ' : txtToInsert;
		//alert('if insert2: ' + vtext.caretPos + ' ' + vtext.value);
		vtext.focus();
	}
	else
	{
//	alert('else insert');
		vtext.value+=txtToInsert;
		vtext.focus();
	} 
	
	if(MixedBaseNames != '')
	{
	    VerifyMixedBasePosition();
	}

}

function verifymixedbases()
{
	var mx_total;
	var a;
	var c;
	var t;
	var g;
	var name;
	var Mixture;
	
	var theForm = document.forms['frmMain'];
    if (!theForm) {
            theForm = theForm;
    }
        
	mx_total=0;
	mx_total = parseInt(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentA.value) + parseInt(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentC.value) + parseInt(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentG.value) + parseInt(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentT.value);
	
	if (mx_total  >= 99 && mx_total <= 100)
	{
		a = Make_CMB_Pct(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentA.value);
		c = Make_CMB_Pct(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentC.value);
		g = Make_CMB_Pct(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentG.value);
		t = Make_CMB_Pct(theForm.OligoAnalyzer_TabsMenu_EntryTabs_percentT.value);
		
		name = (theForm.OligoAnalyzer_TabsMenu_EntryTabs_tbMixBaseName.value);		
		name = replace(name,' ','');
		Mixture = a + c + g + t;
		
		if (name == '')
		{
		    InsertAtCursor('(' + Mixture + ')');
		}
		else
		{
		    if (MixedBaseNames.indexOf(name + ":") > 0)
		    {
		        var isValid = false;
		        if(_MixedBaseArray.length > 0)
	            {
                    var i = 0;
                    for(i=0;i<_MixedBaseArray.length;i=i+1)
                    {                 
                        //var aMixedBase = _MixedBaseArray[i];  
                       // alert("Test: " + _MixedBaseArray[i].Name + " == " + name + "&&" + _MixedBaseArray[i].Mix + " == " + Mixture)      
                        if(_MixedBaseArray[i].Name == name && _MixedBaseArray[i].Mix == Mixture)
                        {
                            InsertAtCursor('(' + name  + ')');
                            isValid = true;		
                            break;
                        }
                    }         	            
	            }
	        
                if(isValid == false)
                {
                    alert("Unable to create the specified custom mix base. Please verify that the name is unique.");
                }
		        
		    }
		    else
		    {
		        InsertAtCursor('(' + name + ':' + Mixture + ')');		    
		        MixedBaseNames = MixedBaseNames + '(' + name + ':' + a + c + g + t + ')';
		        
		        //MixedBaseArray[0] = name; 
		        //MixedBaseArray[1] = a + c + g + t; 
		        //alert("Name: " + MixedBaseArray[0]);
		        
		        var MixedBaseItem = aMixedBaseItm(name, Mixture);
		         _MixedBaseArray.push(MixedBaseItem);  
		        //_MixedBaseArray.push(MixedBaseArray);  
		        
		        AddMixedBaseNames();
		        
		       
		    }
		    
		}			
		return true;
	}
	else
	{
		alert("Unable to create the specified custom mix base. Please verify that the total is 99% or 100%.");
		return false;
	}
	
	if(MixedBaseNames != '')
	{
	     VerifyMixedBasePosition();
	}
	
}
// -->


function CreateLabel(CustName, CustMix)
{
    var tdCustMixedBase = $get('OligoAnalyzer_TabsMenu_EntryTabs_tdCustMixedBase');
    
    var aLabel = document.createElement("Div");
    aLabel.innerText = CustName + ' (' + CustMix + ')';
    
    aLabel.id = CustName + i;

    aLabel.style.cursor = "hand"; 
    aLabel.className = "linkItem";

    aLabel.onclick = function(){InsertMixedBase('(' + CustName + ')', CustMix);}

    tdCustMixedBase.appendChild(aLabel);    
    
    

}

function aMixedBaseItm(aName, aMix)
{
	return {Name:aName, Mix:aMix};
}   

function AddMixedBaseNames()
{
    var SelectionArray = MixedBaseNames.split(")");
   //alert("Length: " + SelectionArray.length);
    var i = 0;
    var tdCustMixedBase = $get('OligoAnalyzer_TabsMenu_EntryTabs_tdCustMixedBase');
    tdCustMixedBase.innerText = '';
      
      	        
    for (i=0;i<_MixedBaseArray.length;i=i+1)
	{
	    //var aMixedBase = _MixedBaseArray[i];        
        if(_MixedBaseArray[i].Name != '')
        {
            
            CreateLabel(_MixedBaseArray[i].Name, _MixedBaseArray[i].Mix);
        }    
	}
	
	

      
      
}


function Make_CMB_Pct(theNum)
{
  var RetVal;
  if (parseInt(theNum) >= 10)
  {
    RetVal = theNum;
  }
  else
  {
    RetVal = "0" + theNum;
  }
  return RetVal;
}
// -->

// Begin

function checkFor_r(theString)
{
	if (theString.indexOf("r") > -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
}
function BaseCounter(theSequence, MaxLength)
{
	var divSeqWarning = $get('divSeqWarning');
	var theForm = document.forms['frmMain'];
    if (!theForm) {
        theForm = theForm;
    }
	
	var textareaName = theSequence.name;
	textareaName = replace(textareaName,'OligoAnalyzer:SequenceSettingsControl','')
	textareaName = replace(textareaName,'OligoAnalyzer$SequenceSettingsControl','')
	textareaName = replace(textareaName,':tbSequence','')
	textareaName = replace(textareaName,'$tbSequence','')
	textareaName = 'OligoAnalyzer_SequenceSettingsControl' + textareaName + '_NumberOfBases';
	
	
	var textareaValue = theSequence.value;
	
	
	
	
	
	
	var thelength = textareaValue.length;
	var countMods = Math.round((CountChar(textareaValue, "/"))/2);
	countMods = countMods + Math.round((CountChar(textareaValue, "(")));
	var ModChars = CountModChars(textareaValue);
	textareaValue = RemoveMods(textareaValue);
	textareaValue = RemoveNonBase(textareaValue);
	
	
	
	thelength = (CountChar(textareaValue,"A") + CountChar(textareaValue,"a") + CountChar(textareaValue,"C") 
	+ CountChar(textareaValue,"c") + CountChar(textareaValue,"G") + CountChar(textareaValue,"g") 
	+ CountChar(textareaValue,"T") + CountChar(textareaValue,"t") + (CountChar(textareaValue, "R")) 
	+ (CountChar(textareaValue, "Y")) + (CountChar(textareaValue, "M")) + (CountChar(textareaValue, "K")) 
	+ (CountChar(textareaValue, "S")) + (CountChar(textareaValue, "W")) + (CountChar(textareaValue, "H")) 
	+ (CountChar(textareaValue, "B")) + (CountChar(textareaValue, "V")) + (CountChar(textareaValue, "D"))  
	+ (CountChar(textareaValue, "U")) + (CountChar(textareaValue, "I")) + (CountChar(textareaValue, "|")) 
	+ (CountChar(textareaValue, "N")) + countMods);
	
	var SpacerCount = 0;
	SpacerCount = SpaceCount(theSequence.value) + MaxLength;


//if (thelength > MaxLength)
//if (theSequence.value.length > SpacerCount - (countMods/2) + ModChars)
	if (theSequence.value.length > SpacerCount - (countMods) + ModChars)
			{
				//theSequence.value = theSequence.value.substring(0, SpacerCount - (countMods/2));
			    if (theSequence.value.charAt(SpacerCount - (countMods) + ModChars) == ')'  || theSequence.value.charAt(SpacerCount - (countMods) + ModChars) == '/' || theSequence.value.charAt(SpacerCount - (countMods) + ModChars) == ']')
			    {
			        theSequence.value = RemoveFinalMod(theSequence.value.substring(0, SpacerCount - (countMods) + ModChars));
			    }
			    else
			    {
			        theSequence.value = theSequence.value.substring(0, SpacerCount - (countMods) + ModChars);
			    }
				
				
				thelength = thelength - 1;
				BaseCounter(theSequence, MaxLength);
			}

	theForm[textareaName].value = thelength;
	
	if(MaxLength <= thelength)
	{
	    
	    divSeqWarning.style.display = 'block';
	}
	else
	{
	    divSeqWarning.style.display = 'none';
	}
	
	//This will store the caret
	if (theSequence.createTextRange) theSequence.caretPos = document.selection.createRange().duplicate(); 
	
	if(MixedBaseNames != '')
	{
	     VerifyMixedBasePosition();
	}
	
}

function SpaceCount(originalString)
{ 
	var strLength = originalString.length;  
	var SpaceCounter = 0;
	
	
	if (strLength == 0) 
	{ 
		return SpaceCounter;
	} 
	for (i=0;i<strLength;i=i+1) 
	{
		if (originalString.charAt(i) == " ")
		{
			SpaceCounter = SpaceCounter + 1;
		}
	}
	
	return SpaceCounter;
} 

function OnLoadBaseCounter()
{
    var theForm = document.forms['frmMain'];
    if (!theForm) {
        theForm = theForm;
    }

	for (i=0;i<theForm.length;i=i+1) 
	{
		if (theForm.elements[i].type == 'textarea') 
		{	
			if (theForm.elements[i].name.substring(15,23) == 'Sequence')
			{
				var textareaName = theForm.elements[i];
				BaseCounter(textareaName);
			} 
		}
	}
}

function RemoveNonBase(theString)
{
	var returnString = ""
	for ( var i = 0; i < theString.length; i++) {
	if (((theString.charAt(i) == "A") || (theString.charAt(i) == "a") || (theString.charAt(i) == "G") 
	|| (theString.charAt(i) == "g") || (theString.charAt(i) == "C") || (theString.charAt(i) == "c") 
	|| (theString.charAt(i) == "T") || (theString.charAt(i) == "t") || (theString.charAt(i) == "R") 
	|| (theString.charAt(i) == "Y") || (theString.charAt(i) == "M") || (theString.charAt(i) == "K") 
	|| (theString.charAt(i) == "S") || (theString.charAt(i) == "W") || (theString.charAt(i) == "H") 
	|| (theString.charAt(i) == "B") || (theString.charAt(i) == "V") || (theString.charAt(i) == "D") 
	|| (theString.charAt(i) == "U") || (theString.charAt(i) == "I")  || (theString.charAt(i) == "|") 
	|| (theString.charAt(i) == "N"))) {
	returnString += theString.charAt(i)
}
}
	return returnString
}



function CountModChars(theString)
{
	var returnCount = 0
	var IsMod = "False"
	
	
	for ( var i = 0; i < theString.length; i++) 
	    {
	        if (IsMod == "False") 
	         {
	             if (theString.charAt(i) == "/" || theString.charAt(i) == "[" || theString.charAt(i) == "(")
	                 {
	                        IsMod = "True"
	                        returnCount = returnCount + 1;
	                 }
	             
	         }
	         else
	         {
	             returnCount = returnCount + 1;
	             
	            if (theString.charAt(i) == "/" || theString.charAt(i) == "]" || theString.charAt(i) == ")")
	                {
	                 IsMod = "False"
	                
	                }
	         }
	         
        }

	return returnCount
}

function RemoveFinalMod(theString)
{

    var returnString = theString;
	var IsMod = "False";
	var NewLength = theString.length;
	
	
	for ( var i = theString.length; i > 1; i--) 
	    {
	        if (IsMod == "False") 
	         {
	             if (theString.charAt(i) == "/" || theString.charAt(i) == "[" || theString.charAt(i) == "(")
	                 {
	                        IsMod = "True"
	                         break;
	                 }
	               else
	                 {
	                    NewLength = NewLength - 1;
	                 }
	         }
	                  
        }
    returnString = returnString.substring(0,NewLength)
	return returnString;
}



function RemoveMods(theString)
{
	var returnString = "";
	var IsMod = "False";
	
	
	for ( var i = 0; i < theString.length; i++) 
	    {
	        if (IsMod == "False") 
	         {
	             if (theString.charAt(i) == "/" || theString.charAt(i) == "[" || theString.charAt(i) == "(")
	                 {
	                        IsMod = "True";
	                 }
	               else
	                 {
	                     returnString += theString.charAt(i);
	                 }
	         }
	         else
	         {
	            if (theString.charAt(i) == "/" || theString.charAt(i) == "]" || theString.charAt(i) == ")")
	                {
	                 IsMod = "False";
	                 if (theString.charAt(i) == ")")
	                 {
	                    returnString += theString.charAt("|");
	                 }
	                }
	         }
	         
        }

	return returnString;
}

function CountChar(theString,theChar) {
	var returnValue = 0
	theString = theString.toUpperCase()
	for ( var i = 0; i < theString.length; i++) {
	if (theString.charAt(i) == theChar) {
	returnValue ++
	}
}
	return returnValue
}
function replace(originalString,searchText,replaceText)
{ 
	var strLength = originalString.length; 
	var txtLength = searchText.length; 
	
	
	if ((strLength == 0) || (txtLength == 0)) 
	{ 
		return originalString;
	} 
	var i = originalString.indexOf(searchText); 
	if ((!i) && (searchText != originalString.substring(0,txtLength))) 
	{
		return originalString;
	} 
	if (i == -1) 
	{
		return originalString;
	} 
	var newstr = originalString.substring(0,i) + replaceText; 
	if (i+txtLength < strLength) 
	{
		newstr += replace(originalString.substring(i+txtLength,strLength),searchText,replaceText);
	} 
	return newstr;
} 

function convertDNAToRNA(theSequence)
{
	var theField = theSequence;
	var selectedText = document.selection;
	var x;
	if (selectedText.type == 'Text') {
		var newRange = selectedText.createRange();
		theField.focus();
		
		x = newRange.text
		
		if (checkFor_r(x) < 1)
		{
			x = replace(x,"t","T");
			x = replace(x,"a","A");
			x = replace(x,"c","C");
			x = replace(x,"g","G");
			x = replace(x,"u","U");
		
		    x = replace(x,"U","rU");
			x = replace(x,"T","rU");
			x = replace(x,"A","rA");
			x = replace(x,"C","rC");
			x = replace(x,"G","rG");
		}
		else
		{
			alert('Your selection already contains RNA bases');
		}

		document.selection.createRange().text = x
		
	} else {
		alert('select text in the page and then press this button');
		
	}
}


function textCounter(field, maxlimit) 
	{
		var newField = replace(field.value," ", "M")
		//newField.value = field.value.replace( " ", "")
		if (newField.value.length > maxlimit)
			{
				field.value = newField.value.substring(0, maxlimit);
			}

	} 
	
function VerifyMixedBasePosition() {

	var retval;
	//set default textarea, in case no cursor exists
	retval = 'OligoAnalyzer_SequenceSettingsControl_tbSequence';
	
	var theForm = document.forms['frmMain'];
    if (!theForm) {
        theForm = theForm;
    }

	
	for (i=0;i<theForm.length;i=i+1) 
		{
		
			if (theForm.elements[i].type == 'textarea') 
			{
				if (theForm.elements[i].hasFocus  )
				{
					retval = theForm.elements[i].id;
				}
			}
		}
	var vtext;
	vtext = eval('theForm.' + retval);
	
	var theSequence = vtext.value;
	
	for (i=0;i<_MixedBaseArray.length;i=i+1) 
	{
        var aMixedBase = _MixedBaseArray[i];        
        if(_MixedBaseArray[i].Name != '')
        {
            if(theSequence.indexOf(_MixedBaseArray[i].Name + ")") > 0)
            {
                if(theSequence.indexOf(_MixedBaseArray[i].Name + ":") > theSequence.indexOf(_MixedBaseArray[i].Name + ")"))
                {
                   var MixedBaseIndex = theSequence.indexOf(_MixedBaseArray[i].Name + ")");
                   var OrigSeqLen = theSequence.length;
                    
                   theSequence = replace(theSequence,'(' + _MixedBaseArray[i].Name + ":" + _MixedBaseArray[i].Mix + ")",'(' + _MixedBaseArray[i].Name + ')');
                   var newSeq = '';
                    newSeq = theSequence.substring(0, MixedBaseIndex + _MixedBaseArray[i].Name.length) + ':' + _MixedBaseArray[i].Mix + theSequence.substring(MixedBaseIndex + _MixedBaseArray[i].Name.length, theSequence.length + _MixedBaseArray[i].Name.length);
                    
                      if(OrigSeqLen == newSeq.length)
                      {
                        vtext.value = newSeq;                       
                        storeCaret($get('OligoAnalyzer_SequenceSettingsControl_tbSequence'));
                        BaseCounter($get('OligoAnalyzer_SequenceSettingsControl_tbSequence'), 255);
                        sethasFocus('OligoAnalyzer:SequenceSettingsControl:Sequence');
                        vtext.focus();
                      }
                }
                else if (theSequence.indexOf(_MixedBaseArray[i].Name + ":") < 0 && theSequence.indexOf(_MixedBaseArray[i].Name + ")") >= 0)
                {
                    var MixedBaseIndex = theSequence.indexOf(_MixedBaseArray[i].Name + ")");
                    var OrigSeqLen = theSequence.length;
                    var newSeq = '';
                    newSeq = theSequence.substring(0, MixedBaseIndex + _MixedBaseArray[i].Name.length) + ':' + _MixedBaseArray[i].Mix + theSequence.substring(MixedBaseIndex + _MixedBaseArray[i].Name.length, theSequence.length + _MixedBaseArray[i].Name.length);
                    
                      if(OrigSeqLen <= newSeq.length)
                      {
                        vtext.value = newSeq;                       
                        storeCaret($get('OligoAnalyzer_SequenceSettingsControl_tbSequence'));
                        BaseCounter($get('OligoAnalyzer_SequenceSettingsControl_tbSequence'), 255);
                        sethasFocus('OligoAnalyzer:SequenceSettingsControl:Sequence');
                        vtext.focus();
                      }
                }
            }
        }    
	}
	 vtext.focus();
}
				


//  End -->
