/**
 * NS Serviceponts
 * 
 * @version   1.00.090611
 * @author    LBI Lost Boys
 */
NS(function($){

	function Serviceponts() {
		this.form = $('#form-servicepunt');
		this.createSelect();
		NS.subscribe('change', this.handleChange.bind(this));
	}

	Serviceponts.prototype = {
		createSelect: function() {
			var field = this.form.find('fieldset');
			
			this.locations = $('<select><option>Selecteer een plaatsnaam</option></select>');
			this.container = $('<div></div>');
			this.container.css({ clear: 'left', 'float': 'none' });
			
			field.append(this.locations);
			field.append(this.container);

			NS.XHR.load(NS.getProperty('GET_SERVICEPOINTS_INFO'), this.handleServicepoints.bind(this));
		},

		handleChange:function(e) {
			var select = e.target;
			if(select == this.locations[0]) {
				this.displayDetails();
			}
		},

		handleServicepoints:function(xml) {
			var doc = $(xml);
			var cities = $(xml).find("city");
			var locations = this.locations[0].options;

			for(var i=0; i <cities.length; i++){
				var city = $(cities[i]);
				locations[locations.length] = new Option(city.text(), i);
			}
			
			this.data = doc.find('info');
		},

		displayDetails:function() {
			var city = parseInt(this.locations.val(), 10);
			var info = this.data.eq(city).text();
			if(info) {
				NS.DOM.write(this.container, info);
			}
		}
	};

	/**
	 * Bind to NS.initialize
	 */
	NS.subscribe('initialize', function(){
		NS.addApplication('serviceponts', new Serviceponts());
	});
});