// jquery must be loaded

function populateInstitutions()
{
	// the following are defined by perl:
	// window.defaultInstId = ...;
	// window.defaultInst = ...;
	// window.insts = [...];
	// window.countries = [...];
	// window.states = [...];
	// window.forSearch = ...;
	// window.searchCountryId, searchStateId, searchInstitutionId = ...;
	window.countryHash = {}; // inst by country
	window.stateHash = {}; // inst by state
	
	for (var i = 0; i < countries.length; i++)
	{
		countryHash[countries[i]] = [];
	}
	
	for (var i = 0; i < states.length; i++)
	{
		stateHash[states[i]] = [];
	}
	
}

function getSelects()
{
	return { countries:document.getElementById(window.forSearch ? window.searchCountryId : 'institution_country'), states:document.getElementById(window.forSearch ? window.searchStateId : 'institution_state'), institutions:document.getElementById(window.forSearch ? window.searchInstitutionId : 'institution_popup') };
}

function getInstMsgDiv() 
{
        return document.getElementById('institution_msg');
}

function initInstitutions()
{
	populateInstitutions();

	var selects = getSelects();

	if (!selects.countries)
	{
		return;
	}

	var chooseCountry = new Option();
	var chooseState = new Option();
	var chooseInst = new Option();

	chooseCountry.text = forSearch ? "ANY" : "CHOOSE A COUNTRY";
	selects.countries.options[selects.countries.options.length] = chooseCountry;

        var outreachFlag = document.getElementById("search_outreach_flag");
        if (outreachFlag && outreachFlag.value == 1) 
        {
                // add outreach options
                var usOnly = new Option();
                usOnly.text = 'Everywhere except USA';
                usOnly.value = 'NOTUSA';
                selects.countries.options[selects.countries.options.length] = usOnly;

                var developingNations = new Option();
                developingNations.text = 'Developing Nations';
                developingNations.value = 'DEVELOPING';
                selects.countries.options[selects.countries.options.length] = developingNations;
        }
        
	chooseState.text = forSearch ? "ANY" : "CHOOSE A STATE";
	selects.states.options[selects.states.options.length] = chooseState;
	selects.states.disabled = (!defaultInst || defaultInst[2] != 'USA');
	if (!defaultInst || defaultInst[2] != 'USA')
        {
                selects.states.length = 1;
        }
        else
        {
                populateStates(selects);
        }

	chooseInst.text = forSearch ? "ANY" : "CHOOSE AN INSTITUTION";
	selects.institutions.options[selects.institutions.options.length] = chooseInst;
	selects.institutions.disabled = !defaultInst;

	if (document.all)
	{
		selects.countries.attachEvent('onchange', changeCountry);
		selects.states.attachEvent('onchange', changeState);
		selects.institutions.attachEvent('onchange', changeInstitution);
	}
	else
	{
		selects.countries.addEventListener('change', changeCountry, true);
		selects.states.addEventListener('change', changeState, true);
		selects.institutions.addEventListener('change', changeInstitution, true);
	}

	for (var i = 0; i < countries.length; i++)
	{
		var country = new Option();

		country.text = countries[i];

		selects.countries.options[selects.countries.options.length] = country;

		if (defaultInst && (defaultInst[2] == countries[i]))
		{
			selects.countries.selectedIndex = selects.countries.options.length - 1;
		}
	}
        if (defaultInst && defaultInst[2] == 'NOTUSA') 
        {
                selects.countries.selectedIndex = 1;
        }
        else if (defaultInst && defaultInst[2] == 'DEVELOPING')
        {
                selects.countries.selectedIndex = 2;
        }
        
	populateStates(selects);

	if (defaultInst)
	{
//		populateInsts((defaultInst[2] == 'USA' ? stateHash[defaultInst[3]] : countryHash[defaultInst[2]]), defaultInst[1]);
		populateInsts(defaultInst[2], defaultInst[3], defaultInst[1]);
	}
}

function populateStates(selects)
{
        for (var i = 0; i < states.length; i++)
	{
		var state = new Option();

		state.text = states[i];

		selects.states.options[selects.states.options.length] = state;

		if (defaultInst && (defaultInst[2] == 'USA' && defaultInst[3] == states[i]))
		{
			selects.states.selectedIndex = selects.states.options.length - 1;
		}
	}
}

function changeCountry()
{
	var selects = getSelects();
	var country = selects.countries.options[selects.countries.selectedIndex].text;

	selects.states.selectedIndex = 0;
	selects.states.disabled = (selects.countries.selectedIndex == 0 || country != 'USA');
        if (selects.countries.selectedIndex == 0 || country != 'USA')
        {
                selects.states.length = 1;
        }
        else 
        {
                populateStates(selects);
        }

        if (selects.countries.selectedIndex == 0 || country == 'USA')
        {
                selects.institutions.disabled = true;
                selects.institutions.options.length = 1;
	}
	else
	{
//		populateInsts(countryHash[country]);
		populateInsts(country);
	}

	// changeInstitution() won't fire when there are no institutions
	//   available, leaving you with no option to create a new one...
	changeInstitution();
}

function changeState()
{
	var selects = getSelects();

        if (!selects.states.selectedIndex)
	{
                select.institutions.disabled = true;
		selects.institutions.options.length = 1;
	}
	else
	{
//		populateInsts(stateHash[selects.states.options[selects.states.selectedIndex].text]);
		populateInsts('USA', selects.states.options[selects.states.selectedIndex].text);
	}

	// changeInstitution() won't fire when there are no institutions
	//   available, leaving you with no option to create a new one...
	changeInstitution();
}

function changeInstitution()
{
	if (window.forSearch)
	{
		return true;
	}

	var selects = getSelects();
        var instSelectedIdx
        if ((instSelectedIdx = selects.institutions.selectedIndex) > 0) {
                var instSelectedValue = selects.institutions.options[instSelectedIdx].value;
                var instRow = document.getElementById('other_row');
                if (instSelectedValue == -1 && instRow) 
                {
                        try {
                                instRow.style.display='table-row';
                        } catch(e) {
                                instRow.style.display = 'block';
                        }
                }
                else if (instRow) 
                {
                        instRow.style.display = 'none';
                }
        }
}

function populateInsts(country, state, defaultInst)
{
	if (!country)
	{
		return;
	}

        var msgDiv = getInstMsgDiv();
        msgDiv.innerHTML = "<b><font size=-1>Fetching institution data...</font></b>";
        getSelects().institutions.disabled = true;

        $.ajax({ type: "POST",
                 url: window.instAjaxCgi,
                 data: "institution_country=" + country + "&institution_state=" + state,
                 dataType: "xml",
                 success:  function(xml) 
                 {
                 var selects = getSelects();
                 
                 selects.institutions.options.length = 1;
                 var institutions = xml.getElementsByTagName('institution');
                 for (var i = 0;  i < institutions.length; i++) 
                 {
                         var inst = institutions[i];
                         var option = new Option();
                         
                         option.text = inst.firstChild ? unescape(inst.firstChild.nodeValue) : '';
                         option.value = inst.getAttribute('oid');
                         //   alert(defaultInst);
                         //alert(inst.firstChild.nodeValue);
                         selects.institutions.options[selects.institutions.options.length] = option;
                         if (defaultInstId && option.value == unescape(defaultInstId))
                         {
                                 selects.institutions.selectedIndex = selects.institutions.options.length - 1;
                         }

                         if (window.forSearch && !defaultInstId)
                         {
                                 selects.institutions.selectedIndex = 0;
                         }
                 } 
                 // add Other institution
                 if (document.getElementById('other_row'))
                 {
                         var option = new Option();
                         option.text = 'Other';
                         option.value = -1;
                         selects.institutions.options[selects.institutions.options.length] = option;
                 }

                 if (!window.forSearch && selects.institutions.options.length == 2)
                 {
                         // only have Other option, so select Other and make textfield visible
                         selects.institutions.selectedIndex = 1;
                         var otherRow = document.getElementById('other_row');
                         if (otherRow)
                         {
                                 try {
                                         otherRow.style.display='table-row';
                                 } catch(e) {
                                         otherRow.style.display = 'block';
                                 }
                         }
                 }
                 else
                 {
                         var otherRow = document.getElementById('other_row');
                         if (otherRow)
                         {
                                 otherRow.style.display = 'none';
                         }
                 }
                 getInstMsgDiv().innerHTML = "";  
                 getSelects().institutions.disabled = false; //need to add cases for USA and CHOOSE
                 } // end success function
                
                }
              );
/* 	var selects = getSelects(); */
	
/* 	selects.institutions.options.length = 1; */

/* 	for (var i = 0; i < instList.length; i++) */
/* 	{ */
/* 		var option = new Option(); */
		
/* 		option.text = unescape(instList[i][1]); */
/* 		option.value = instList[i][0]; */

/* 		selects.institutions.options[selects.institutions.options.length] = option; */

/* 		if (defaultInst && defaultInst == instList[i][1]) */
/* 		{ */
/* 			selects.institutions.selectedIndex = selects.institutions.options.length - 1; */
/* 		} */
/* 	} */
}

/* function populateInsts(instList, defaultInst) */
/* { */
/* 	if (!instList) */
/* 	{ */
/* 		return; */
/* 	} */

/* 	var selects = getSelects(); */
	
/* 	selects.institutions.options.length = 1; */

/* 	for (var i = 0; i < instList.length; i++) */
/* 	{ */
/* 		var option = new Option(); */
		
/* 		option.text = unescape(instList[i][1]); */
/* 		option.value = instList[i][0]; */

/* 		selects.institutions.options[selects.institutions.options.length] = option; */

/* 		if (defaultInst && defaultInst == instList[i][1]) */
/* 		{ */
/* 			selects.institutions.selectedIndex = selects.institutions.options.length - 1; */
/* 		} */
/* 	} */
/* } */
