// declare a global  XMLHTTP Request object
var XmlHttpObj;
var cityList = null;
var weeksList = null;
var provinceList = null;
var communityList = null;
var usersList = null;
var childcareCentreList = null

// create an instance of XMLHTTPRequest Object, varies with browser type, try for IE first then Mozilla
function CreateXmlHttpObj()
{
    // try creating for IE (note: we don't know the user's browser type here, just attempting IE first.)
    try
    {
        XmlHttpObj = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            XmlHttpObj = new ActiveXObject("Microsoft.XMLHTTP");
        } 
        catch(oc)
        {
            XmlHttpObj = null;
        }
    }
    // if unable to create using IE specific code then try creating for Mozilla (FireFox) 
    if(!XmlHttpObj && typeof XMLHttpRequest != "undefined") 
    {
        XmlHttpObj = new XMLHttpRequest();
    }
}

// called from onChange or onClick event of the continent dropdown list
function provinceListOnChange(pl, cl)
{
    cityList = cl;
    provinceList = pl;
    
    // get selected continent from dropdown list
    var selectedProvince = provinceList.options[provinceList.selectedIndex].value;
    
    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp

var fullURL = parent.document.URL 
var lang = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length) 

    requestUrl = "/system/include/xml_city_provider.php" + "?filter=" + encodeURIComponent(selectedProvince) + "&" + lang;
    // use the following line if using php
    // requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent);
    
    CreateXmlHttpObj();
    
    // verify XmlHttpObj variable was successfully initialized
    if(XmlHttpObj)
    {
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
        XmlHttpObj.onreadystatechange = ProvinceChangeHandler;
        
        // define the iteraction with the server -- true for as asynchronous.
        XmlHttpObj.open("GET", requestUrl,  true);
        
        // send request to server, null arg  when using "GET"
        XmlHttpObj.send(null);        
    }
}

function communitiesListOnChange(cl, ul, ccl, obs_flag, sur_type, pre_post, edit)
{
    communityList = cl;
    usersList = ul;
    childcareCentreList = ccl;
    
    // get selected continent from dropdown list
    var selectedCommunity = communityList.options[communityList.selectedIndex].value;
    
    if( selectedCommunity == '' )
    {
        usersList.options.length = 1;
        childcareCentreList.options.length = 1;
        return true;
    }
    
    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp
    
    var survey_param = '';
    if( sur_type != '' )
    {
        survey_param = '&survey_type=' + sur_type;
    }

    var edit_param = '';
    if( edit != '' )
    {
        edit_param = '&edit=' + edit;
    }

    var pre_post_param = '';
    switch(pre_post)
    {
        case 0:
        case '0':
        case 1:
        case '1':
            pre_post_param = '&pre_post=' + pre_post;
            break;
        default:
            pre_post_param = '';
    }
    //alert('Pre/Post: ' + pre_post);
    
    requestUrl = "/system/include/xml_usernames_provider.php" + "?community=" + encodeURIComponent(selectedCommunity) + "&obs_flag=" + obs_flag + survey_param + pre_post_param + edit_param;
    
    //alert(requestUrl);
    // use the following line if using php
    // requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent);
    
    CreateXmlHttpObj();
    
    // verify XmlHttpObj variable was successfully initialized
    if(XmlHttpObj)
    {
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
        XmlHttpObj.onreadystatechange = CommunityChangeHandler;
        
        // define the iteraction with the server -- true for as asynchronous.
        XmlHttpObj.open("GET", requestUrl,  true);
        
        // send request to server, null arg  when using "GET"
        XmlHttpObj.send(null);        
    }
}


function usersListOnChange(cl, ul, ccl, obs_flag)
{
    communityList = cl;
    usersList = ul;
    childcareCentreList = ccl;
    
    // get selected continent from dropdown list
    var selectedUser = usersList.options[usersList.selectedIndex].value;
    
    if( selectedUser == '' )
    {
        childcareCentreList.options.length = 1;
        return true;
    }
    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp

    requestUrl = "/system/include/xml_centre_provider.php" + "?user_id=" + encodeURIComponent(selectedUser) + "&obs_flag=" + obs_flag;
    // use the following line if using php
    // requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent);
    
    CreateXmlHttpObj();
    
    // verify XmlHttpObj variable was successfully initialized
    if(XmlHttpObj)
    {
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
        XmlHttpObj.onreadystatechange = UserChangeHandler;
        
        // define the iteraction with the server -- true for as asynchronous.
        XmlHttpObj.open("GET", requestUrl,  true);
        
        // send request to server, null arg  when using "GET"
        XmlHttpObj.send(null);        
    }
}


// called from onChange or onClick event of the continent dropdown list
function phaseListOnChange(pl, wl)
{
    
    if( wl == null )
    {
        return;
    }
    weeksList = wl;
    phaseList = pl;

    // get selected continent from dropdown list
    var selectedPhase = phaseList.options[phaseList.selectedIndex].value;

    // url of page that will send xml data back to client browser
    var requestUrl;
    // use the following line if using asp

    var fullURL = parent.document.URL 
    var lang = fullURL.substring(fullURL.indexOf('?')+1, fullURL.length) 

    requestUrl = "/system/include/xml_weeks_provider.php" + "?filter=" + encodeURIComponent(selectedPhase) + "&" + lang;
    // use the following line if using php
    // requestUrl = "xml_data_provider.php" + "?filter=" + encodeURIComponent(selectedContinent);

    CreateXmlHttpObj();

    // verify XmlHttpObj variable was successfully initialized
    if(XmlHttpObj)
    {
        // assign the StateChangeHandler function ( defined below in this file)
        // to be called when the state of the XmlHttpObj changes
        // receiving data back from the server is one such change
        XmlHttpObj.onreadystatechange = PhaseChangeHandler;

        // define the iteraction with the server -- true for as asynchronous.
        XmlHttpObj.open("GET", requestUrl,  true);

        // send request to server, null arg  when using "GET"
        XmlHttpObj.send(null);        
    }

}

// this function called when state of  XmlHttpObj changes
// we're interested in the state that indicates data has been
// received from the server
function ProvinceChangeHandler()
{
    // state ==4 indicates receiving response data from server is completed
    if(XmlHttpObj.readyState == 4)
    {
        // To make sure valid response is received from the server, 200 means response received is OK
        if(XmlHttpObj.status == 200)
        {    
            //alert(XmlHttpObj.responseText);
            PopulateCityList(XmlHttpObj.responseXML.documentElement);
        }
        else
        {
            alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
        }
    }

}

function CommunityChangeHandler()
{
    // state ==4 indicates receiving response data from server is completed
    if(XmlHttpObj.readyState == 4)
    {
        // To make sure valid response is received from the server, 200 means response received is OK
        if(XmlHttpObj.status == 200)
        {    
            //alert(XmlHttpObj.responseText);
            PopulateUsersList(XmlHttpObj.responseXML.documentElement);
        }
        else
        {
            alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
        }
    }

}

function UserChangeHandler()
{
    // state ==4 indicates receiving response data from server is completed
    if(XmlHttpObj.readyState == 4)
    {
        // To make sure valid response is received from the server, 200 means response received is OK
        if(XmlHttpObj.status == 200)
        {    
            //alert(XmlHttpObj.responseText);
            PopulateCentreList(XmlHttpObj.responseXML.documentElement);
        }
        else
        {
            alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
        }
    }

}

function PhaseChangeHandler()
{
    // state ==4 indicates receiving response data from server is completed
    if(XmlHttpObj.readyState == 4)
    {
        // To make sure valid response is received from the server, 200 means response received is OK
        if(XmlHttpObj.status == 200)
        {    
            //alert(XmlHttpObj.responseText);
            PopulateWeeksList(XmlHttpObj.responseXML.documentElement);
        }
        else
        {
            alert("problem retrieving data from the server, status code: "  + XmlHttpObj.status);
        }
    }

}

// populate the contents of the province dropdown list
function PopulateCityList(provinceNode)
{
    // clear the target list 
    cityList.options.length = 1;

    var cityNodes = provinceNode.getElementsByTagName('city');
    var idValue;
    var textValue; 
    var optionItem;

    //optionItem = new Option( txtSelectOne, '',  false, false );
    //cityList.options[cityList.length] = optionItem;

    // populate the dropdown list with data from the xml doc
    for (var count = 0; count < cityNodes.length; count++)
    {
           textValue = GetInnerText(cityNodes[count]);
        idValue = cityNodes[count].getAttribute("id");
        optionItem = new Option( textValue, idValue,  false, false );
        cityList.options[cityList.length] = optionItem;
    }

}

function PopulateUsersList(communityNode)
{
    // clear the target list(s) 
    usersList.options.length = 1;
    /*var optgroups = document.getElementsByTagName('optgroup');
    var at_least_one_found = true;
    while(optgroups.length > 0 && at_least_one_found == true)
    {
        for(var i=0; i<optgroups.length; i++)
        {
            //alert(optgroups[i].getAttribute('label'));
            if( optgroups[i].parentNode.getAttribute('id') == 'supervisor_id' )
            {
                optgroups[i].parentNode.removeChild(optgroups[i]);
            }
        }
        at_least_one_found = false;
    }*/
    childcareCentreList.options.length = 1;

    var userNodes = communityNode.getElementsByTagName('user');
    var centreNodes = communityNode.getElementsByTagName('centre');
    
    var idValue;
    var idValueTmp;
    var textValue; 
    var optionItem;
    var groupId;
    
    /*
    var optgroupMentors = document.createElement('optgroup');
    var optgroupMentees = document.createElement('optgroup');
    
    optgroupMentors.setAttribute('label', 'Mentors');
    optgroupMentees.setAttribute('label', 'Mentees');
    //*/
    var optgroupMentors = document.getElementById('optgroupMentors');
    var optgroupMentees = document.getElementById('optgroupMentees');
    
    // populate the dropdown list with data from the xml doc
    for (var count = 0; count < userNodes.length; count++)
    {
        textValue = GetInnerText(userNodes[count]);
        idValueTmp = userNodes[count].getAttribute("id").split(':');
        groupId = idValueTmp[0];
        idValue = idValueTmp[1];
        optionItem = new Option( textValue, idValue,  false, false );
        //alert(textValue);
        /*switch(groupId)
        {
            case '6':
                //alert('Mentor ' + optgroupMentors.id);
                optgroupMentors.appendChild(optionItem);
                break;
            case '7':
                //alert('Mentee ' + optgroupMentees.id);
                optgroupMentees.appendChild(optionItem);
                break;
            default:
                //alert(groupId);
                usersList.options[usersList.length] = optionItem;
        }*/               
        usersList.options[usersList.length] = optionItem;
    }
    //usersList.appendChild(optgroupMentors);
    //usersList.appendChild(optgroupMentees);
    
    // populate the dropdown list with data from the xml doc
    for (var count = 0; count < centreNodes.length; count++)
    {
        textValue = GetInnerText(centreNodes[count]);
        idValue = centreNodes[count].getAttribute("id");
        optionItem = new Option( textValue, idValue,  false, false );
        childcareCentreList.options[childcareCentreList.length] = optionItem;
    }
    
}

function PopulateCentreList(userNode)
{
    // clear the target list(s) 
    childcareCentreList.options.length = 1;

    var centreNodes = userNode.getElementsByTagName('centre');
    
    var idValue;
    var textValue; 
    var optionItem;
    
    // populate the dropdown list with data from the xml doc
    for (var count = 0; count < centreNodes.length; count++)
    {
        textValue = GetInnerText(centreNodes[count]);
        idValue = centreNodes[count].getAttribute("id");
        optionItem = new Option( textValue, idValue,  false, false );
        childcareCentreList.options[childcareCentreList.length] = optionItem;
    }
    
}

function PopulateWeeksList(phaseNode)
{
    // clear the target list 
    weeksList.options.length = 1;

    var weeksNodes = phaseNode.getElementsByTagName('week');
    var idValue;
    var textValue; 
    var optionItem;

    // populate the dropdown list with data from the xml doc
    for (var count = 0; count < weeksNodes.length; count++)
    {
        textValue = GetInnerText(weeksNodes[count]);
        idValue = weeksNodes[count].getAttribute("id");
        optionItem = new Option( textValue, idValue,  false, false );
        weeksList.options[weeksList.length] = optionItem;
    }
}

// returns the node text value 
function GetInnerText (node)
{
     return (node.textContent || node.innerText || node.text) ;
}
