function hideHelp()
{
	document.getElementById('help_closed').style.display = 'block';
	document.getElementById('help_open').style.display = 'none';
}

function showHelp()
{
	document.getElementById('help_closed').style.display = 'none';
	document.getElementById('help_open').style.display = 'block';
}

function setStandard(standard)
{
	// make sure the standard exists
	if (conversion[standard] == null || lociOrder[standard] == null)
		standard = 'NIST';
	
    // set the combo value
    setComboValue('combo_standards', standard, 0);
    
    // fire the standard event
    standardChanged(standard);
}

// get lab standard
function getStandard()
{
    return document.getElementById('combo_standards').value;
}

function standardChanged(standard)
{
    // show the unknown text if necessary
    updateUnknownMarkerConversion(standard);
    
    // fill the marker combos
    populateMarkerValues(standard);
    
    // update the 389 label if necessary
    updateDYS389B(standard);
    
    // update the 635/YGATAC4 label
    updateDYS635(standard);
    
    // reorder the combos
    setOrder(standard);
    
    // store the standard in the previous
    previousStandard = standard;
}

function setOrder(standard)
{
    // don't set it if already set
    // just check the first combo to see if it's right
/*
    var parent = document.getElementById('marker_group_0');
    var combo = document.getElementById('marker_group_' + getFirstLocus(standard));
    if (combo.parentNode == parent)
    	return;
*/
    	
    // fire the order changed event
    orderChanged(standard);
}

function getFirstLocus(standard)
{
	for (var i = 0; i < groupNames.length; i++)
	{
		var groupName = groupNames[i];
		var index = lociOrder[standard][groupName];
		if (index == '0')
			return groupName;
	}
	return 'unknown';
}

function orderChanged(standard)
{
    // temporary storage
    var markers = new Array();
    var idNames = ['marker_label_', 'marker_group_'];
    
    // loop through all the markers and remove them from the current parents
    for (var i = 0; i < groupNames.length; i++)
    {
        var groupName = groupNames[i];
        markers[groupName] = new Array();
        for (var j = 0; j < idNames.length; j++)
        {
            markers[groupName][j] = document.getElementById(idNames[j] + groupName);
            markers[groupName][j].parentNode.removeChild(markers[groupName][j]);
        }
    }
    
    // put the nodes back in the correct order
    for (var i = 0; i < groupNames.length; i++)
    {
        var groupName = groupNames[i];
        var index = lociOrder[standard][groupName];
        for (var j = 0; j < idNames.length; j++)
        {
            var parentNode = document.getElementById(idNames[j] + index);
            parentNode.appendChild(markers[groupName][j]);
        }
    }
}

// get the marker value for the specified locus
function getMarkerValue(locusName)
{
	return document.getElementById('marker_combo_' + locusName).value;
}

// sets a single locus combobox to the specified allele value, in smgf standard
function setMarkerValue(locusName, selection)
{
    setComboValue('marker_combo_' + locusName, selection, 0);
    
    //if the marker set is 389I update 389B
    if (locusName == 'DYS389I')
    	populateMarker('DYS389B', getStandard(), null);
}

function markerChanged(locusName)
{
	// because DYS389B/II is dependent on I we have to handle it special
	if (locusName == 'DYS389I')
		populateMarker('DYS389B', getStandard(), null);
	
    // see if we still have the minimum number of loci
    updateMinLoci();
}

// Populate a single locus' combo box
function populateMarker(locName, standard, previous)
{
    // Get conversion offset
    var labConv = conversion[standard][locName]; // Lab standard conversion
    if (labConv == 'unknown')
        labConv = conversion['NIST'][locName]; // use (NIST standard) if conversion unknown
    var conv = -parseFloat(labConv);
    
	// see if the conversion is the same as the previous one, this speeds up changing the lab standard considerably
	if (previous != null)
	{
	    var prevLabConv = conversion[previous][locName]; // Lab standard conversion
        if (prevLabConv == 'unknown')
            prevLabConv = conversion['NIST'][locName]; // use (NIST standard) if conversion unknown
	    var prevConv = -parseFloat(prevLabConv);
	        
	    if (conv == prevConv && locName != 'DYS389B') // dys389b always needs to be refilled
	    	return;
	}
	
    // get the combo
    var comboBox = document.getElementById('marker_combo_' + locName);
    
    // store the current selection so we can restore it after
    var selection = comboBox.value; // this is always smgf standard

    // Empty current options
    for (var i = comboBox.options.length - 1; i >= 1; --i)
        comboBox.options[i] = null;  // Browser bug workaround

    // populate DYS389B different
    if (locName == 'DYS389B')
    {
    	// get the value for 389I
    	var dys389i = getMarkerValue('DYS389I');
    	
    	// don't put values for 389B if 389I is none
    	if (dys389i == 'None')
    	{
	    	setMarkerValue(locName, 'None');
	        return;
    	}
    	
    	// add the I value to the conversion if the standard uses II
    	if (!uses389B[standard])
    		conv += parseFloat(dys389i);  // DYS389 conversion: DYS389II = DYS389I + DYS389B
    }
    
    // populate combo box
    for (var j = 0; j < alleles[locName].length; j++)
    {
        var smgfAllele = alleles[locName][j];
        var convAllele = convertAllele(locName, smgfAllele, conv);
        comboBox.options[j+1] = new Option(convAllele, smgfAllele);
    }
    
    // restore the selection
    setMarkerValue(locName, selection);
}

// Populate all markers
function populateMarkerValues(standard)
{
    for (var i = 0; i < locusNames.length; i++)
        populateMarker(locusNames[i], standard, previousStandard);
}

function clearMarkerValues()
{
    for (var i = 0; i < locusNames.length; i++)
        setMarkerValue(locusNames[i], 'None');
    
    // update the minimum number of loci
    updateMinLoci();
}

function resetMarkerValues()
{
	setHaplotype(initial);
}

function defaultMarkerValues()
{
	setHaplotype(defaults);
}

function setSearchType(type)
{
	document.getElementById('search_' + type).checked = true;
	searchTypeClicked(type);
}

// search type clicked
function searchTypeClicked(value)
{
	var surname_search = value == 'surname';

	document.getElementById('surname').disabled = !surname_search;
	document.getElementById('surname_exact').disabled = !surname_search;
	document.getElementById('surname_approximate').disabled = !surname_search;
	document.getElementById('surname').className = surname_search ? '' : 'label_disabled text_disabled';
	document.getElementById('surname_labels').className = surname_search ? '' : 'label_disabled';

	document.getElementById('genetic_match_100').disabled = surname_search;
	document.getElementById('genetic_match_85').disabled = surname_search;
	document.getElementById('genetic_match_70').disabled = surname_search;
	document.getElementById('genetic_labels').className = !surname_search ? '' : 'label_disabled';
}

// parses the haplotype cookie
function parseHaplotype(cookie, defaults)
{
	if (cookie == null)
		return defaults;
		
    var initial = new Array();
    for (var i = 0; i < locusNames.length; i++)
    {
        var locName = locusNames[i];
        var patt = '|' + locName + ':';
        var locIdx = cookie.indexOf(patt);
		if (locIdx >= 0)
		{
        	var locEndIdx = cookie.indexOf('|', locIdx + patt.length);
          	if (locEndIdx < 0)
            	locEndIdx = cookie.length;
          	var locVal = cookie.substring(locIdx + patt.length, locEndIdx);
          	initial[locName] = locVal;
		}
	}
	
	// special case for old duplicated loci format
	var duplicated = new Array('DYS385', 'DYS459', 'YCAII');
	for (var i = 0; i < duplicated.length; i++)
	{
		var locName = duplicated[i];
        var patt = '|' + locName + ':';
        var locIdx = cookie.indexOf(patt);
		if (locIdx >= 0)
		{
        	var locEndIdx = cookie.indexOf('|', locIdx + patt.length);
          	if (locEndIdx < 0)
            	locEndIdx = cookie.length;
          	var locVal = cookie.substring(locIdx + patt.length, locEndIdx);
          	// split the value into a and b parts
          	locIdx = locVal.indexOf('-');
          	if (locIdx >= 0)
          	{
          		initial[locName + '_a'] = locVal.substring(0, locIdx);
          		initial[locName + '_b'] = locVal.substring(locIdx+1, locVal.length);
          	}
          	else
          	{
          		// there isn't a b value for some reason, so just use none
          		initial[locName + '_a'] = locVal;
          		initial[locName + '_b'] = 'None';
          	}
		}
	}
	return initial;
}

// sets the default search haplotype
function setHaplotype(alleleValues)
{
    for (var i = 0; i < locusNames.length; i++)
        setMarkerValue(locusNames[i], alleleValues[locusNames[i]]);
    
    // update the minimum number of loci
    updateMinLoci();
}

function updateUnknownMarkerConversion(standard)
{
    // Mark loci that don't have conversion info
    var numAnnotatedLoci = 0;
    for (var i = 0; i < groupNames.length; i++)
    {
        var groupName = groupNames[i];
        var labConv = conversion[standard][groupName]; // Lab standard conversion
        if (labConv == null) // this should be a duplicated loci
        {
        	var index = groupName.indexOf('_');
        	if (index > 0)
        		labConv = conversion[standard][groupName.substring(0, index)+'_a']; // we can just check a because they are all the same
        }
        var mark = (labConv == 'unknown');
        if (mark)
            numAnnotatedLoci++;
        setTextNode('marker_mark_' + groupName, (mark ? '*' : ''));
    }
    
    // Show note about marker conversions if needed
    document.getElementById('noConversionInfo').style.display = (numAnnotatedLoci == 0 ? 'none' : 'block');
}

function updateMinLoci()
{
	var markersWithValues = 0;
	// the group names match the locus names except in the duplicated loci which we have to account for differently anyways
	for (var i = 0; i < groupNames.length; i++)
	{
		var comboBox = document.getElementById('marker_combo_' + groupNames[i]);
		if (comboBox != null && comboBox.selectedIndex > 0)
			markersWithValues++;
	}
	
	// only check the dups if necessary
	if (markersWithValues < minLoci)
	{
		var duplicated = new Array('DYS385', 'DYS459', 'YCAII');
		for (var i = 0; i < duplicated.length; i++)
		{
			var locName = duplicated[i];
			var combo1 = document.getElementById('marker_combo_' + locName + '_a');
			var combo2 = document.getElementById('marker_combo_' + locName + '_b');
			if (combo1.selectedIndex > 0 || combo2.selectedIndex > 0)
				markersWithValues++;
		}
		
		// 464
		var combo464a = document.getElementById('marker_combo_DYS464_a');
		var combo464b = document.getElementById('marker_combo_DYS464_b');
		var combo464c = document.getElementById('marker_combo_DYS464_c');
		var combo464d = document.getElementById('marker_combo_DYS464_d');
		if (combo464a.selectedIndex > 0 || combo464b.selectedIndex > 0 || combo464c.selectedIndex > 0 || combo464d.selectedIndex > 0)
			markersWithValues++;
	}

    // show the note if the number is under the minimum
    document.getElementById("minimumMarkerInfo").style.display = (markersWithValues < minLoci ? 'block' : 'none');
}

// update the 389b label to reflect which variant the standard uses B/II
function updateDYS389B(standard)
{
	setTextNode('marker_href_DYS389B', uses389B[standard] ? 'DYS389B' : 'DYS389II');
}

// update the 635 label to reflect what the standard uses
function updateDYS635(standard)
{
	setTextNode('marker_href_YGATAC4', uses635[standard] ? 'DYS635' : 'Y-GATA-C4');
}

function convertAllele(locName, origAllele, conv)
{
    if (origAllele == 'None')
        return 'None';

    var alleleParts = origAllele.split('-');
    var result = '';
    for (var i = 0; i < alleleParts.length; i++)
    {
        var index = alleleParts[i].indexOf('.');
        if (index < 0)
            index = alleleParts[i].length;
        var wholeRepeats = parseInt(alleleParts[i].substring(0, index), 10) + conv;
        result += (i > 0 ? '-' : '') + wholeRepeats + alleleParts[i].substring(index);
    }
    return result;
}

function setSurname(surname)
{
	document.getElementById('surname').value =  surname;
}

function setSurnameType(type)
{
	document.getElementById('surname_' + type).checked = true;
}

function setMatchPercent(percent)
{
	document.getElementById('genetic_' + percent).checked = true;
}

function setShowSurnames(show)
{
	var bool = show == 'true';
	document.getElementById('show_surnames').checked = bool;
}

function setShowCountry(show)
{
	var bool = show == 'true';
	document.getElementById('show_countries').checked = bool;
}

function setShowMissing(show)
{
	var bool = show == 'true';
	document.getElementById('show_missing').checked = bool;
}
