String.prototype.trim = function() { 
	return this.replace(/^\s+|\s+$/g, ''); 
}
String.prototype.isEmpty = function() { 
	return this.length == 0 || this.match(/^\s+$/); 
}

window.AlleMultiSearch = {
		availableHostPrefixes : null,
		currentTaskId : null,
		currentHostPrefix : "",
		selectRandomHostForRequest : function() {
			var hostName = window.location.hostname;
			if (AlleMultiSearch.availableHostPrefixes) {
				var host = AlleMultiSearch.availableHostPrefixes[Math.floor(Math.random() * AlleMultiSearch.availableHostPrefixes.length)];
				if (hostName.indexOf("alleszukacz.pl") != -1) {
					hostName = host + ".alleszukacz.pl";
				} else if (hostName == "localhost") {
					hostName = host + ".localhost";
				}
			}
			AlleMultiSearch.currentHostPrefix = "http://" + hostName + ((window.location.port) ? ":" + window.location.port : "");
		},
		cancelCurrentTask : function() {
			if (AlleMultiSearch.currentTaskId) {
				var url = AlleMultiSearch.currentHostPrefix + "/cancel?taskId=" + AlleMultiSearch.currentTaskId + "&callback=?";
				$.getJSON(url, function(data) {});
				AlleMultiSearch.currentTaskId = null;
			}
		},
		performSearch : function() {
			var data = location.search;
			if (!data || data.indexOf("?") != 0 || data.length < 9) {
				AlleMultiSearch.displaySearchFormError("Bledne zapytanie");
				return;
			}
			data = data.substring(1);

			AlleMultiSearch.cancelCurrentTask();
			AlleMultiSearch.selectRandomHostForRequest();
			AlleMultiSearch.showProgress();
			var url = AlleMultiSearch.currentHostPrefix + "/szukaj?" + data + "&callback=?";
			$.getJSON(url, function(data) {
				if (data.success) {
					AlleMultiSearch.currentTaskId = data.success.taskId;
					AlleMultiSearch.fakeProgress();
					setTimeout(AlleMultiSearch.checkResults, 5000);
				} else {
					AlleMultiSearch.displaySearchFormError(data.error.message);
				}
			});

		},
		checkResults : function() {
			if (!AlleMultiSearch.currentTaskId) {
				return;
			}
			var url = AlleMultiSearch.currentHostPrefix + "/check?taskId=" + AlleMultiSearch.currentTaskId + "&callback=?";
			$.getJSON(url, function(data) {
				if (data.success) {
					if (!data.success.finished) {
						AlleMultiSearch.updateProgress(data.success.progress);
						setTimeout(AlleMultiSearch.checkResults, 5000);
					} else {
						AlleMultiSearch.presentResults(data.success.userResults);
						AlleMultiSearch.cancelCurrentTask();
					} 
				} else {
					AlleMultiSearch.hideProgress();
					$("#searchResults").empty();
					AlleMultiSearch.displaySearchFormError(data.error.message);
					AlleMultiSearch.cancelCurrentTask();
				}
			});
		},
		showProgress : function() {
			$("#progress").show();
			$("#progress").progressbar({ value : 0 });
		},
		shouldFakeProgress : true, 
		fakeProgress : function() {
			if (AlleMultiSearch.shouldFakeProgress) {
				var value = $("#progress").progressbar('option', 'value');
				if (value < 95) {
					value++;
					$("#progress").progressbar('option', 'value', value);
					setTimeout(AlleMultiSearch.fakeProgress, 1000);
				}
			}
		},
		updateProgress : function(progress) {
			var value = (progress.fetchItemsInfoProgress * 100).toFixed(0);
			if (value > 0) {
				$("#progress").progressbar('option', 'value', value);
			}
		},
		hideProgress : function() {
			$("#progress").hide();
		},
		drawStars : function(where, fileName, amount) {
			for (var i = 0; i < amount; i++) {
				where.append('<img src="gfx/' + fileName + '" />');
			}
		},
		appendStars : function(where, rating) {
			if (rating == 1) {
				AlleMultiSearch.drawStars(where, 'star1.gif', 1);
			} else if (rating == 2) {
				AlleMultiSearch.drawStars(where, 'star1.gif', 2);
			} else if (rating == 3) {
				AlleMultiSearch.drawStars(where, 'star1.gif', 3);
			} else if (rating == 4) {
				AlleMultiSearch.drawStars(where, 'star1.gif', 4);
			} else if (rating >= 5 && rating <= 9) {
				AlleMultiSearch.drawStars(where, 'star5.gif', 1);
			} else if (rating >= 10 && rating <= 14) {
				AlleMultiSearch.drawStars(where, 'star5.gif', 2);
			} else if (rating >= 15 && rating <= 19) {
				AlleMultiSearch.drawStars(where, 'star5.gif', 3);
			} else if (rating >= 20 && rating <= 24) {
				AlleMultiSearch.drawStars(where, 'star5.gif', 4);
			} else if (rating >= 25 && rating <= 49) {
				AlleMultiSearch.drawStars(where, 'star25.gif', 1);
			} else if (rating >= 55 && rating <= 74) {
				AlleMultiSearch.drawStars(where, 'star25.gif', 2);
			} else if (rating >= 75 && rating <= 99) {
				AlleMultiSearch.drawStars(where, 'star25.gif', 3);
			} else if (rating >= 100 && rating <= 124) {
				AlleMultiSearch.drawStars(where, 'star25.gif', 4);
			} else if (rating >= 125 && rating <= 249) {
				AlleMultiSearch.drawStars(where, 'star125.gif', 1);
			} else if (rating >= 250 && rating <= 374) {
				AlleMultiSearch.drawStars(where, 'star125.gif', 2);
			} else if (rating >= 375 && rating <= 499) {
				AlleMultiSearch.drawStars(where, 'star125.gif', 3);
			} else if (rating >= 500 && rating <= 624) {
				AlleMultiSearch.drawStars(where, 'star125.gif', 4);
			} else if (rating >= 625 && rating <= 1249) {
				AlleMultiSearch.drawStars(where, 'star625.gif', 1);
			} else if (rating >= 1250 && rating <= 1874) {
				AlleMultiSearch.drawStars(where, 'star625.gif', 2);
			} else if (rating >= 1875 && rating <= 2499) {
				AlleMultiSearch.drawStars(where, 'star625.gif', 3);
			} else if (rating >= 2500 && rating <= 3124) {
				AlleMultiSearch.drawStars(where, 'star625.gif', 4);
			} else if (rating >= 3125 && rating <= 6249) {
				AlleMultiSearch.drawStars(where, 'star3125.gif', 1);
			} else if (rating >= 6250 && rating <= 9374) {
				AlleMultiSearch.drawStars(where, 'star3125.gif', 2);
			} else if (rating >= 9375 && rating <= 12499) {
				AlleMultiSearch.drawStars(where, 'star3125.gif', 3);
			} else if (rating >= 12500) {
				AlleMultiSearch.drawStars(where, 'star3125.gif', 4);
			}
		},
		presentResults : function(userResults) {
			$("#noresults").hide();
			$("#searchResults").empty();
			$(userResults).each(function(idx, userResult) {
				var tpl = $("#userTemplate").clone();
				tpl.removeAttr("id");
				tpl.css("display", "block");
				tpl.find(".username").text(userResult.sellerLogin);
				tpl.find(".userrank").text(userResult.sellerRating);
				AlleMultiSearch.appendStars(tpl.find(".stars"), userResult.sellerRating);
				tpl.find(".userlink").attr("href", tpl.find(".userlink").attr("href") + userResult.sellerId);
				tpl.find(".usermylink").attr("href", tpl.find(".usermylink").attr("href") + userResult.sellerId);

				$(userResult.phraseResult).each(function(idx2, phraseResult) {
					var phraseTmp = $("#itemHeaderTemplate").clone();
					phraseTmp.removeAttr("id");
					phraseTmp.find(".itemName").text(phraseResult.phrase + ":");
					tpl.append(phraseTmp);
					var counter = 0;
					$(phraseResult.categories).each(function(idx3, category) {
						$(category.items).each(function(idx4, item) {
							var itemTpl = $("#itemTemplate").clone();
							itemTpl.removeAttr("id");
							itemTpl.find(".itemlink").attr("href", itemTpl.find(".itemlink").attr("href") + item.id);
							itemTpl.find(".name a").text(item.name);
							if (item.price != 0) {
								itemTpl.find(".price .bidPrice").text(item.price.toFixed(2));
							} else {
								itemTpl.find(".price .bidPrice").hide();
							}
							if (item.buyNowPrice != 0) {
								itemTpl.find(".price .buyNowPrice").text(item.buyNowPrice.toFixed(2));
							} else {
								itemTpl.find(".price .buyNowPrice").hide();
							}
							
							itemTpl.find(".minPostageCost").text(AlleMultiSearch.findMinPostagePriceForItem(item.postageOptions));
							
							$(item.postageOptions).each(function(idx4, postageOption) {
								var fileName = "";
								if (postageOption.name == "Przesyłka kurierska") {
									fileName = 'alle-kurier.png';
								} else if (postageOption.name == "Odbiór osobisty") {
									fileName = 'alle-osobisty.png';
								} else if (postageOption.name == "Paczka pocztowa priorytetowa") {
									fileName = 'alle-paczka-priorytet.png';
								} else if (postageOption.name == "Paczka pocztowa ekonomiczna") {
									fileName = 'alle-paczka-zwykla.png';
								} else if (postageOption.name == "Przesyłka pobraniowa") {
									fileName = 'alle-pobranie-zwykle.png';
								} else if (postageOption.name == "Przesyłka pobraniowa priorytetowa") {
									fileName = 'alle-pobranie-priorytet.png';
								} else if (postageOption.name == "Przesyłka kurierska pobraniowa") {
									fileName = 'alle-kurier-pobranie.png';
								} else if (postageOption.name == "List ekonomiczny") {
									fileName = 'alle-zwykly.png';
								} else if (postageOption.name == "List priorytetowy") {
									fileName = 'alle-priorytet-zwykly.png';
								} else if (postageOption.name == "List polecony ekonomiczny") {
									fileName = 'alle-priorytet-zwykly.png';
								} else if (postageOption.name == "List polecony priorytetowy") {
									fileName = 'alle-priorytet.png';
								} else if (postageOption.name == "Przesyłka elektroniczna (e-mail)") {
									fileName = 'alle-mail.png';
								} else if (postageOption.name == "Zgadzam się na wysłanie przedmiotu za granicę") {
									fileName = 'alle-zagranica.png';
								}
								itemTpl.find(".postages").append(' <a href="javascript:;" class="tooltip"><img src="/gfx/' + fileName + '" alt="' + postageOption.name + ': ' + postageOption.amount + ' zł" /></a> ');
							});
							if (counter++ % 2 == 1) {
								$(itemTpl.find("td")).addClass("even");
							}
							tpl.append(itemTpl);
						}); 
					});
				});
				if (idx == 0) {
					AlleMultiSearch.appendNewSearchLink($("#searchResults"));
				}
				
				$("#searchResults").append(tpl);
				
				$("a.tooltip").hover(function(event) {
					$("body").append('<div id="tooltip">' + $(event.target).attr("alt") + '</div>');
					$("#tooltip").css("position", "absolute")
						.css("top",(event.pageY - 40) + "px")
						.css("background", "#ddd")
						.css("width", "250px")
						.css("border", "1px solid black")
						.css("padding", "5px")
						.fadeIn("fast");
					var x = event.pageX - 30;
					if (x + $("#tooltip").width() >= $(window).width() - 10) {
						x = $(window).width() - $("#tooltip").width() - 20;
					}
					$("#tooltip").css("left", x + "px")
				}, function(event) {
					$("#tooltip").remove();
				});
				$("a.tooltip").mousemove(function(event) {
					if ($("#tooltip").text() != $(event.target).attr("alt")) {
						$("#tooltip").text($(event.target).attr("alt"));
					}
					$("#tooltip").css("top",(event.pageY - 40) + "px");
					var x = event.pageX - 30;
					if (x + $("#tooltip").width() >= $(window).width() - 10) {
						x = $(window).width() - $("#tooltip").width() - 20;
					}
					$("#tooltip").css("left", x + "px");
				});

				if (idx == userResults.length - 1) {
					AlleMultiSearch.appendNewSearchLink($("#searchResults"));
				}
			});
			if ($(userResults).length == 0) {
				$("#noresults").show();
			}
			AlleMultiSearch.hideProgress();
		},
		findMinPostagePriceForItem : function(postageOptions) {
			var minPrice = -1;
			$(postageOptions).each(function(idx, postageOption) {
				if (postageOption.amount > 0) {
					if (minPrice == -1) {
						minPrice = postageOption.amount;
					} else {
						minPrice = Math.min(minPrice, postageOption.amount);
					}
				}
			});
			return minPrice > 0 ? minPrice : "-";
		},
		appendNewSearchLink : function(parent) {
			$(parent).append('<p><a href="/" style="color: blue; font-weight: bold">&lt;&lt; Nowe wyszukiwanie</a></p>');
		},
		countItemsInPhraseResult : function(phraseResult) {
			var count = 0;
			$(phraseResult.categories).each(function(idx, category) {
				count += category.items.length;
			});
			return count;
		},
		installSearchFormListeners : function() {
			AlleMultiSearch.bindSearchFieldsListeners($("#q1"), $("#q1tpl").text());
			AlleMultiSearch.bindSearchFieldsListeners($("#q2"), $("#q2tpl").text());
			$("#searchForm").submit(AlleMultiSearch.submitSearchForm);
		},
		bindSearchFieldsListeners : function(field, defaultText) {
			field.focus(function(eventObject) {
				if ($(this).attr("value").isEmpty() || $(this).attr("value").trim() == defaultText) {
					$(this).attr("value", "");
				}
				$(this).removeClass("grayed");
				$(this).addClass("notgrayed");

				AlleMultiSearch.clearSearchFormError();
			});
			field.blur(function(eventObject) {
				if ($(this).attr("value").isEmpty()) {
					$(this).attr("value", defaultText);
					$(this).removeClass("notgrayed");
					$(this).addClass("grayed");
				}
			});
		},
		submitSearchForm : function() {
			var q1 = $("#q1").val();
			var q2 = $("#q2").val();
			if (q1.isEmpty() || q1.trim() == $("#q1tpl").text()) {
				AlleMultiSearch.displaySearchFormError("Proszę wpisać pierwszy przedmiot.");
				return false;
			}
			if (q1.length < 2) {
				AlleMultiSearch.displaySearchFormError("Wprowadź co najmniej 2 znaki w polu pierwszego przedmiotu.");
				return false;
			}

			if (q2.isEmpty() || q2.trim() == $("#q2tpl").text()) {
				AlleMultiSearch.displaySearchFormError("Proszę wpisać drugi przedmiot.");
				return false;
			}
			if (q2.length < 2) {
				AlleMultiSearch.displaySearchFormError("Wprowadź co najmniej 2 znaki w polu drugiego przedmiotu.");
				return false;
			}

			if (q1.trim().toLowerCase() == q2.trim().toLowerCase()) {
				AlleMultiSearch.displaySearchFormError("Proszę wpisać dwa różne przedmioty.");
				return false;
			}
			return true;
		},
		displaySearchFormError : function(message) {
			$("#error").show();
			$(".error").text(message);
		},
		clearSearchFormError : function(message) {
			$(".error").text("");
			$("#error").hide();
		},
		attachModalsHandlers : function() {
			$("#contactLink").click(function() {
				var clone = $("#contact").clone();
				$(clone).dialog({modal: true, width: '460px'});
				$(clone).find("form").submit(function() {
					if ($(this).find("input[name=from]").attr("value").trim().isEmpty()
						|| $(this).find("input[name=from]").attr("value").trim().indexOf('@') == -1
						|| $(this).find("input[name=from]").attr("value").trim().indexOf('.') == -1) {
						alert('Proszę wpisać prawidłowy adres e-mail.');
						return false;
					}
					if ($(this).find("input[name=subject]").attr("value").trim().isEmpty()) {
						alert('Proszę wpisać temat wiadomości.');
						return false;
					}
					if ($(this).find("textarea[name=body]").val().trim().isEmpty()) {
						alert('Proszę wpisać treść wiadomości.');
						return false;
					}
					$.ajax({
						url : "/contact",
						type : "POST",
						data : $(this).serialize(),
						success : function() {
							alert("Wiadomość wysłana poprawnie.");
							clone.dialog('close');
						},
						error : function(error) {
							alert("Problem z wysłaniem wiadomości: " + error);						
						}
					});
					return false;
				});
				return false;
			});
			$(".howItWorksLink").click(function() {
				$("#howItWorks").clone().dialog({modal: true, width: '460px'});
				return false;
			});
			$(".advancedSearch").click(function() {
				$("#advancedSearchPanel").show();
				$(".advancedSearch").hide();
				$(".simpleSearch").show();
			});
			$(".simpleSearch").click(function() {
				$("#advancedSearchPanel").hide();
				$(".advancedSearch").show();
				$(".simpleSearch").hide();
				$("#city").val("");
				$("input:radio[@value=date]")[0].checked = true;
			});
		}
	}

