
var Namespace = new function() {

    function TimeZoneChooser(root_div, callback_function) {
        this.root_div = root_div;
        this.callback_function = callback_function;
        this.timezone_name = '';
        this.timezone_tzname = '';
        this.build_loading();
        this.load();
    }

    TimeZoneChooser.prototype.build_loading = function() {
        this.tz_div = document.createElement("div");
        set_class(this.tz_div, "timezone_choose_div");
        this.loading_div = document.createElement("div");
        set_class(this.loading_div, "timezone_loading");
        this.loading_div.innerHTML = "načítavám..";
        this.tz_div.appendChild(this.loading_div);
        this.root_div.appendChild(this.tz_div);
    }

    TimeZoneChooser.prototype.destroy_loading_div = function() {
        if (this.loading_div) {
            this.tz_div.removeChild(this.loading_div);
        }
    }

    TimeZoneChooser.prototype.build_list = function() {
        var self_bl = this;
        this.destroy_loading_div();
        for (var i=0; i<this.cities.length; i++) {
            var city = this.cities[i];
            var item = document.createElement("a");
            set_class(item, "timezone_item clickable");
            item.data = i;
            item.onclick = function() { self_bl['timezone_click'](this); return false; };
            item.innerHTML = city[0];
            this.tz_div.appendChild(item);
            this.tz_div.appendChild(document.createElement("br"));
        }
    }

    TimeZoneChooser.prototype.clean_tz_div = function() {
        this.root_div.removeChild(this.tz_div);
    }

    TimeZoneChooser.prototype.timezone_click = function(param) {
        var number = parseInt(param.data);
        var tz = this.cities[number];
        this.clean_tz_div();
        var self_tzc = this;
        this.timezone_name = tz[0];
        this.timezone_tzname = tz[1];
        setTimeout(function() { self_tzc['callback_function'](self_tzc); }, 0);
    }

    TimeZoneChooser.prototype.received = function(req) {
        var response = req.xmlhttp.responseText;
        this.timezones = eval(response);
        this.build_list();
    }

    TimeZoneChooser.prototype.load = function() {
        jQuery.ajax({
            url: '/cities',
            context: this,
            success: function(data) {
                this.cities = eval(data);
                this.build_list();
            }
        });
    }

    return {
        TimeZoneChooser: TimeZoneChooser
    }
}

var TimeZoneChooser = Namespace.TimeZoneChooser;

