var VehicleModels = null;
var VehicleJsLoaded = false;


function ModelSelection(model_field, make_id) {
	this.model_field = model_field;
	this.make_id = make_id;
	this.mode = 'optgroups';
	
	this.setMode = function(mode) {
		this.mode = mode;
	}

	this.load = function () {
		VehicleModels = null;
		this.include('/js/Models/'+ this.make_id +'.js');
		this.setValues();
	}

	this.include = function (file) {
		$.ajax({
			type: "GET",
			url: file,
			dataType: "script",
			async: false
		});
		return;
	}

	this.setValues = function() {		
		var title = this.model_field.attr('title');
		this.model_field.html('<option value="">'+ (title ? title : '') +'</option>');
		this.generateOptions(VehicleModels, 0);
	}

	this.generateOptions = function(m, depth) {
		if (!m) {
			return;
		}
		var depth = parseInt(depth);
		var c  = m.length;

		var style = '';
		var langkey = this.getLangKey(this.getLangFromUrl());

		for (var i = 0; i < c; i++) {
			if (this.mode == 'optgroups' && m[i].childs && m[i].childs.length > 0) {				
				this.model_field.append('<optgroup label="' + m[i].label[langkey] +'">');
				this.generateOptions(m[i].childs, depth + 1);
				this.model_field.append('</optgroup>');
			}
			else {
				if (this.mode != 'optgroups' && m[i].childs && m[i].childs.length > 0) {
					style = 'style="font-weight:bold"';
				}
				else {
					style = (depth > 0 ? 'style="padding-left:'+ (depth * 15) + 'px" ': '');
				}

				this.model_field.append('<option '+ style +'value="'+ m[i].id +'">' + m[i].label[langkey] +'</option>');

				if (this.mode != 'optgroups' && m[i].childs && m[i].childs.length > 0) {
					this.generateOptions(m[i].childs, depth + 1);
				}
			}
		}
	}
	
	this.getLangFromUrl = function() {
		var url = document.location.href;
		if (url.indexOf('lang=') > -1 ) {
			var lang = url.match(/lang=((.)*)/);
			lang = lang[1].split('&');
			return lang[0];
		}
		url = document.location.pathname;
		var lang = url.match(/^\/(est|eng|rus|lat|lit)/)
		if (lang  && lang[1]) {
			return lang[1];
		}
		else {
			return 'est';
		}
	}

	this.getLangKey = function(lang) {		
		var langs = ['est', 'eng', 'rus', 'lat', 'lit'];
		for(var i in langs) {
			if (langs[i] == lang) {
				return i;
			}
		}
		return 0;
	}

	return this;
}