﻿function TGBManager() {
	this.queueLength = 0;
	this.queueLocked = false;
	this.pollingStarted = false;

	this.requestQueue = new Array();

	this.requestParameters;

	this.excludeIds = "";

	this.addRequestToQueue = function (sender, type, count, tag) {
		if (this.queueLocked)
			setTimeout(function () { window.manager.addRequestToQueue(sender, type, count, tag) }, 300);
		else {
			this.queueLocked = true;

			this.requestQueue[this.requestQueue.length] = new Array(sender, type, count, tag);

			this.queueLocked = false;

			if (!this.pollingStarted) {
				this.pollingStarted = true;
				this.sendRequest();
			}
		}
	};

	this.htmlWrap = function (type, id, url, title, text, agency, addSpacer, phone, hasAgencyPhoto, altType, tag, tgbIndex, tgbCount) {
		var hasAgency = agency != null && agency != "";
		var resultHtml = '', hasResult;

		if (type == 'Vertical' || type == 'VerticalLeft' || type == 'VerticalPlus') {
			if (tag == 'MainPageCentral' ||
				tag == 'SearchResultVP' ||
				tag == 'EstateObjectCentral') {
				if (tgbIndex == 0) {
					if (tag == 'SearchResultVP') {
						resultHtml += "<div class=\"mb5px\"></div>";
					}
					resultHtml += "<div class=\"yell_block tgb3c-fix-search-t\"><div class=\"r_t\"><div class=\"l_b\"><div class=\"r_b\">" +
						"<div class=\"tgb3c-cntr\"><ul class=\"row\">";
				}

				var itemWidth = Math.round(100 / tgbCount);

				resultHtml += "<li class=\"item";
				if (tgbIndex == tgbCount - 1) {
					resultHtml += " last";
				}
				resultHtml += "\" style=\"width:" + itemWidth + "%\"><span class=\"sub-cntr\">" +
						"<a target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
							"<span class=\"header\">" + title + "</span>" +
							"<div class=\"img-cnt\">" +
								"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"168\" height=\"108\" />" +
							"</div>" +
							"<div class=\"text\">" + text + "</div>" +
						"</a>" +
					"</span></li>";


				if (tgbIndex == tgbCount - 1) {
					resultHtml += "</ul></div>" +
						"</div></div></div></div>";
					if (tag == 'SearchResultVP') {
						resultHtml += "<div class=\"list_item tgb3c-fix-search-b\"></div>";
					}
				}
			} else {
				resultHtml += "<a target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url +
					"\" class=\"block mb5px\"><span class=\"block_top\"><span class=\"block_bottom\">" +
					"<span class=\"h\">" + title + "</span>";

				if (tag == 'LeftColumn') {
					altType = 10;
				} else if (tag == 'RightColumn') {
					altType = 11;
				}

				if (!altType || (altType != 10 && altType != 11 && altType != 12)) {
					resultHtml += "<span style=\"width: 65px; float:left; display:block;\">" +
				"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"60\" />";
				} else {
					if (altType == 10) {
						resultHtml += "<span style=\"width: 168px; display:block;\">" +
					"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"168\" height=\"108\" />";
					} else if (altType == 11) {
						resultHtml += "<span style=\"width: 206px; display:block;\">" +
					"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"206\" height=\"133\" />";
					} else if (altType == 12) {
						resultHtml += "<span style=\"width: 100%; max-width:206px; display:block;\">" +
					"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"98%\" height=\"133\" />";
					}
				}

				if (hasAgency) {
					if (!altType || (altType != 10 && altType != 11 && altType != 12)) {
						resultHtml += (hasAgencyPhoto ? "<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "&agency=1\" alt=\"" + agency.replace(/\"/g, "'") + "\" style=\"max-width: 60px\" />" : "");
					}
				}

				resultHtml += "</span><span>" + text + "<br />" + (hasAgency ? "<i style=\"display: block; margin: 7px 0; font-family: Times New Roman; color: #666;\">" + agency + "</i>" : "");

				if (!altType || (altType != 10 && altType != 11 && altType != 12)) {
					resultHtml += (phone != null && phone != "" ? "<b style=\"font-weight: 900;\">" + phone + "</b>" : "");
				}

				resultHtml += "</span></span></span></a>";
			}
			hasResult = true;
		}
		else if (type == 'SearchResult' || type == 'SearchResult2' || type == 'SearchResult3' || type == 'AboveCityList') {
			resultHtml = "<a class=\"h\" target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
				"<span style=\"float:left; display:block; margin-right: 10px;\">" +
				"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"75\" height=\"54\" />" +
				"</span>" +
				"<b style=\"font-weight: 900;\">" + title + "</b><br />" +
				"<span class=\"text\">" + text + "<br />" +
				(phone != null && phone != "" ? "<b class=\"phone\">" + phone + "</b>" : "") +
				(hasAgency ? "<i class=\"agency\">" + agency + "</i>" : "") +
				"</span></span></span></a>";
			hasResult = true;
		}
		else if (type == 'UnderLogo') {
			resultHtml = "<a class=\"h\" target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
				"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"75\" height=\"54\" style=\"float:left;margin-right:4px;\" />" +
				"<span class=\"text\">" + text + "</span>" +
				"</a>";
			hasResult = true;
		}
		else if (type == 'UnderTags') {
			resultHtml = "<a class=\"h\" target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
				(title != null && title != "" ? "<span class=\"text title\"><b>" + title + "</b></span>" : "") +
				"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"75\" height=\"54\" style=\"float:left;margin-right:4px;\" />" +
				"<span class=\"text desc\">" + text + "</span>" +
				(phone != null && phone != "" ? "<b class=\"phone\">" + phone + "</b><br/>" : "") +
				(hasAgency ? "<i class=\"agency\">" + agency + "</i>" : "") +
				"</a>";
			hasResult = true;
		} else if (type == 'EstateCardUnderPhoto') {
			resultHtml = "<div class=\"estatecardtgb\"><a target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
			(title != null && title != "" ? "<span class=\"text title\"><b>" + title + "</b></span>" : "") +
			"</a></div>";
			hasResult = true;
		}

		if (!hasResult) {
			if (addSpacer) {
				resultHtml = "<td class=\"r\"></td>";
			}
			resultHtml += "<td width=\"33%\"><div class=\"top\"><p><span></span></p></div><div class=\"cnt\">" +
				"<a target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\" class=\"h\">" + title + "</a>" +
				"<a target=\"_blank\" onclick=\"click_track('" + id + "')\" href=\"/Goto.ashx?out=" + url + "\">" +
				"<img src=\"http://files.mirkvartir.ru/Image.axd?tgbId=" + id + "\" alt=\"" + title.replace(/\"/g, "'") + "\" width=\"140\" height=\"100\" /></a>" +
				"<span>" + (agency != null && agency != "" ? (agency + "<br />") : "") + text + "</span></div></td>";
		}

		return resultHtml;
	};

	this.sendRequest = function () {
		if (this.queueLocked || typeof (window.manager.requestQueue[window.manager.requestQueue.length - 1]) == 'undefined')
			setTimeout(function () { window.manager.sendRequest() }, 300);
		else {
			window.manager.queueLocked = true;

			currentRequest = window.manager.requestQueue[window.manager.requestQueue.length - 1];

			$.ajax(
				{
					url: '/GetTGBs.axd'
						+ '?searchTypeIndex=' + this.requestParameters[0]
						+ '&count=' + currentRequest[2]
						+ '&type=' + currentRequest[1]
						+ (this.requestParameters[1] > 0 ? ('&countryId=' + this.requestParameters[1]) : "")
						+ (this.requestParameters[2] > 0 ? ('&regionId=' + this.requestParameters[2]) : "")
						+ (this.requestParameters[3] > 0 ? ('&provinceId=' + this.requestParameters[3]) : "")
						+ (this.requestParameters[4] > 0 ? ('&townId=' + this.requestParameters[4]) : "")
						+ (this.requestParameters[5] > 0 ? ('&streetId=' + this.requestParameters[5]) : "")
						+ (this.requestParameters[6] > 0 ? ('&districtId=' + this.requestParameters[6]) : "")
						+ (this.requestParameters[7] > 0 ? ('&subwayId=' + this.requestParameters[7]) : "")
						+ (this.requestParameters[8] > 0 ? ('&houseId=' + this.requestParameters[8]) : "")
						+ '&tag=' + currentRequest[3]
						+ (this.excludeIds.length > 0 ? ('&excludeIds=' + this.excludeIds) : ""),
					dataType: 'json',
					success: function (response) {
						var TGBTarget = $("#" + currentRequest[0]);

						var result = '';
						if (currentRequest[1] == 'Vertical' || currentRequest[1] == 'VerticalLeft' || currentRequest[1] == 'VerticalPlus') {
							if (currentRequest[3] != 'MainPageCentral' &&
								currentRequest[3] != 'SearchResultVP' &&
								currentRequest[3] != 'EstateObjectCentral') {
								result = "<div class=\"yell_block\"><div class=\"r_t\"><div class=\"l_b\"><div class=\"r_b\">";
							}
						}
						else if (currentRequest[3] == '') {
							if (currentRequest[1] != 'UnderLogo') {
								if (currentRequest[1] == 'AboveCityList' ||
									currentRequest[1] == 'UnderTags' ||
									currentRequest[1] == 'EstateCardUnderPhoto') {
									result = "<div class=\"list_item nb\"><div class=\"cntr\">";
								} else {
									result = "<div class=\"list_item\"><div class=\"cntr\">";
								}
							}
							if (currentRequest[1] == 'UnderTags') {
								result = "<div class=\"tgb-under-tags\"><table width=\"100%\">";
							}
						}

						var len;

						for (var i = 0; i < response.TGB.length; i++) {
							len = window.manager.excludeIds.length;

							if (len > 0 && window.manager.excludeIds[len - 1] != ",")
								window.manager.excludeIds = window.manager.excludeIds + ",";

							window.manager.excludeIds = window.manager.excludeIds + response.TGB[i].Id + ",";

							_gaq.push(['_trackEvent', 'TGB', 'Show', response.TGB[i].Id.toString(), 1, true]);

							if (response.TGB[i].Tag == '') {
								if (currentRequest[1] == 'UnderTags') {
									if ((i % 2) == 0) {
										if (i != 0) {
											result += "</tr><tr>";
										} else {
											result += "<tr>";
										}
									}
								}
								if (currentRequest[1] == 'UnderTags') {
									result += "<td>";
								}
							}

							result += window.manager.htmlWrap(currentRequest[1], response.TGB[i].Id, response.TGB[i].Link, response.TGB[i].Title, response.TGB[i].Text,
								response.TGB[i].Agency, currentRequest[1] == 'Horizontal' && i > 0, response.TGB[i].Phone, response.TGB[i].HasAgencyPhoto,
								response.TGB[i].TGBType, response.TGB[i].Tag, i, response.TGB.length);

							if (response.TGB[i].Tag == '') {
								if (currentRequest[1] == 'UnderTags') {
									result += "</td>";
								}
							}
						}

						len = window.manager.excludeIds.length;

						if (len > 0 && window.manager.excludeIds[len - 1] == ",") {
							window.manager.excludeIds = window.manager.excludeIds.substr(0, len - 1);
						}

						if (currentRequest[3] == '') {
							if (currentRequest[1] == 'Horizontal') {
								result += "</div>";
							}

							if (currentRequest[1] != 'UnderLogo') {
								result += "</div></div></div></div>";
							}

							if (currentRequest[1] == 'UnderTags') {
								if ((response.TGB.length % 2) != 0) {
									result += "<td>&nbsp;</td>";
								}
								result += "</tr></table></div>";
							}
						}

						var container = document.getElementById(currentRequest[0]);
						if (container) {
							container.innerHTML = result;
						}

						window.manager.requestQueue.pop();

						window.manager.queueLocked = false;

						window.manager.queueLength = window.manager.queueLength - 1;

						if (!window.manager.queuePopulationFinished || window.manager.queueLength > 0)
							window.manager.sendRequest();
					},
					error: function () {
						window.manager.requestQueue.pop();

						window.manager.queueLocked = false;

						window.manager.queueLength = window.manager.queueLength - 1;

						if (!window.manager.queuePopulationFinished || window.manager.queueLength > 0)
							window.manager.sendRequest();
					}
				});
		}
	}

	window.manager = this;
};

function click_track(senderId) {
	_gaq.push(['_trackEvent', 'TGB', 'Click', senderId, 1, true]);
}

var manager = new TGBManager();

$(document).ready(function () { manager.queuePopulationFinished = true; });
