﻿Ext.onReady(function() {

	function setOptions(el, text) {
		var temp = document.createElement('div');
		temp.innerHTML = '<select>' + text + '</select>';

		el.dom.options[0] = new Option('Choose...', null);

		var count = 1;

		for(var i = 0; i < temp.childNodes[0].childNodes.length; i++) {
			if(temp.childNodes[0].childNodes[i].tagName && temp.childNodes[0].childNodes[i].tagName.toLowerCase() == 'option') {
				el.dom.options[count] = new Option(temp.childNodes[0].childNodes[i].text, temp.childNodes[0].childNodes[i].value);
				count++;
			}
		}
	}

	if(Ext.get('qtypeSel') !== null) {
		Ext.get('qtypeSel').on('change', function() {
			Ext.Ajax.request({
				url: '/client/getmanufacturers.html?vehicleType=' + this.getValue(),
				success: function(r) {
					setOptions(Ext.get('qbrandSel'), r.responseText);
				}
			});
		});
	}

	if(Ext.get('qbrandSel') !== null) {
		Ext.get('qbrandSel').on('change', function() {
			var txt = this.dom.options[this.dom.selectedIndex].innerHTML;
			Ext.get('manufacturerName').dom.value = txt;
			
			Ext.Ajax.request({
				url: '/client/getmodels.html?vehicleType=' + Ext.get('qtypeSel').getValue() + '&manufacturerId=' + this.getValue(),
				success: function(r) {
					setOptions(Ext.get('qmodelSel'), r.responseText);
				}
			});
		});
	}

	if(Ext.get('qmodelSel') !== null) {
		Ext.get('qmodelSel').on('change', function() {
			var txt = this.dom.options[this.dom.selectedIndex].innerHTML;
			Ext.get('modelName').dom.value = txt;
			
			Ext.Ajax.request({
				url: '/client/getderivatives.html?vehicleType=' + Ext.get('qtypeSel').getValue() + '&modelId=' + this.getValue(),
				success: function(r) {
					setOptions(Ext.get('qderSel'), r.responseText);
				}
			});
		});
	}
	
	if(Ext.get('qderSel') !== null) {
		Ext.get('qderSel').on('change', function() {
			var txt = this.dom.options[this.dom.selectedIndex].innerHTML;
			Ext.get('derivativeName').dom.value = txt;
		});
	}
});
