// Copyright (c) 2010 Erik Juárez.
// File written by Alex Blanca, from Idea.Factor-e.
// alex.blanca@ideafactor-e.com
// Pieces based on code found in http://www.javascript-coder.com/javascript-form/getelementbyid-form.htm
// Additional copyrights may apply, See below.

// Used to generically access elements with the element's IDs.
// Based on code found in http://www.javascript-coder.com/javascript-form/getelementbyid-form.htm
function getElement(id)
{
    if (document.getElementById)
    {
        return document.getElementById(id);
    }
    else if (document.all)
    {
        return window.document.all[id];
    }
    else if (document.layers)
    {
        return window.document.layers[id];
    }
    
    return null;
}

// Legacy Javascript functions begin.
///////////////////////////////////////
// Dubious copyright, but oh well.
// Roshan's Ajax dropdown code with php.
// This notice must stay intact for legal use.
// Copyright reserved to Roshan Bhattarai - nepaliboy007@yahoo.com
// If you have any problem contact me at http://roshanbh.com.np
// Function to obtain XML HTTP Request object.
function getXMLHTTP()
{ 
    // Function to return the xml http object.
    var xmlhttp = false;
    try
    {
        xmlhttp = new XMLHttpRequest();
    }
    catch(e)
    {
        try
        {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(e)
        {
            try
            {
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e1)
            {
                xmlhttp = false;
            }
        }
    }

    return xmlhttp;
}

// Legacy function to obtain state information for a country, through a
// XML HTTP Request object.
// Extended to fix bug 0022. Added parameters
// to specify the output mode of findstate.php and
// to specify the state selector ID in case the mode specified
// is cvs-js. If the latter is cvs-js, the state selector ID
// will be used to dynamically load the selector with new data.
// This was the only way to guarantee that the Spry validator
// would work with this field, when required.
function getState(countryId, mode, stateSelectorId)
{
    if (countryId == -1)
    {
        // No country specified. No case in doing anything of the below.
        // Setting state selector to index 0 (with value -1).
        getElement(stateSelectorId).selectedIndex = 0;
        // Dropping the rest of the invalid elements;
        getElement(stateSelectorId).length = 1;
    }
    else
    {
        var strURL = "findState.php?country=" + countryId + "&mode=" + mode;
        var req = getXMLHTTP();

        if (req)
        {
            // TODO: change this to req.onload.
            req.onreadystatechange =
            function()
            {
                if (req.readyState == 4)
                {
                    // Only if "OK".
                    if (req.status == 200)
                    {
                        if (mode == 'html')
                        {
                            document.getElementById('statediv').innerHTML = req.responseText;
                        }
                        else if (mode == 'csv-js')
                        {
                            // For future reference: http://www.greywyvern.com/?post=258
                            // in case it's required.
                            // Also, it might be a better idea to use json (http://www.json.org/).
                            var responseArray = req.responseText.split(',');
                            var selectElement = getElement(stateSelectorId);
                            // Resetting selector.
                            selectElement.length = 1;
                            // Appending new elements.
                            for (var i = 0; i < responseArray.length; i += 2)
                            {
                                selectElement.options[selectElement.options.length] = new Option(responseArray[i], responseArray[i + 1]);
                            }
                        }
                    }
                    else
                    {
                        alert("There was a problem while using XMLHTTP: " + req.statusText);
                    }
                }
            };
            req.open("GET", strURL, true);
            req.send(null);
        }
    }
}

// Legacy function to obtain city information for a country / state, through a
// XML HTTP Request object.
// Extended to fix bug 0022. Added parameters
// to specify the output mode of findcity.php and
// to specify the city selector ID in case the mode specified
// is cvs-js. If the latter is cvs-js, the city selector ID
// will be used to dynamically load the selector with new data.
// This was the only way to guarantee that the Spry validator
// would work with this field, when required.
function getCity(countryId, stateId, mode, citySelectorId)
{
    if (stateId == -1)
    {
        // No country specified. No case in doing anything of the below.
        // Setting city selector to index 0 (with value -1).
        getElement(citySelectorId).selectedIndex = 0;
        // Dropping the rest of the invalid elements;
        getElement(citySelectorId).length = 1;
    }
    else
    {
        var strURL = "findCity.php?country=" + countryId + "&state=" + stateId + "&mode=" + mode;
        var req = getXMLHTTP();

        if (req)
        {
            // TODO: change this to req.onload.
            req.onreadystatechange =
            function()
            {
                if (req.readyState == 4)
                {
                    // Only if "OK".
                    if (req.status == 200)
                    {
                        if (mode == 'html')
                        {
                            document.getElementById('citydiv').innerHTML = req.responseText;
                        }
                        else if (mode == 'csv-js')
                        {
                            // For future reference: http://www.greywyvern.com/?post=258
                            // in case it's required.
                            // Also, it might be a better idea to use json (http://www.json.org/).
                            var responseArray = req.responseText.split(',');
                            var selectElement = getElement(citySelectorId);
                            // Resetting selector.
                            selectElement.length = 1;
                            // Appending new elements.
                            for (var i = 0; i < responseArray.length; i += 2)
                            {
                                selectElement.options[selectElement.options.length] = new Option(responseArray[i], responseArray[i + 1]);
                            }
                        }
                    }
                    else
                    {
                        alert("There was a problem while using XMLHTTP: " + req.statusText);
                    }
                }
            };
            req.open("GET", strURL, true);
            req.send(null);
        }
    }
}

///////////////////////////////////////
// Legacy functions finished.

// Added to fix bug-0034.
// Function that calls getState and cleanups city field properly.
// VERY specific to this site.
// Added parameters to fix bug-0022: format represents the format of
// of the xmlhttprequest: html or csv-js. If it's html, the response will
// be output in HTML and will be directly written to the appropriate div.
// If the format is CSV-JS, the output will be a CSV list that will be used
// by a script to dynamically load the selector identified by stateSelectorId.
function getStateAndResetCity(countryId, citySelectorId, format, stateSelectorId)
{
    // Setting city selector to index 0 (with value -1).
    getElement(citySelectorId).selectedIndex = 0;
    // Dropping the rest of the invalid elements;
    getElement(citySelectorId).length = 1;
    // Setting state selector to index 0 (with value -1).
    getElement(stateSelectorId).selectedIndex = 0;
    // Dropping the rest of the invalid elements;
    getElement(stateSelectorId).length = 1;
    // Getting states corresponding to the new country.
    getState(countryId, format, stateSelectorId);
}
