﻿//<using>
//  nui/nui.js
//  nui/prototype.js
//  nui/lang.js
//  nui/util.js
//  nui/ajax.js
//  nui/widget.js
//</using>

/**
 * Location. How to use ?
 *  var node = NUI.Widget.Input.Location(function(vCountry, vProvince, vCity) {
 *      alert(vCity.id + "_" + vProvince.id + "_" + vCity.id);});
 *  node.appendTo("conId");
 */
NUI.Widget.Input.Location = (function() {
    var g_dom = NUI.Util.DomService,
        g_ajax = NUI.Ajax,
        g_ht = NUI.Util.DataStructure.HashTable,
        g_sb = NUI.Util.StringService.StringBuilder,
        g_countriesCache = null,
        g_provincesCache = new g_ht(),
        g_citiesCache = new g_ht();
        
    /**
     * Get the country list
     * @param vFunc {function}. The function to construct the country-select-input after getting the country list
     */
    function _getCountryList(vFunc) {
        var m_func = vFunc ? vFunc : function() {};
        if(g_countriesCache != null) {
            m_func(g_countriesCache);
            return;
        }
        g_ajax.call("GetCountryList", {
            args : [],
            func : {
                success : function(vCountries) {
                    if(g_countriesCache != null) {
                        m_func(g_countriesCache);
                    } else {
                        if(vCountries != null) {
                            g_countriesCache = vCountries;
                            m_func(vCountries);
                        } else {
                            m_func([]);
                        }
                    }
                }
            }
        });
    }
    /**
     * Get the province list
     * @param vCountryId {int}. The id of the country
     * @param vFunc {function}. The function to construct the province-select-input after getting the province list
     */
    function _getProvinceList(vCountryId, vFunc) {
        var m_func = vFunc ? vFunc : function() {};
        if(vCountryId == -2) {
            m_func([]);
            return;
        }
        if(g_provincesCache.exist(vCountryId)) {
            m_func(g_provincesCache.getValue(vCountryId));
            return;
        }
        g_ajax.call("GetProvinceList", {
            args : [vCountryId],
            func : {
                success : function(vProvinces) {
                    if(g_provincesCache.exist(vCountryId)) {
                        m_func(g_provincesCache.getValue(vCountryId));
                    } else {
                        if(vProvinces != null) {
                            g_provincesCache.setValue(vCountryId, vProvinces);
                            m_func(vProvinces);
                        } else {
                            m_func([]);
                        }
                    }
                }
            }
        });
    }
    /**
     * Get the city list
     * @param vCountryId {int}. The id of the country
     * @param vProvinceId {int}. The id of the province
     * @param vFunc {function}. The function to construct the province-select-input after getting the province list
     */
    function _getCityList(vCountryId, vProvinceId, vFunc) {
        var m_func = vFunc ? vFunc : function() {};
        if(vCountryId == -2 || vProvinceId == -2) {
            m_func([]);
            return;
        }
        var key = vCountryId + "_" + vProvinceId;
        if(g_citiesCache.exist(key)) {
            m_func(g_citiesCache.getValue(key));
            return;
        }
        g_ajax.call("GetCityList", {
            args : [vCountryId, vProvinceId],
            func : {
                success : function(vCities) {
                    if(g_citiesCache.exist(key)) {
                        m_func(g_citiesCache.getValue(key));
                    } else {
                        if(vCities != null) {
                            g_citiesCache.setValue(key, vCities);
                            m_func(vCities);
                        } else {
                            m_func([]);
                        }
                    }
                }
            }
        });
    }
    
    /**
     * @class NUI.Widget.Input.Location 
     * @param vFunc(vCountry, vProvince, vCity) {function}. The function to execute after choosing the target city
     * @param vAttributes {object}.
     *      vAttributes = {
     *          initValue : {           // only for (isMultipleCity == false)
     *              country : {int},
     *              province : {int},
     *              city : {int}
     *          },
     *          isMultipleCity : {boolean}
     *      }
     */
    return function(vFunc, vAttributes) {
        var m_secret = {},
            m_func = vFunc ? vFunc : function() {},
            m_attribute = vAttributes ? vAttributes : {
                isMultipleCity : false
            },
            m_initValue = m_attribute.initValue ? m_attribute.initValue : {
                country : -2,   // here, since -1 is used by "其他地区" for countries except China, we can not use it
                province : -2,
                city : -2
            };
        
        var m_country = null,
            m_province = null,
            m_city = null;
            
        function _setuplist(vNode, vArealist, vInitValue) {
            if(!vNode || !vArealist) {
                return;
            }
            g_dom.removeChildren(vNode);
            var count = vArealist.length;
            for(var i=0; i<count; i++) {
                var area = vArealist[i];
                if(area == null) {
                    continue;
                }
                var opt = g_dom.createNode("option", {
                    value : area.id
                });
                if(vInitValue == opt.value) {
                    g_dom.setAttributes(opt, {
                        selected : "selected"
                    });
                }
                g_dom.setInnerHTML(opt, area.caption);
                g_dom.appendNode(vNode, opt);
            }
        }
        /**
         * Setup the country/province/city list
         */
        function _setupCountryList() {
            if(!m_countrySelect) {
                return;
            }
            m_secret.showMsg("正在获取国家信息...");
            _getCountryList(function(vArealist) {
                m_secret.showMsg("");
                if(vArealist != null) {
                    if(!m_attribute.isMultipleCity && (vArealist.length==0 || vArealist[0].id!=-2)) {
                        vArealist.addAt(0, {
                            id : -2,
                            caption : "--请选择--"
                        });
                    }
                    if(vArealist.length == 0) {
                        return;
                    }
                    m_country = {
                        id : vArealist[0].id,
                        caption : vArealist[0].caption
                    };
                    if(!m_attribute.isMultipleCity) {
                        for(var i=0; i<vArealist.length; i++) {
                            if(vArealist[i].id == m_initValue.country) {
                                m_country = {
                                    id : vArealist[i].id,
                                    caption : vArealist[i].caption
                                };
                                break;
                            }
                        }
                    }
                    _setuplist(m_countrySelect, vArealist, m_country.id);
                    _setupProvinceList(m_country);
                }
            });
        }
        /**
         * Setup the country/province/city list
         */
        function _setupProvinceList(vCountry) {
            if(!m_provinceSelect || !vCountry) {
                return;
            }
            var vCountryId = vCountry.id;
            m_secret.showMsg("正在获取省份信息...");
            _getProvinceList(vCountryId, function(vArealist) {
                m_secret.showMsg("");
                if(vArealist != null) {
                    if(!m_attribute.isMultipleCity && (vArealist.length==0 || vArealist[0].id!=-2)) {
                        vArealist.addAt(0, {
                            id : -2,
                            caption : "--请选择--"
                        });
                    }
                    if(vArealist.length == 0) {
                        return;
                    }
                    m_province = {
                        id : vArealist[0].id,
                        caption : vArealist[0].caption
                    };
                    if(!m_attribute.isMultipleCity) {
                        if(vCountryId==m_initValue.country) {
                            for(var i=0; i<vArealist.length; i++) {
                                if(vArealist[i].id == m_initValue.province) {
                                    m_province = {
                                        id : vArealist[i].id,
                                        caption : vArealist[i].caption
                                    };
                                    break;
                                }
                            }
                        }
                    }
                    _setuplist(m_provinceSelect, vArealist, m_province.id);
                    _setupCityList(m_country, m_province);
                }
            });
        }
        /**
         * Setup the country/province/city list
         * @param vNode {object}. The select input
         */
        function _setupCityList(vCountry, vProvince) {
            if(!m_citySelect || !vCountry || !vProvince) {
                return;
            }
            var vCountryId = vCountry.id,
                vProvinceId = vProvince.id;
            m_secret.showMsg("正在获取城市信息...");
            _getCityList(vCountryId, vProvinceId, function(vArealist) {
                m_secret.showMsg("");
                if(vArealist != null) {
                    if(m_attribute.isMultipleCity) {
                        _setuplist(m_citySelect, vArealist, -2);
                    } else {
                        if(vArealist.length==0 || vArealist[0].id!=-2) {
                            vArealist.addAt(0, {
                                id : -2,
                                caption : "--请选择--"
                            });
                        }
                        m_city = {
                            id : vArealist[0].id,
                            caption : vArealist[0].caption
                        };
                        if(vCountryId==m_initValue.country && vProvinceId==m_initValue.province) {
                            for(var i=0; i<vArealist.length; i++) {
                                if(vArealist[i].id == m_initValue.city) {
                                    m_city = {
                                        id : vArealist[i].id,
                                        caption : vArealist[i].caption
                                    };
                                    break;
                                }
                            }
                        }
                        _setuplist(m_citySelect, vArealist, m_city.id);
                    }
                }
            });
        }
        
        var that = NUI.Widget.Input.Base(m_secret),
            m_id = m_secret.id,
            m_citySelect = g_dom.createNode("select", {
                style : {
                    width : "150px"
                },
                onchange : function() {
                    var options = m_citySelect.options;
                    for(var i=0; i<options.length; i++) {
                        var opt = options[i];
                        if(opt.selected) {
                            m_city = {
                                id : opt.value,
                                caption : opt.innerHTML
                            };
                            m_func(m_country, m_province, m_city);
                        }
                    }
                }
            }),
            m_provinceSelect = g_dom.createNode("select", {
                style : {
                    width : "150px"
                },
                onchange : function() {
                    var value = m_provinceSelect.value;
                    if(value != m_province) {
                        var caption = null;
                        var provincelist = g_provincesCache.getValue(m_country.id);
                        if(provincelist == null) {
                            return;
                        }
                        for(var i=0; i<provincelist.length; i++) {
                            if(provincelist[i].id == value) {
                                caption = provincelist[i].caption;
                                break;
                            }
                        }
                        if(caption == null) {
                            return;
                        }
                        m_province = {
                            id : value,
                            caption : caption
                        };
                        _setupCityList(m_country, m_province);
                    }
                }
            }),
            m_countrySelect = g_dom.createNode("select", {
                style : {
                    width : "150px"
                },
                onchange : function() {
                    var value = m_countrySelect.value;
                    if(value != m_country) {
                        var caption = null;
                        var countrylist = g_countriesCache;
                        if(countrylist == null) {
                            return;
                        }
                        for(var i=0; i<countrylist.length; i++) {
                            if(countrylist[i].id == value) {
                                caption = countrylist[i].caption;
                                break;
                            }
                        }
                        if(caption == null) {
                            return;
                        }
                        m_country = {
                            id : value,
                            caption : caption
                        };
                        _setupProvinceList(m_country);
                    }
                }
            }),
            m_nodeDom = (function() {
                var retval = m_secret.node
                    body = g_dom.createNode("div", {
                        className : "location"
                    });
                g_dom.appendNode(body, m_countrySelect);
                g_dom.appendNode(body, m_provinceSelect);
                g_dom.appendNode(body, m_citySelect);
                g_dom.appendNode(retval, body);
                return retval;
            })();
            
        if(m_attribute.isMultipleCity) {
            g_dom.setAttributes(m_countrySelect, {
                size : "10"
            });
            g_dom.setAttributes(m_provinceSelect, {
                size : "10"
            });
            g_dom.setAttributes(m_citySelect, {
                size : "10",
                multiple : "multiple"
            });
        }
        _setupCountryList();
        
        NUI.Util.ObjectService.annex(that, { 
            nodeEntity : m_nodeDom,
            
            /** 
             * Reset the onclick event
             */
            resetEvent : function(vFunc) {
                m_func = vFunc ? vFunc : function() {};
            }
        });
        
        /**
         * Set note
         */
        (function() {
            var html = "(请在下面列表里选择地区)";
            m_secret.setNote(html);
        })();
        
        return that;
    };
})();

