//вспомогательная фнк. на случай если не подгрузился mui.$
if ($ == undefined){
	$ = function(id){return document.getElementById(id)};
}

//для того чтобы не засорять глобальное пространство имен
//оформим функционал в виде объекта
function m_match(){
	this.tt_id = "match_tt";
	this.preload = "preload";
	this.tt_num = "tt-num";
	this.xhr = null;//не больше 1 активного запроса
	this.t_out = null;//таймаут для реализации микропаттерна для onkeyup()
};

m_match.prototype = {

	//обновляем массивы чекнутых чекбоксов (и заносим результат в input type=hidden)
	_updateArrays : function(id, arr, id_input){
		var node = $(id),
		pos = -1;

		for (var i = 0, length = arr.length; i < length; ++i)
		if (node && arr[i] == node.value) pos = i;
		//добавляем или удаляем элемент из массива
		if (node.checked && pos == -1) arr.push(node.value);
		else if (!node.checked && pos >=0) arr.splice(pos, 1);
		//записываем массив чекнутых чекбоксов в input type=hidden
		var inp_el = $(id_input);
		if (inp_el && inp_el.value != undefined){
			inp_el.value = arr.join(",");
		}
	},
	
	//выводим краткую подсказку с кол-твом моделей в подборе
	tooltip : function(srcElement){
		if (srcElement){
			//создаем подсказку и присоединяем к body
			if (!$(this.tt_id)) {
				var tt_div  = document.createElement('div');
					tt_div.className = "tt-match";	
					tt_div.id = this.tt_id;
				document.body.appendChild(tt_div);
				//наполняем тултипу html
				tt_div.innerHTML = this.tt_html();
			}
			//позиционируем тултипу
			this.tt_position(srcElement);
		}
	},
	
	//добавляет верное окончание к кол-ву моделей
	add_ending : function(str, number, o1, o2, o5) {
		var result = "";
		if ((number >= 10) && (number <= 20)) result = o5;
		else {
			var last_digit = number % 10;
			if (last_digit == 0) result = o5;
			else if (last_digit == 1) result = o1;
			else if (last_digit <= 4) result = o2;
			else result = o5;
		}
		return str+result;
	},
	
	ttAddInfo : function(srcElement, data){
		if (typeof $('tt-info') != "undefined" && typeof data.num != "undefined"){
			if (parseInt(data.num) >= 0){
				if ($(this.preload)) $(this.preload).style.display = "none";
				var ht = "";		
				ht += "	Выбрано <span id='"+this.tt_num+"'>"+data.num+"</span><img id='preload' src='/img/preload.gif' width='15' height='15' style='display:none; vertical-align:middle;' /> "+this.add_ending('модел', data.num, 'ь', 'и', 'ей')+" &nbsp;<a href='javascript:void(0)' onclick='document.getElementById(\"form_match\").submit(); return false;' style='color:#0655a4; position:relative'>Подобрать</a>";
				ht += "	<a class='x' href='javascript:void(0)' onclick='document.getElementById(\"match_tt\").style.display = \"none\"'></a>";					
				$('tt-info').innerHTML = ht;
			}
			//тушим подсказку
			else if (parseInt(data.num) == -1){
				$('tt-info').innerHTML = "<a href='javascript:void(0)' onclick='document.getElementById(\"form_match\").submit(); return false;' style='color:#0655a4; position:relative'>Показать</a> выбранные модели<a class='x' href='javascript:void(0)' onclick='document.getElementById(\"match_tt\").style.display = \"none\"'></a>";			
			}
		}
	},
	
	tt_position : function(srcElement){
		if (mui && srcElement && $(this.tt_id)){			
			var coords = mui.getCoordsXY(srcElement);			
			$(this.tt_id).style.left = "229px";
			$(this.tt_id).style.top = coords[1] - 8;
			$(this.tt_id).style.display = "block";			
		}
	},
	
	tt_html : function(){
		
		var ht = "";
		ht += "<table cellpadding='0' cellspacing='0' border='0'>";
		ht += "		<tr>";
		ht += "			<td class='left' id='tt-info'>";
		ht += "				Выбрано <span id='"+this.tt_num+"'></span><img id='preload' src='/img/preload.gif' width='15' height='15' style='display:inline-block; vertical-align:middle;' /> моделей &nbsp;<a href='javascript:void(0)' onclick='document.getElementById(\"form_match\").submit(); return false;' style='color:#0655a4; position:relative'>Подобрать</a>";
		ht += "				<a class='x' href='javascript:void(0)' onclick='document.getElementById(\"match_tt\").style.display = \"none\"'></a>";
		ht += "			</td>";
		ht += "			<td class='right'></td>";
		ht += "		</tr>";
		ht += "	</table>";
		
		return ht;
	},

	//обрабатывает событие обновдение цены
	//навеяно вот этим: http://habrahabr.ru/blogs/javascript/60957/
	changeHandler : function(item, timeout, _show){
		if (parseInt(timeout) > 0){
			clearTimeout(this.t_out);
			this.t_out = setTimeout(function(){
				if (_show){
					m_match.showTip(item);
				}
				else{
					m_match.sendRequest(item);
				}
			}, timeout);
		}
		else {
			if (_show){
				this.showTip(item);
			}
			else{
				this.sendRequest(item);
			}
		}
	},
	
	showTip : function(srcElement){
		//показываем подсказку
		m_match.tooltip(srcElement);
		//показываем подсказку
		m_match.ttAddInfo(srcElement, {"num" : "-1"});
	},

	sendRequest : function(srcElement){

		if ($(this.preload) && $(this.tt_num)) {$(this.preload).style.display = ""; $(this.tt_num).style.display = "none";}
		//показываем подсказку
		m_match.tooltip(srcElement);
		
		if (mui != undefined && (typeof presets_sel != "undefined") && (typeof brands_sel != "undefined") && (typeof subkatalogs_sel != "undefined")){//отправляем данные на сервер при помощи mui
			var source = "mtools/mui_match.php";
			//передаем какие отмечены сейчас

			var data = "brands_="+mui.escape(brands_sel.join(","))+"&presets_="+mui.escape(presets_sel.join(","))+"&subkatalogs_="+mui.escape(subkatalogs_sel.join(","))+"&katalog_="+mui.escape(""+IDKatalog_+"");

			if ($("minPrice_") && $("minPrice_").value != undefined){
				data += "&minPrice_="+mui.escape($("minPrice_").value);
			}

			if ($("maxPrice_") && $("maxPrice_").value != undefined){
				data += "&maxPrice_="+mui.escape($("maxPrice_").value);
			}

			if ($("sc_id_") && $("sc_id_").value != undefined){
				data += "&sc_id_="+mui.escape($("sc_id_").value);
			}

			//для того чтобы не накапливалась очередь запросов
			if (this.xhr) {
				this.xhr.abort();
				this.xhr = null;
			}
			this.xhr = mui.loadPOST(source, data, null, function(responce){																											 
																 
				if (mui != undefined && responce.br_off != undefined && responce.pr_off != undefined){
					
					//показываем подсказку
					m_match.ttAddInfo(srcElement, responce);
					
					var br_off = (responce.br_off) ? responce.br_off.split(",") : [];
					var pr_off = (responce.pr_off) ? responce.pr_off.split(",") : [];
					var sk_off = (responce.sk_off) ? responce.sk_off.split(",") : [];

					//ставим Подобрать + (количество моделей)
					var match_submit = $("match_submit");
					if (match_submit && parseInt(responce.num) >= 0){
						if (match_submit.value.match(/\(\d*\)/)) {
							match_submit.value = match_submit.value.replace(/\(\d*\)/, "("+responce.num+")");
						}
						else match_submit.value += " ("+responce.num+")";
					}

					var _temp = null,
					_pos = -1;

					brands_.map(function(_id){
						_temp = $("br"+_id);
						if (_temp){
							if (mui.inArray(_id, br_off) >= 0){
								//делаем его не чекнутым
								_temp.checked = false;
								//убираем с массива чекнутых
								if (mui.inArray(_id, brands_sel) >= 0){
									m_match._updateArrays("br"+_id, brands_sel, "brands_ID");
								}
								_temp.disabled = true;
							}
							else {_temp.removeAttribute("disabled")}
						}
					});
					presets_.map(function(_id){
						_temp = $("c"+_id);
						if (_temp){
							if (mui.inArray(_id, pr_off) >= 0){
								//делаем его не чекнутым
								_temp.checked = false;
								//убираем с массива чекнутых
								if (mui.inArray(_id, presets_sel) >= 0){
									m_match._updateArrays("c"+_id, presets_sel, "presets_ID");
								}
								_temp.disabled = true;
							}
							else {_temp.removeAttribute("disabled")}
						}
					});
					subkatalogs_.map(function(_id){
						_temp = $("sk"+_id);
						if (_temp){
							if (mui.inArray(_id, sk_off) >= 0){
								//делаем его не чекнутым
								_temp.checked = false;
								//убираем с массива чекнутых
								if (mui.inArray(_id, subkatalogs_sel) >= 0){
									m_match._updateArrays("sk"+_id, subkatalogs_sel, "subkatalogs_ID");
								}
								_temp.disabled = true;
							}
							else {_temp.removeAttribute("disabled")}
						}
					});
				}
			}, "json");
		}
	},

	//обрабатываем событие check/uncheck чекбокса
	checkHandler : function(item, _show){
		var pos = -1,
		id = item.id;

		if (id){
			if (item.name == "mn_[]") {
				this._updateArrays(id, brands_sel, "brands_ID");
			}
			else if (item.name == "pr_[]") {
				this._updateArrays(id, presets_sel, "presets_ID");
			}
			else if (item.name == "sk_[]") {
				this._updateArrays(id, subkatalogs_sel, "subkatalogs_ID");
			}
			
			if (_show){
				this.showTip(item);
			}
			else{
				this.sendRequest(item);
			}
		}
	}
}

m_match = new m_match();

mui.ready(function(){
	
	//чтобы подсказка пропадала по клику на любом месте экрана кроме нее
	mui.bind("click", function(event){
		var parent = event.target || event.srcElement,
			id = null;					   

		//проходим вверх по дереву DOM
		while ( parent && parent.parentNode ){
			if (parent.id == "match_tt" || parent.tagName.toLowerCase() == 'label' ||parent.name == "mn_[]" || parent.name == "pr_[]" || parent.name ==  "maxPrice_" || parent.name ==  "minPrice_" || parent.name == "sc_id_" ) {
				id = "match_tt";
				break;
			}
			parent = parent.parentNode;
		}
		if (!id && $("match_tt")) $("match_tt").style.display = "none";
	});
});

