

window.addEvent('domready', function() {

	var jsonInput = $('jsonInput');

    var addSelect = function(name, options) {
        
        var jsonSelect = $(name);
        if (jsonSelect != null){
            jsonInput.empty();
        }        
		
		var listingDiv = $('listingDiv');
		var listing = $('listing');
	    if (listing != null){
	    	listingDiv.empty();
	    }

	    var el = new Element('select', {'name': name, 'id': name});
		options.each(function(option) {
			var name = new Element('option', {'name': option.name, 'value':option.name}).inject(el);
			name.setText(option.name);
		    el.inject(jsonInput);
		});

        // lazy...
        $(name).addEvent('change', function(e) {
            var optionID = this.getValue();
            //e.stop();
            var request = new Json.Remote('shopfinder/getJsonData.php?shops=' + optionID,{
                onComplete: function(jsonObj) {
                    showShops(jsonObj.shops);
              	}
			}).send();
        });

	};

    // triggers onchange json request to show Cities
	$('jsonCountry').addEvent('change', function(e) {
        var optionID = this.getValue();
		//e.stop();
		var jSonRequest = new Json.Remote('shopfinder/getJsonData.php?country=' + optionID, {
			onComplete: function(jsonObj) {
				addSelect("jsonCities", jsonObj.cities);
	   		}
		}).send();   

 		/*
		var request = new Request.JSON({
			url: 'getJsonData.php?country=' + optionID,
			onComplete: function(jsonObj) {
				addSelect("jsonCities", jsonObj.cities);
			}
		}).send();
		*/
	});

    // generating HTML output of shop listing 
    var showShops = function(shops) {

        var listingDiv = $('listingDiv');
		var listing = $('listing');
        if (listing != null){
            listingDiv.empty();
        }
        
		var el = new Element('span', {'id': 'listing'});
		shops.each(function(shop) {

			var name = new Element('p', {'html': shop.name, 'value':shop.name}).inject(el);
			var street = new Element('p', {'html':  shop.street}).inject(name, 'after');
 			name.setHTML(shop.name);                         		
			//var footer = new Element('span').inject(img, 'after');
		    el.inject(listingDiv);
		});

    };


	$('clearJson').addEvent('click', function(e) {
		e.stop();
		jsonInput.empty();
	});

});
