var request = new XMLHttpRequest() 
var selects = document.querySelector('.selects');
var weatherDiv = document.querySelector('.weather');
request.open('GET', 'https://raw.githubusercontent.com/David-Haim/CountriesToCitiesJSON/master/countriesToCities.json', true) // последний параметр указывает на синхронность или асинхронность запроса. В данном случае запрос асинхронный


request.onreadystatechange = function(){ //обработчик изменения статуса запроса. Статус == 4 сигнализирует о том, что запрос окончен.
    if (request.readyState != 4){
        return;
    }

    if (request.status == 200){
        var object = JSON.parse(request.responseText);

        
        var keys = Object.keys(object);
        var select = document.createElement("select");
        for (var i = 0; i < keys.length; i++) {
            var option = document.createElement("option");
            option.innerHTML = keys[i];
            option.value = keys[i];
            select.appendChild(option);
        }
        select.onchange = function(e){
            console.log(this.value)
            var select = document.createElement("select");
            for (var i = 0; i < object[this.value].length; i++) {
                var option = document.createElement("option")
                option.innerHTML = object[this.value][i];
                

                select.appendChild(option);
                
            }
            if(selects.children.length > 1){
                selects.replaceChild(select, document.getElementById("main").nextElementSibling);
            }
            else
                selects.appendChild(select);
            request.open('GET', "https://query.yahooapis.com/v1/public/yql?" + 'q=' + encodeURIComponent("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\'" + select.value + "\') and u='c'") + '&format=json', true);
            	console.log(this.value)
            	request.onreadystatechange = function(){
            		if(request.readyState === 4 && request.status === 200){
            			console.log(JSON.parse(request.responseText));
            			var obj = JSON.parse(request.responseText);
            			
            			var weather = obj.query.results.channel.item.description;
            			
            			var resWeather = weather.replace(/href|CDATA|[\!]|[\[]|[\]]/g,"");
            			var resWeather2 = resWeather.slice(1,resWeather.length - 1);
            			var resWeather3 = resWeather2.replace(/Full Forecast at Yahoo Weather/g,"");
            			var resWeather4 = resWeather3.slice(0,resWeather3.length - 28);
            			weatherDiv.innerHTML = resWeather4;
            			console.log(resWeather4)
            			
            		}
            		else if(request.readyState > 1 && request.readyState < 4){
            			weatherDiv.setAttribute("heigt", "400px")
            			weatherDiv.innerHTML = "loading...";
            		}
            		else if(request.status === 400){
            			weatherDiv.innerHTML = "error 400";
            		}
            	}
            	request.send();
            select.onchange = function(){

            	request.open('GET', "https://query.yahooapis.com/v1/public/yql?" + 'q=' + encodeURIComponent("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\'" + this.value + "\') and u='c'") + '&format=json', true);
            	console.log(this.value)
            	request.onreadystatechange = function(){
            		if(request.readyState === 4 && request.status === 200){
            			console.log(JSON.parse(request.responseText));
            			var obj = JSON.parse(request.responseText);
            			
            			var weather = obj.query.results.channel.item.description;
            			
            			var resWeather = weather.replace(/href|CDATA|[\!]|[\[]|[\]]/g,"");
            			var resWeather2 = resWeather.slice(1,resWeather.length - 1);
            			var resWeather3 = resWeather2.replace(/Full Forecast at Yahoo Weather/g,"");
            			var resWeather4 = resWeather3.slice(0,resWeather3.length - 28);
            			weatherDiv.innerHTML = resWeather4;
            			console.log(resWeather4)
            			// var resObj = obj.query.results;
            			// var keys = Object.keys(resObj);
            			// var table = document.createElement("table");
            			// for (var i = 0; i < keys.length; i++) {
            			// 	var tr = document.createElement("tr");
            			// 	var td1 = document.createElement("td");
            			// 	var td2 = document.createElement("td");
            			// 	td1.innerHTML = keys[i];
            			// 	td2.innerHTML = resObj[keys[i]];
            			// 	tr.appendChild(td1);
            			// 	tr.appendChild(td2);
            			// 	table.appendChild(tr);
            			// }
            			// document.body.appendChild(table);
            		}
            		else if(request.readyState > 1 && request.readyState < 4){
            			weatherDiv.setAttribute("heigt", "400px")
            			weatherDiv.innerHTML = "loading...";
            		}
            		else if(request.status === 400){
            			weatherDiv.innerHTML = "error 400";
            		}
            	}
            	request.send();
            }
            
        }
        selects.appendChild(select);
        select.id = "main"
            }
            else {
                alert('shit happens: ' +  xhr.status + ', ' + xhr.statusText );
            }
        }

request.send()
