
// 1. Change this to modify the behavior of being able to pick both traits from the same 
// parent.  If false, you will be able to use the same traits for a parent.
var fastPlant = false;

// 2.  Change the values in quotes to accurately represent the trait attributes of the
// breedable organizm.  Each attribute should be a single letter, distinguishable by it's
// case.  I.E. capital letter = dominant, non-caps = recessive.
var firstTraitType = { DOMINANT:"ANL", RECESSIVE:"anl" };  //pea example: color: yellow, green
var secondTraitType = { DOMINANT:"R", RECESSIVE:"r" }; //pea example: shape: round, wrinkled
var firstDominance = { DOMINANT:"Purple", RECESSIVE:"Non-Purple" };

var curParents;
var curChildren;
var numSelected = 0;
var firstParentDiv = null;
var firstCheckedParent = null;
var secondCheckedParent = null;
var showingGenotypes = false;

function plantInstance(ftg0, ftg1){
    // ft = first trait
    // st = second trait
	this.ftGenes = new Array(2);
	this.ftGenes[0] = ftg0;
	this.ftGenes[1] = ftg1;
	
    this.ft = ftg0 + ftg1;
    this.st = "____";
    
    // ftSelected = first trait is selected (checked w/ check box, for example)
    this.ftSelected = false; 
    this.stSelected = false;
    
    // These are handles to objects in the DOM.
    // plantTag = the div containing the pea
    this.plantTag = null;
    
    // stRadio = the checkbox for the second trait
	this.stRadio = null;
	this.ftRadio = null;
    
    // use the first and second trait rules to create this plant's
    // apparent trait
    this.firstTrait = firstTraitRule(this.ft);
  //  this.secondTrait = secondTraitRule(this.st);
}


function firstTraitRule(ftg0, ftg1){
    if (dominantTrait(ftg0, ftg1) == true){
        return firstTraitType.DOMINANT;
    }else{
        return firstTraitType.RECESSIVE;
    }
}
/*
function secondTraitRule(st){
    if (dominantTrait(st) == true){
        return secondTraitType.DOMINANT;
    }else{
        return secondTraitType.RECESSIVE;
    }
}
*/
//create new random plant instance
function randomPlant(){
    
    var ftg0, ftg1;//, pst;
    
    
	if (Math.random() >= .5){
		ftg0 = firstTraitType.DOMINANT;
	} else {
		ftg0 = firstTraitType.RECESSIVE;
	}
    if (Math.random() >= .5){
		ftg1 = firstTraitType.DOMINANT;
	} else {
		ftg1 = firstTraitType.RECESSIVE;
	}
    
    /*
	if (Math.random() >= .5){
		pst = secondTraitType.DOMINANT;
	} else {
		pst = secondTraitType.RECESSIVE;
	}
    if (Math.random() >= .5){
		pst += secondTraitType.DOMINANT;
	} else {
		pst += secondTraitType.RECESSIVE;
	}
    */
    return new plantInstance(ftg0, ftg1);
}


function dominantTrait(tg0, tg1){
	return (tg0 == firstTraitType.DOMINANT || tg1 == firstTraitType.DOMINANT);
	/*
	secondGenotypeIndex = traits.length / 2;
    //if a dominant attribute in the trait (upper case) is present, the trait is dominant
    return (traits.charCodeAt(0) <= 90 || 
			traits.charCodeAt(secondGenotypeIndex) <= 90); */
}

function isUpper(theString){
    return (theString.charCodeAt(0) <= 90);
}

function toggleGenotypes(){
	var genotypeList = document.getElementsByTagName('genotype');
	showingGenotypes = (!showingGenotypes);
	var newStyle = '';
	if (showingGenotypes){
		newStyle = 'inline';
	}else {
		newStyle = 'none';
	}
	/*
	if (genotypeList.length > 0){
		if (genotypeList[0].style.display == 'none' || genotypeList[0].style.display == ''){
			newStyle = 'inline';
		} else {
			newStyle = 'none';
		}
	}
	*/
	for (i = 0; i < genotypeList.length; i++){
		genotypeList[i].style.display = newStyle;
		
	}
	
}


// called when a checkbox is clicked
function toggle(radioInput, plant, row){
    trait = radioInput.value; //radioInput.getAttribute('trait');
    var inputList = row.getElementsByTagName('input');
    var shouldCheck = radioInput.checked;

	
    if (fastPlant){  //don't allow (un)check if same plant
        if (trait == plant.ftRadio.value) {
            if(plant.stRadio.checked){
                plant.ftRadio.checked = false;
                return;
            } 
        } else if (trait == plant.stRadio.value) {
            if(plant.ftRadio.checked){
                plant.stRadio.checked = false;
                return;
            } 
        }
    }
    var nChecked = 0;
    for (i = 0; i < inputList.length; i++){
      //  alert('trait: ' + trait + '  inputList[i] trait: ' + inputList[i].getAttribute('trait'));
        if (trait == inputList[i].value){
			if (inputList[i].checked == true){
				nChecked++;
			} 
			//       inputList[i].checked = false;
          	  
        } 
    }


    
 /*   for (i = 0; i < curParents.length; i++){
        if (trait == 'firstTrait'){
            curParents[i].ftSelected = false;
        }else{
            curParents[i].stSelected = false;
        }
    }
*/
	if (nChecked > 2){
		radioInput.checked = false;
	} 
 //   radioInput.checked = shouldCheck;
 	
	
    if (trait == 'firstTrait'){
        plant.ftSelected = radioInput.checked;
    }else{
        plant.stSelected = radioInput.checked;
    }
	

    
}

function replaceBreedButton(oldDiv, newDiv){
    //remove from old div
    var breedButton = document.getElementById('breedbutton');
    oldDiv.removeChild(breedButton);
    
    //put in new div
    newDiv.appendChild(breedButton);
}


function initParents(){
	var mainDiv = document.getElementById('main');
	var p1 = new plantInstance(firstTraitType.RECESSIVE, firstTraitType.RECESSIVE);
	var p2 = new plantInstance(firstTraitType.DOMINANT, firstTraitType.DOMINANT);
	var divAndRow = newDiv(mainDiv, true);
	
	
	var div = divAndRow[0];
	var row = divAndRow[1];
	curParents = new Array(2);
    curParents[0] = p1;
    curParents[1] = p2;
	createAttachPlant(p1, row, true);
	createAttachPlant(p2, row, true);
	
	
    replaceBreedButton(mainDiv, div);

}


function initRandomParents(mainDiv){
    var divAndRow = newDiv(mainDiv, true);
    var div = divAndRow[0];
    var row = divAndRow[1];
    
    var p1 = randomPlant();
    var p2 = randomPlant();
    curParents = new Array(2);
    curParents[0] = p1;
    curParents[1] = p2;
    
	createAttachPlant(p1, row);
    createAttachPlant(p2, row);
    
    replaceBreedButton(mainDiv, div);
}


function newDiv(parentDiv, isParent){
    var pDiv = document.createElement('div');
    var txt;

    
    if (isParent){
        pDiv.id = 'parents';
        var classAttr = document.createAttribute('class');
        classAttr.value = 'parents';
        pDiv.setAttributeNode(classAttr);
      //  pDiv.class = 'parents';
        txt = document.createTextNode('Parents');
        
    }else{
        pDiv.id = 'children';
        var classAttr = document.createAttribute('class');
        classAttr.value = 'children';
        pDiv.setAttributeNode(classAttr);
        
        //pDiv.class = 'children';
        txt = document.createTextNode('Children (pick 2 new parents)');

    }
    
    
    var table = document.createElement('table');
    var tableBody = document.createElement('tbody');
    var row = document.createElement('tr');
    tableBody.appendChild(row);
    table.appendChild(tableBody);
    
    pDiv.appendChild(txt);
    pDiv.appendChild(document.createElement('br'));
    pDiv.appendChild(table);
    parentDiv.appendChild(pDiv);
    
    var retArray = new Array(2);
    retArray[0] = pDiv;
    retArray[1] = row;
    
    return retArray;
}



function createAttachPlant(plant, row, mature){
    var col = document.createElement('td');
       
    var plantTag = document.createElement('plant');
    var firstTraitAttr = document.createAttribute('ft');
    firstTraitAttr.value = plant.ft;
    plantTag.setAttributeNode(firstTraitAttr);
    
    var plantClass = document.createAttribute('class');
    plantClass.value = '';
    plantTag.setAttributeNode(plantClass);
    
       
    var secondTraitAttr = document.createAttribute('st');
    secondTraitAttr.value = plant.st;
    plantTag.setAttributeNode(secondTraitAttr);
    
    var newImg = document.createElement('img');
    newImg.src = imgFile(plant, mature);
	var firstTrait = null;
	var secondTrait = null;
	
	if (dominantTrait(plant.ftGenes[0], plant.ftGenes[1]) == true){
		firstTrait = document.createTextNode(firstDominance.DOMINANT);
    } else {
		firstTrait = document.createTextNode(firstDominance.RECESSIVE);
	}
	
	var genTag = document.createElement('genotype');
	if (showingGenotypes){
		genTag.style.display = 'inline';
	} else {
		genTag.style.display = 'none';
	}
	
	//var genTagClass = document.createAttribute('class');
	//genTagClass.value = 'hidden';
	//genTag.setAttributeNode(genTagClass);
	
	
    //var firstTrait = document.createTextNode(plant.ft);
    //var secondTrait = document.createTextNode(plant.st);
    
    var ftRadio = document.createElement('input');
    ftRadio.type = 'checkbox';
    ftRadio.onclick = function(){ return toggle(this, plant, row); }
    var ftRadioAttr = document.createAttribute('trait');
    ftRadioAttr.value = 'firstTrait';
    ftRadio.setAttributeNode(ftRadioAttr);
    ftRadio.value = 'firstTrait';
	plant.ftRadio = ftRadio;
	
	if (mature != null && mature == true){
		ftRadio.setAttribute('disabled', 'true');
	}
    
	
    /*var stRadio = document.createElement('input');
    stRadio.type = 'checkbox';
    var stRadioAttr = document.createAttribute('trait');
    stRadioAttr.value = 'secondTrait';
    stRadio.onclick = function(){ return toggle(this, plant, row); }
    stRadio.setAttributeNode(stRadioAttr);
    stRadio.value = 'secondTrait';
	plant.stRadio = stRadio;
    */
    plantTag.appendChild(newImg);
    plantTag.appendChild(document.createElement('br'));
    plantTag.appendChild(ftRadio);
    plantTag.appendChild(firstTrait);
	plantTag.appendChild(document.createElement('br'));
	var halfIndex = plant.ft.length / 2;
	
	genTag.appendChild(document.createTextNode(plant.ft.substring(0, halfIndex) + '/' +
											   plant.ft.substring(halfIndex, 2*halfIndex)));
	plantTag.appendChild(genTag);
   /*
    plantTag.appendChild(document.createElement('br'));
    plantTag.appendChild(stRadio);
    plantTag.appendChild(secondTrait);
	*/
    col.appendChild(plantTag);
    row.appendChild(col);
    
    plant.plantTag = plantTag;
}



function imgFile(plant, mature){
    //Since there is no way to distinguish different files based on their case,
    //we have to add "d" for dominant trait, and "r" for recessive.
    //So, a yellow (dominant), wrinkled (recessive) pea should have the filename:
    //"Yd-rr.gif"
    var first = "";
    if (dominantTrait(plant.ftGenes[0], plant.ftGenes[1])){
		first = firstDominance.DOMINANT + "d";
	} else {
        first = firstDominance.RECESSIVE + "r";
    }
    
	if (mature != null && mature == true){
		first += "m";
	}
   /* var second = plant.secondTrait;
    if (isUpper(second)){
        second += "d";
    } else {
        second += "r";
    }
    */
	
	return 'images/' + first + '.gif';
}



function selectedParents(){
    var list = curParents;
    var numSelected = 0;
    var selectedParents = new Array(2);
	
	
    for(i = 0; i < list.length; i++){
        if (list[i].ftSelected){
            selectedParents[numSelected++] = list[i];
        }
        
        if (list[i].stSelected){
            selectedParents[numSelected++] = list[i];
        }
        
        if (numSelected >= 2){
            break;
        }
    }
    if (numSelected != 2){
        return null;
    }
    return selectedParents;
}







function mate(){
    
    var mainDiv = document.getElementById('main');
    
    if (curParents == null || curParents.length < 1){
        
		initRandomParents(mainDiv);
        var parentDiv = document.getElementById('parents');
        var inputList = parentDiv.getElementsByTagName('input');
        for (i = 0; i < inputList.length; i++){
            if (inputList[i].id != 'breedbutton'){
                inputList[i].setAttribute('disabled', 'true');
            }
        }
        
        return;
	} 
    
    var sParents = null;
    
    if (curChildren == null){
        sParents = curParents;
    }else{
        sParents = selectedParents();
    }
    
    if (sParents == null || sParents.length != 2){
        alert('Please select 2 parents');
        return;
    }
    
    var numParents = sParents.length;
    
    
    curChildren = new Array(4);
    var divAndRow = newDiv(mainDiv, false);
    var div = divAndRow[0];
    var row = divAndRow[1];
    
	var numChildren = 0;
	
    for(i=0; i<numParents; i++){
        for (j=0; j<numParents; j++){
		/*	ftg0 = sParents[0].ftGenes[i]
			var numCharsInGen = sParents[0].ft.length / 2;
			var firstIndex = i*numCharsInGen;
			var secondIndex = j*numCharsInGen;
			var first = sParents[0].ft.substring(firstIndex, firstIndex + numCharsInGen);
			var second = sParents[1].ft.substring(secondIndex, secondIndex + numCharsInGen);
			var firstTraitAttr = first + second;
				
//            var firstTraitAttr = sParents[0].ft.charAt(i) + sParents[1].ft.charAt(j);
			var secondTraitAttr = sParents[0].st.substring(firstIndex, firstIndex + numCharsInGen) + 
				sParents[1].st.substring(secondIndex, secondIndex + numCharsInGen);
			 
//            var secondTraitAttr =  sParents[0].st.charAt(i) + sParents[1].st.charAt(j);
            */
            var newChild = new plantInstance(sParents[0].ftGenes[i], sParents[1].ftGenes[j]);
            createAttachPlant(newChild, row);
            curChildren[numChildren++] = newChild;
        }
    }
    sParents[0].plantTag.setAttribute('class', 'selected');
    sParents[1].plantTag.setAttribute('class', 'selected');
    
    
    if (curChildren != null){
        curParents = curChildren;
    }
    
    var parentDiv = document.getElementById('parents');
    var childrenDiv = document.getElementById('children');    
    replaceBreedButton(parentDiv, childrenDiv);

    var inputList = parentDiv.getElementsByTagName('input');
    for (i = 0; i < inputList.length; i++){
        inputList[i].setAttribute('disabled', 'true');
    }

    parentDiv.firstChild.nodeValue = 'Parents';
    parentDiv.setAttribute('class', 'oldparents'); 
    parentDiv.setAttribute('className', 'oldparents'); 
    parentDiv.setAttribute('id', '');
   
    childrenDiv.setAttribute('id', 'parents');
    childrenDiv.setAttribute('class', 'parents');
    childrenDiv.setAttribute('className', 'parents');
    
    updateOldParents();
}

function updateOldParents(){
    //find number of oldparent divs
    var divList = document.getElementsByTagName('div');
    firstParentDiv = null;
    var numOldParents = 0;
    for (i = 0; i < divList.length; i++){
        if (divList[i].className == 'oldparents' && divList[i].style.display != 'none'){
            if (firstParentDiv == null){
                firstParentDiv = divList[i];
            }
            numOldParents++;
        }
        
    }
    
    if (firstParentDiv != null && numOldParents >= 5){
        firstParentDiv.style.display = 'none';
    }
	
	if (numOldParents >= 3){
		toggleGenotypeButton = document.getElementById('toggleGenotypes');
		toggleGenotypeButton.style.display = 'inline';
	}
    
}
