//Предзагрузка изображения
var loadImg = new Image();
loadImg.src = "../images/ajax-loader.gif";

//Переменные
var msg = $("<div style='padding: 200px; text-align: center;'></div>");
var error_msg = $("<div style='padding: 200px; text-align: center;' class='error'></div>");
var error_msg1 = $("<div style='padding: 80px; text-align: center;' class='error'></div>");

//************* Функции *********************************

//Страница загружена
$(document).ready( function() {
	//Установки ajax
	$.ajaxSetup({ timeout: 3000 });
	$("body").ajaxError( function (event, request, settings) {
		//Определяем по url ajax-запроса, куда будем выводить ошибку
		//список застройщиков
		/**/if (settings.url.indexOf("builder_list") != -1)
			$("#page_content").html(error_msg.html("Ошибка запроса страницы " + settings.url));

		//форма добавления застройщика
		else if (settings.url.indexOf("form_new_builder") != -1) {
			//Выведем ошибку
			$("#modal_content").html(error_msg1.html("Ошибка запроса страницы " + settings.url));
			//Добавим кнопку "закрыть"
			$("#modal_control").html("<div class='button' style='margin-right:10px; \
				margin-top:10px;' onclick='javascript:{$.modal.close();}'>Закрыть</div>");
		}
	});

	//Загружаем данные (в зависимости от страницы)
	if (location.href.indexOf("page=nlhouse") != -1)  {
		LoadHouseTable(1);
	}
	else if (location.href.indexOf("page=lthouse") != -1)  {
		LoadHouseTable(2);
	}
	else if (location.href.indexOf("page=house") != -1) {
		LoadDistricts();
		LoadHouseTable(0, 10);
	}
	else if (location.href.indexOf("page=builder") != -1) {
		LoadBuildersTable();
	}
});

//Загрузить новости
function NewsList() {
	alert(ExtractGetParam());
	//Иконка загрузки
	ShowLoadingIcon();
	//Загрузим новости
	$.post("actions.php?action=news_list", null, function(server_response) {
		$("#page_content").html(server_response);
	}, "text");
}

//Загрузить список районов
function LoadDistricts() {
	
	//Покажем иконку загрузки 
	$("#districts_content").html("<div id='load_img' style='margin-top: 20px; text-align: center;'></div>");
	$("#load_img").html(loadImg);
	
	$.post("actions.php?action=get_districts", null, function(server_response) {
		$("#districts_content").html(server_response);
	}, "text");
}

//Загрузить таблицу домов
function LoadHouseTable(nl, district_id) {

	//Уберем подсказки
	$("#cluetip").hide();
	
	//Иконка загрузки
	ShowLoadingIcon();
	
	var nl_str = '';
	if ( nl == 1 ) nl_str = "actions.php?action=nlhouse_list";
	else if ( nl == 2 ) nl_str = "actions.php?action=lthouse_list";
	else nl_str = "actions.php?action=house_list&id=" + district_id;	
	
	$.post(nl_str, null, function(server_response) {
		//Очистим содержимое контента
		var content = $("#page_content");
		content.html("");		
		//Сформируем таблицу
		var table = "<table id='house_table' class='tablesorter' cellpadding='0' cellspacing='0'>";
		var row_num = 0;
		for (var row in server_response) {
			if (row_num == 0) table += "<thead>";
			if (row_num == 1) table += "<tbody>";
			var id = server_response[row]["id"];
			for (var cell in server_response[row]) {
				var val = server_response[row][cell];
				if (cell == "BUILDER_ID") continue;
				//Начало строки				
				if (cell == "id") {
					table += "<tr id='row" + id + "'>";
					if (row_num > 0)
						table += "<td style='padding-left:10px;'>" + row_num + "</td>";
					else table += "<th>№</th>";
					continue;
				}
				//Ячейки шапки
				if (row_num == 0) {
					if ( nl > 0 ) {
						if (cell == "quarter") continue;
						if (cell == "year") continue;
						if (cell == "num_contract") continue;
						if (cell == "state") continue;
						if (cell == "plan_date") continue;
					}
					if (nl == 0) {
						if (cell == "district_name") continue;
					}					
					if (cell == "builder_id") continue;					
					if (cell == "map_link" || cell == "photo") {
						table += "<th>";
						table += "&nbsp;";
						table += "</th>";
						continue;
					}					
					if (cell == "height" ||
						cell == "area" ||
						cell == "num_apart" ||
						cell == "plan_date" ||
						cell == "num_contract" ||
						cell == "state" ||
						cell == "docs") {
							table += "<th class='use_tips' title='|" + val + "'>";
							table += "<img bordr='0' src='../images/" + cell + ".gif'>";
							table += "</th>";
							continue;
					}
					
					table += "<th>";
					table += val;
					table += "</th>";
				}
				//Ячейки строк
				else {

					if ( nl > 0 ) {
						if (cell == "quarter") continue;
						if (cell == "year") continue;
						if (cell == "num_contract") continue;
						if (cell == "state") continue;
						if (cell == "plan_date") continue;
					}
					
					if (nl == 0) {
						if (cell == "district_name") continue;
					}			
					//Застройщик		
					if (cell == "builder_name") {
						table += "<td>";
						var b_link = "actions.php?action=get_builder&id=" + server_response[row]["builder_id"];
						table += "<font class='builder_tf use_tips2' mytitle='" + val + "'" + 
							" rel='" + b_link + "'>" + val + "</font>";
						table += "</td>";
						continue;
					}
					if (cell == "builder_id") continue;
					
					//Квартал - выводим квартал+год
					if (cell == "quarter") {
						var q = server_response[row]["quarter"];
						var y = server_response[row]["year"];
						if (q > 0 && y > 0)
							table += "<td>" + y + "/" + GetQuarter(q - 0) + "</td>";
						else table += "<td>&nbsp;</td>";
						continue;
					}
					if (cell == "year") continue;
					
					//Показать на карте
					if (cell == "map_link" && val != "") {
						table += "<td><img src='../images/globe.gif' border='0' " +
							"alt='На карте' class='map_img use_tips' title='|Показать на карте'" +
							" onclick='javascript:{ShowOnMap(\"" + val + "\");}'></td>";
						continue;
					}
					
					//Показать фото
					if (cell == "photo") {
						if (val > 0)
							table += "<td><img src='../images/camera.gif' class='photo_img use_tips' title='|Фотографии дома'" +
							"alt='Фото' onclick='javascript:{" +
								"ShowPhotos(" + id + "); }'></td>";
						else table += "<td>&nbsp;</td>";
						continue;
					}
					
					//Показать документацию
					if (cell == "docs") {
						if (nl > 0) {
							table += "<td><font color='red'><b>";
							table += (val == "" || val == 0) ? "&nbsp;" : val;
							table += "</b></font></td>";
						}
						else {
							table += "<td>";
							if (val != "") {
								table += "<img bordr='0' src='../images/docs_row.gif' " +
									"mytitle='Разрешительная документация|" + val + "' class='doc_img use_tips1'>";
							}
							else table += "&nbsp;";
							table += "</td>";
						}
						continue;
					}
					
					//Другие данные
					table += "<td>";
					table += (val == "" || val == 0) ? "&nbsp;" : val;
					table += "</td>";					
				} 
			}
			//Конец строки
			table += "</tr>";
			if (row_num == 0) table += "</thead>";
			row_num++;
		}
		if (row_num == 1) table += "<tbody><tr><td></td></tr></tbody>";
		if (row_num > 1) table += "</tbody>";
		table += "</table>";
		
		//Покажем таблицу
		//$("#page_content").append("qq="+server_response);
		$("#page_content").append(table);
		var table_obj = $("#house_table");
				
		//Подсветка заголовков столбцов
		$("thead > tr > th", table_obj).hover(
	      	function () {
	      		$(this).css("opacity","0.8");
	      	},
	      	function () {
	      		$(this).css("opacity","1");
	      	}
	    );
	    
	    $("thead > tr > th", table_obj).click(
	    	function () { 
			    //Уберем подсказки
				$("#cluetip").hide();
			}
		);

	    //Сортировка и стили для таблицы
	    table_obj.tablesorter({
			sortList: [[0,0]], 
			widgets: ["zebra"],
			headers: { 
				1: { sorter: false },
				2: { sorter: false },
				12: { sorter: false }				
			}			
		});
		table_obj.trigger("update");
		table_obj.focus();
		
		//Устанавливаем подсказки
		//Простые
		$('.use_tips').cluetip({ 
			splitTitle: '|',	
	    	showTitle: false,
	    	cursor: "pointer",
	    	width: 110
	  	});
	  	//Разрешающая документация
	  	$('.use_tips1').cluetip({ 
			splitTitle: '|',	
	    	cursor: "pointer",
	    	width: 250,
	    	arrows: true,
	    	sticky: true,
			closePosition: 'bottom',
			closeText: '<img src="../images/cross.gif" />',
			activation: 'click',
			titleAttribute: 'mytitle',
		    fx: {
				open: 'fadeIn', // can be 'show' or 'slideDown' or 'fadeIn'
				openSpeed: 200
		    }
	  	});
	  	//Застройщик
	  	$(".use_tips2").cluetip({
	  		arrows: true,
	    	sticky: true,
			closePosition: 'bottom',
			waitImage: '<img src="../images/ajax-loader.gif" />',
			closeText: '<img src="../images/cross.gif" />',
			activation: 'click',
	  		titleAttribute: 'mytitle',
	    	width: 350,
	    	fx: {
				open: 'fadeIn', // can be 'show' or 'slideDown' or 'fadeIn'
				openSpeed: 200
		    }
	  	});

	}, "json");
	
}

//Загрузить таблицу застройщиков по id района
function LoadBuildersTable() {

	ShowLoadingIcon();
	
	$.post("actions.php?action=builder_list", null, function(server_response) {
		//Очистим содержимое контента
		var content = $("#page_content");
		content.html("");
		//Сформируем таблицу
		var table = "<table id='builders_table' class='tablesorter' cellpadding='0' cellspacing='0'>";
		var row_num = 0;
		for (var row in server_response) {
			if (row_num == 0) table += "<thead>";
			if (row_num == 1) table += "<tbody>";
			for (var cell in server_response[row]) {
				var val = server_response[row][cell];
				if (cell == "id") {
					table += "<tr id='row" + val + "'>";
					if (row_num > 0)
						table += "<td style='padding-left:10px;'>" + row_num + "</td>";
					else table += "<th>№</th>";
					continue;
				}
				if (cell == "license") continue;//не показываем лицензию (временно?)
				
				//Начало ячейки
				table += row_num == 0 ? "<th>" : "<td>";
				//если ссылка
				if (row_num != 0 && cell == "website" && val != "") 
					table += "<a href='" + val + "' target='_blank'>" + val + "</a>";
				else table += val == "" ? "&nbsp;" : val;
				//Конец ячейки
				table += row_num == 0 ? "</th>" : "</td>";
			}
			table += "</tr>";
			if (row_num == 0) table += "</thead>";
			row_num++;
		}
		if (row_num == 1) table += "<tbody></tbody>";
		if (row_num > 1) table += "</tbody>";
		table += "</table>";

		//Покажем таблицу
		$("#page_content").append(table);
		var table_obj = $("#builders_table");
				
		//Подсветка заголовков столбцов
		$("thead > tr > th", table_obj).hover(
	      	function () {
	      		$(this).css("opacity","0.8");
	      	},
	      	function () {
	      		$(this).css("opacity","1");
	      	}
	    );

		//Подсветка строк таблицы
		$("tbody > tr", table_obj).hover(
	      	function () {
				var this_row = $(this);
				this_row.data("stored_class", this_row.attr("class"));
				this_row.attr("class", "t_row_hl");
	      	},
	      	function () {
				var this_row = $(this);
				this_row.attr("class", this_row.data("stored_class"));
				this_row.removeAttr("stored_class");
	      	}
	    );
	    
	    //Сортировка и стили для таблицы
	    table_obj.tablesorter({
			sortList: [[0,0]], 
			widgets: ["zebra"]
		});
		table_obj.trigger("update");
		table_obj.focus();

	}, "json");
}

//Показать фото по photo_id для дома house_id
function ShowPhotos(house_id) {

	//Создадим окно
	CreateModal("Фотографии дома", 705, 620);
	//Добавим кнопку "закрыть"
	$("#modal_control").html("<div class='button' style='margin-right:10px; " +
		"margin-top:10px;' onclick='javascript:{$.modal.close();}'>Закрыть</div>");
	//Запросим контент
	GetViewContent(house_id, 0);

	/*		
	window.open('actions.php?action=show_photo&id=' + id,'',
		'toolbar=0, location=0,directories=0, menubar=0, scrollbars=0, resizable=1, width=800, height=600, left=50, top=50');
	*/
}

function GetViewContent(house_id, photo_id) {

	//Покажем иконку загрузки
	$("#modal_content").html($("<div style='padding-top: 200px;' align='center'></div>").html(loadImg));
	//Загрузим контент
	$.post("actions.php?action=show_photo_view&house_id=" + house_id + "&photo_id=" + photo_id,
		null, function(server_response) {
		//Отобразим контент
		if (server_response == "404")
			$("#modal_content").html("<div style='margin-top: 50px; text-align: center;'" +
				"class='text'>Нет фото</div>");
		else {
			$("#modal_content").html(server_response);
		}
	}, "text");
	
}

function ShowOnMap(map_link) {
	
	//Загрузим картинку		
	var pic_url = "http://www.admgor.nnov.ru/map/drawobj.php?" + map_link.split("?")[1];
	var pic = new Image();
	pic.src = pic_url;

	//Откроем окно
	CreateModal("Показать на карте", 554, 570);
	//Добавим кнопку "закрыть"
	$("#modal_control").html("<div class='button' style='margin-right:10px; " +
		"margin-top:10px;' onclick='javascript:{$.modal.close();}'>Закрыть</div>");
	//Покажем иконку загрузки
	$("#modal_content")
		.html($("<div style='padding-top: 200px;' align='center'></div>")
		.html(loadImg));

	$(pic).bind("load",  function() {
		$("#modal_content").html("<div style='padding: 30px 50px 10px 50px;'>" +
			"<div id='pic_content' style='width: 450px; border: 1px solid #DDA04F;'></div></div>");
		$("#pic_content").html(pic);
	});
}

//Создание модального окна
function CreateModal(title, w, h) {
	var window_data =
		"<div id='modal_head'></div>"+
		"<div id='modal_content'></div>" +
		"<div id='modal_control'></div>";
   	$(window_data).modal({
   		onOpen: function (dialog) {
				  	dialog.overlay.fadeIn(200, function () {
						dialog.container.fadeIn(200);
			      		dialog.data.fadeIn();
				  	});
				},
   		onClose: function (dialog) {
					dialog.data.fadeOut(200);
				  	dialog.overlay.fadeOut(200, function () {
				    	$.modal.close();
					});
				},
		close: false,
		containerCss: {
			height: h,
			width: w 
		}
	});
	$("#modal_head").html(title);
	$("#modal_content").css("height", h - 70);
}

// Показать иконку загрузки
function ShowLoadingIcon() {
	$("#page_content").html("<div id='load_img' style='margin-top: 200px; text-align: center;'></div>");
	$("#load_img").html(loadImg);
}

//Функция вывода квартала - 1 => I, 2 => II и т.д.
function GetQuarter(q) {
	switch (q) {
		case 1: return "I";
		case 2: return "II";
		case 3: return "III";
		case 4: return "IV";
	}
	return null;
}
