var CJSearch = function () {
}

CJSearch.prototype.init = function () {
	$.ajaxSetup({
		type: "POST",
		url: "rpc.php",
		timeout: 30000,
		cache: false,
		beforeSend: function (xhr) {
			$("#loading").show();
			return true;
		},
		success: function (data, textStatus) {
			if (!data) {
				this.error(null, "No data recived from server.", null, data);
				return;
			}
			if (!data.status) {
				this.error(null, "Invalid data received from server.", null, data);
				return;
			}
			if (data.status != "OK") {
				if (data.result) {
					this.error(null, data.result, null, data);
				} else {
					this.error(null, "Unknown error generated on server.", null, data);
				}
				return;
			}
			CJS.handleJsonRpcResponse(data);
		},
		error: function (xhr, textStatus, errorThrown, data) {
			var message = "<b>AJAX Transfer Error</b><br />\n";
			if (errorThrown) {
				message += "<b>Error Thrown:</b> " + errorThrown + "<br />\n";
			}
			if (textStatus) {
				message += textStatus + "<br />\n";
			}
			CJS.handleJsonRpcError(message, data);
		},
		complete: function (xhr, textStatus) {
			$("#loading").hide();
		}
	});

	$("#cjsearch form")
		.attr("action", "javascript:void(0)")
		.submit(function (e) { CJS.newSearch($(this).children(".query").val()); e.preventDefault(); return false; })
		.children(".query")
			.val(this.getParam("keywords"))
		.end();

	if ($("#results").children().length) {
		this.updateHeader();
		this.updatePagination();
		this.updateFooter();
	}
}

CJSearch.prototype.handleJsonRpcError = function (message, data) {
	if (data) {
		alert(data.method + " failed... \n" + message);
	} else {
		alert(message);
	}
}

CJSearch.prototype.handleJsonRpcResponse = function (data) {
	if (data.method == "search") {
		$("#results").empty().html(data.result);
		this.updateResults();
	}
}

CJSearch.prototype.newSearch = function (keywords) {
	keywords = $.trim(
					keywords
					.replace(/[^a-z0-9.-]/ig, " ")
					.replace(/ +/g, " ")
				)
				.replace(/ /g, "-");
	if (keywords.length) {
		document.location.href = "search-" + keywords + ".html";
	} else {
		document.location.href = "index.php";
	}
}

CJSearch.prototype.updateSearch = function (params) {
	$.scrollTo("#cjsearch", 800);

	var defaults = {
		keywords: this.getParam("keywords"),
		size: this.getParam("size"),
		page: 1,
		sort: this.getParam("sort"),
		order: this.getParam("order"),
		low: this.getParam("low"),
		high: this.getParam("high")
	};
	$.jsonRpc({
		method: "search",
		params: [$.extend(defaults, params)]
	});
}

CJSearch.prototype.updateResults = function () {
	this.updateHeader();

	$("#results .result").each(function (i) {
		CJS.updateResult(i);
	});

	this.updatePagination();
	this.updateFooter();
}

CJSearch.prototype.updateResult = function (num) {
	$("#results .result")
	.eq(num)
		.hover(function () { $(this).addClass("hover"); }, function () { $(this).removeClass("hover"); })
		.find(".image img, .advertiser *, .name, .buy")
			.click(function () { 
				CJS.link(num /*$(this).parents().filter(".result").attr("num")*/);
			})
		.end()
	.end()
	
	var description = $("#results .description").eq(num);
	var sale = $("#results .sale").eq(num);
	var price = $("#results .price").eq(num);
	
	description.html(CJS.summarize(description.html()));
	if ($.trim(sale.text()).length > 0) {
		sale.attr("title", "Sale Price: " + $.trim(sale.text()));
		price.addClass("rebate");
	}
}

CJSearch.prototype.getParam = function (param) {
	return $("#params ." + param).text();
}

CJSearch.prototype.updateHeader = function () {
	if (!$("#header").length) {
		$(DIV)
			.prependTo("#results")
			.attr("id", "header")
			.append(H1).children(":last")
				.text(this.getParam("keywords"))
				.prepend(SPAN).children(":first")
					.text("Search for: ")
				.end()
			.end();
	}

	var total = parseInt(this.getParam("total"));
	var size = parseInt(this.getParam("size"));
	var page = parseInt(this.getParam("page"));
	var limit_low = ((page - 1) * size + 1);
	var limit_high = limit_low + ($("#results .result").length) - 1;
	if (!$("#results .result").length) {
		limit_low = 0;
		limit_high = 0;
	}

	$("#header")
		.children(".clear")
			.remove()
		.end()
		.append(DIV).children(":last")
			.addClass("stats")
			.html("Displaying results <b>" + limit_low + "-" + limit_high + "</b> out of <b>" + total + "</b>")
		.end()
		.append(DIV).children(":last")
			.addClass("clear")
		.end();

	if (!$("#results .result").length) {
		$("#results")
			.append(DIV).children(":last")
				.addClass("empty")
				.html("No results found")
			.end();
	}
}

CJSearch.prototype.updateFooter = function () {
	$(DIV)
		.attr("id", "footer")
		.appendTo("#results")
		.append("<form></form>").children(":last")
			.addClass("ranger")
			.attr("action", "javascript:void(0)")
			.html("Price range $<input type=\"text\" /> to $<input type=\"text\" /> <input type=\"submit\" />")
			.children("input[type=text]:first")
				.val(this.getParam("low"))
			.end()
			.children("input[type=text]:last")
				.val(this.getParam("high"))
			.end()
			.children("input[type=submit]:last")
				.val("Go")
			.end()
			.submit(function (e) { CJS.updateSearch({low: $(this).children("input[type=text]:first").val(), high: $(this).children("input[type=text]:last").val()}); e.preventDefault(); return false; })
		.end()
		.append(DIV).children(":last")
			.addClass("pager")
			.html("Show <select></select> products per page")
			.children("select")
				.append("<option></option>").children(":last").attr("value", 6).html(6).end()
				.append("<option></option>").children(":last").attr("value", 12).html(12).end()
				.append("<option></option>").children(":last").attr("value", 24).html(24).end()
				.append("<option></option>").children(":last").attr("value", 48).html(48).end()
				.val(this.getParam("size"))
				.change(function () { CJS.updateSearch({size: $(this).val()}); })
			.end()
		.end()
		.append(DIV).children(":last")
			.addClass("clear")
		.end();
}

CJSearch.prototype.updatePagination = function () {
	$(DIV).attr("id", "pagination").appendTo("#results");

	var total = parseInt(this.getParam("total"));
	var size = parseInt(this.getParam("size"));
	var page = parseInt(this.getParam("page"));
	var pages = Math.ceil(total / size);
	var page_low = Math.max(page - 9, 1);
	var page_high = Math.min(page + 9, pages);

	if (page > 1) {
		$(IMG).attr("src", "previous-page.gif").click(function () { CJS.updateSearch({page: (page - 1)}); }).appendTo("#pagination");
	}
	for (var p = page_low; p <= page_high; p++) {
		var link = $(SPAN).html(p).addClass("page").appendTo("#pagination");
		if (p == page) {
			link.addClass("current");
		} else {
			link.click(function () { CJS.updateSearch({page: $(this).text()}); });
		}
	}
	if (page < pages) {
		$(IMG).attr("src", "next-page.gif").click(function () { CJS.updateSearch({page: (page + 1)}); }).appendTo("#pagination");
	}
}

CJSearch.prototype.summarize = function (text) {
	if (!text) {
		return $(SPAN);
	}

	if (text.length < 210) {
		return $(SPAN).html(text);
	}

	var summary_id = (new Date()).getTime() + "-" + Math.floor(9999*Math.random());

	return $(SPAN)
		.append(SPAN).children(":last")
			.attr("id", "less-" + summary_id)
			.html(text.substring(0, 180) + "... ")
			.append(SPAN).children(":last")
				.addClass("summarize")
				.html("(<i>more</i>)")
				.click(function () { $("#less-" + summary_id).hide(); $("#more-" + summary_id).show(); })
			.end()
		.end()
		.append(SPAN).children("span:last")
			.hide()
			.attr("id", "more-" + summary_id)
			.html(text + " ")
			.append(SPAN).children(":last")
				.addClass("summarize")
				.html("(<i>less</i>)")
				.click(function () { $("#more-" + summary_id).hide(); $("#less-" + summary_id).show(); })
			.end()
		.end()
}

CJSearch.prototype.link = function (num) {
	var result = $("#results .result").eq(num);

	this.linkerTimeout = setTimeout(function () { document.location.href = result.find(".url").attr("href"); }, 5000);

	var cancelFn = function () { clearTimeout(CJS.linkerTimeout); $("#linker").hide(); $("#linker-bg").hide(); };

	$("#linker-bg")
		.show();

	$("#linker")
		.children(".box")
			.empty()
			.append(IMG).children(":last")
				.error(function () { $(this).remove(); })
				.attr("src", result.find(".advertiser img").length ? result.find(".advertiser img").attr("src") : "")
			.end()
			.append(DIV).children(":last")
				.append("You will now be redirected to")
				.append("<b>" + result.find(".advertiser span").text() + "</b>")
				.append("<span>Cancel</span>")
				.children("span:last")
					.click(cancelFn)
				.end()
			.end()
		.end()
		.show();
	
}




var CJS = new CJSearch();

var H1 = "<h1></h1>";
var DIV = "<div></div>";
var SPAN = "<span></span>";
var IMG = "<img />";
var BR = "<br />";

$(function () {
	CJS.init();
});



