
// 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:"Y", RECESSIVE:"y" };  //pea example: color: yellow, green
var secondTraitType = { DOMINANT:"R", RECESSIVE:"r" }; //pea example: shape: round, wrinkled


var curParents;
var curChildren;
var numSelected = 0;
var firstParentDiv = null;

function plantInstance(ft, st){
    // ft = first trait
    // st = second trait
    this.ft = ft;
    this.st = 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(ft){
    if (dominantTrait(ft) == 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 pft, pst;
    
    
	if (Math.random() >= .5){
		pft = firstTraitType.DOMINANT;
	} else {
		pft = firstTraitType.RECESSIVE;
	}
    if (Math.random() >= .5){
		pft += firstTraitType.DOMINANT;
	} else {
		pft += 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(pft, pst);
}


function dominantTrait(traits){
    //if a dominant attribute in the trait (upper case) is present, the trait is dominant
    return (traits.charCodeAt(0) <= 90 || traits.charCodeAt(1) <= 90);
}

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

// 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;
            } 
        }
    }
    
    for (i = 0; i < inputList.length; i++){
      //  alert('trait: ' + trait + '  inputList[i] trait: ' + inputList[i].getAttribute('trait'));
        if (trait == inputList[i].value){
            inputList[i].checked = false;
          	  
        } 
    }


    
    for (i = 0; i < curParents.length; i++){
        if (trait == 'firstTrait'){
            curParents[i].ftSelected = false;
        }else{
            curParents[i].stSelected = 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 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){
    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);
    
    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;
    
    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'));
    plantTag.appendChild(stRadio);
    plantTag.appendChild(secondTrait);

    col.appendChild(plantTag);
    row.appendChild(col);
    
    plant.plantTag = plantTag;
}



function imgFile(plant){
    //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 = plant.firstTrait;
    if (isUpper(first)){
            first += "d";
    } else {
        first += "r";
    }
    
    var second = plant.secondTrait;
    if (isUpper(second)){
        second += "d";
    } else {
        second += "r";
    }
    
	return 'images/' + first + '-' + second + '.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++){
            var firstTraitAttr = sParents[0].ft.charAt(i) + sParents[1].ft.charAt(j);
            var secondTraitAttr =  sParents[0].st.charAt(i) + sParents[1].st.charAt(j);
            
            var newChild = new plantInstance(firstTraitAttr, secondTraitAttr);
            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 >= 6){
        firstParentDiv.style.display = 'none';
    }
    
}
