var CL = CL || {};
CL.Ajax = {
	XMLHttpFactories: [
		function () {return new XMLHttpRequest()},
		function () {return new ActiveXObject("Msxml2.XMLHTTP")},
		function () {return new ActiveXObject("Msxml3.XMLHTTP")},
		function () {return new ActiveXObject("Microsoft.XMLHTTP")}
	],
	sendRequest: function (url, callback, postData) {
		var req = this.createXMLHTTPObject();
		if (!req) {
			return;
		}
		var method = (postData) ? "POST" : "GET";
		req.open(method, url, true);
		req.setRequestHeader('User-Agent', 'XMLHTTP/1.0');
		req.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
		if (postData) {
			req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
		}
		req.onreadystatechange = function () {
			if (req.readyState != 4) {
				return;
			}
			if (req.status != 200 && req.status != 304) {
	//			alert('HTTP error ' + req.status);
				return;
			}
			callback(req);
		}
		if (req.readyState == 4) {
			return;
		}
		req.send(postData);
	},	
	createXMLHTTPObject: function () {
		var xmlhttp = false;
		for (var i = 0; i < this.XMLHttpFactories.length; i++) {
			try {
				xmlhttp = this.XMLHttpFactories[i]();
			}
			catch (e) {
				continue;
			}
			break;
		}
		return xmlhttp;
	}
};
CL.Utils = {
	loadImage: function (containerID, imgPath) {
		var targetContainer = document.getElementById(containerID),
			w = targetContainer.style.width,
			h = targetContainer.style.height,
			top = 0, left = 0;
		w = w.split('px')[0];
		h = h.split('px')[0];
		left = Math.floor((parseInt(w) - 32) / 2);
		top = Math.floor((parseInt(h) - 32) / 2);
		targetContainer.innerHTML = '<img src="' + document.getElementById('car-view-base-path').innerHTML + 'app/web/img/loading.gif" alt="" style="margin: ' + top + 'px 0 0 ' + left + 'px" />';
		
		var imgObj = new Image();
		
		imgObj.onload = function () {
			targetContainer.innerHTML = '';
			targetContainer.appendChild(imgObj);
		};
		
		imgObj.src = imgPath;
	}
};

if (document.getElementById('make_id')) {
	document.getElementById('make_id').onchange = function () {
		var id = document.getElementById('make_id').options[document.getElementById('make_id').selectedIndex].value;
		CL.Ajax.sendRequest(document.getElementById('car-search-base-path').innerHTML + 'index.php?controller=Front&action=getModels&id=' + id, function (res) {
			document.getElementById('car-search-model').innerHTML = res.responseText;
			document.getElementById('model_id').setAttribute(document.all ? 'className' : 'class', 'car-select car-select-medium');
		});
	};
}
