var SPiN = {
	getRequestConstants: function() {
		// return "[session][id]=" + SPiN.social.session.id + "&" + str
		// .join("&");
		return "";
	},
	input: {
		initialize: function($el) {},
		serialize: function($el) {
			return $(":input", typeof $el != "undefined" ? $el : $(document)).serialize();
		},
		validate: function($el) {}
	},
	lightbox: function(id) {
		$("#overlay").show();
		var $el = typeof id != "undefined" ? $("#lightbox-" + id) : $($(this).attr("href"));
		var height = $el.height();
		var width = $el.width();
		$el.css({
			height: "200px",
			marginLeft: "-100px",
			width: "200px"
		}).addClass("loadingindicator").children().css("visibility", "hidden").parent().fadeIn(500, function() {
			$(this).animate({
				height: height
			}, 500, function() {
				$(this).animate({
					marginLeft: "-" + parseInt(width / 2) + "px",
					width: width
				}, function() {
					$(".lightbox-hide", $el).hide();
					$(".lightbox-show", $el).show();
					$(this).removeClass("loadingindicator").children().css("visibility", "visible");
				});
			});
		});
		y = $(window).scrollTop();
		$el = $.browser.safari ? $("body") : $("html");
		$el.animate({
			scrollTop: 0
		}, 500);
	},
	pagination: function(Obj) {
		this.data = [];
		this.callback = Obj.callback;
		this.columns = Obj.columns;
		this.currentPage = 0;
		this.filtered = false;
		this.firstRow = 0;
		this.lastRow = 0;
		this.node = null;
		this.orderBy = Obj.hasOwnProperty("orderBy") ? Obj.orderBy : "created DESC";
		this.perPage = Obj.hasOwnProperty("perPage") ? Obj.perPage : 10;
		this.request = null;
		this.requestConstants = Obj.hasOwnProperty("requestConstants") ? Obj.requestConstants : "";
		this.table = Obj.table;
		this.totalPages = 0;
		this.totalRows = 0;
		this.url = Obj.hasOwnProperty("url") ? Obj.url : "commands/pagination.php";
		this.where = {
			constants: "",
			defaultValue: "1 = 1",
			value: "1 = 1"
		};
	},
	queryString: function(param) {
		var url = location.href;
		var index = url.indexOf("?");
		if (index == -1) return null;
		var str = [];
		
		function queryString(el) {
			el = el.split("=");
			str[el[0]] = el[1];
		}
		
		url.slice(index + 1).split("&").forEach(queryString);
		return str[param];
	},
	request: function(type, url, data, success, failure, context, id) {
		var Obj = {
			data: SPiN.getRequestConstants() + "timestamp=" + new Date().getTime() + "&" + data,
			error: function(XHR, textStatus, errorThrown) {
				if (errorThrown != "abort") {
					if (failure) failure(errorThrown);
					else alert(errorThrown);
				}
			},
			success: function(response) {
				if (typeof id != "undefined") delete SPiN.requests[id];
				success.apply(this, [response]);
			},
			type: type,
			url: url
		};
		if (typeof context != "undefined") Obj.context = context;
		if (typeof id != "undefined") return SPiN.requests[id] = $.ajax(Obj);
		return $.ajax(Obj);
	},
	requests: [],
	scroller: function(Obj) {
		this.node = Obj.node;
		this.count = Obj.count;
		this.interval = Obj.hasOwnProperty("interval") ? Obj.interval : 1;
		this.ratio = Obj.ratio;
		this.speed = Obj.hasOwnProperty("speed") ? Obj.speed : 12;
	},
	storage: []
};

SPiN.pagination.prototype.abort = function() {
	if (this.request != null) this.request.abort();
};

SPiN.pagination.prototype.fetch = function(page) {
	this.filtered = this.where.value != this.where.defaultValue;
	this.request = SPiN.request("GET", this.url, "columns=" + encodeURIComponent(this.columns) + "&table=" + encodeURIComponent(this.table) + "&orderby=" + this.orderBy + "&where=" + encodeURIComponent((this.where.constants != "" ? this.where.constants + " AND " : "") + this.where.value) + "&perpage=" + this.perPage + "&page=" + page + (this.requestConstants != "" ? "&" + this.requestConstants : ""), function(response) {
		var data = JSON.parse(response);
		this.data = data[1];
		this.currentPage = page;
		this.totalRows = data[0];
		this.totalPages = this.totalRows > 0 ? parseInt(this.totalRows / this.perPage) + (this.totalRows % this.perPage ? 1 : 0) : 1;
		this.lastRow = this.data ? Math.min(this.currentPage * this.perPage, this.totalRows) : 0;
		this.firstRow = this.data ? this.currentPage * this.perPage - (this.perPage - 1) : 0;
		this.statistics();
		this.callback();
	}, false, this);
};

SPiN.pagination.prototype.firstPage = function() {
	this.fetch(1);
};

SPiN.pagination.prototype.lastPage = function() {
	this.fetch(this.totalPages);
};

SPiN.pagination.prototype.nextPage = function() {
	var nextPage = parseInt(this.currentPage) + 1;
	if (nextPage <= parseInt(this.totalPages)) this.fetch(nextPage);
};

SPiN.pagination.prototype.previousPage = function() {
	this.fetch(parseInt(this.currentPage) - 1);
};

SPiN.pagination.prototype.statistics = function() {
	var $pagination = $(".pagination");
	if ($pagination) if (this.perPage > -1) {
		var str = [];
		if (this.currentPage > 1) str.push("<a class=\"navigation pagination-prev\" href=\"#\"><span>&lt;</span> Prev</a> ");
		str.push("page&nbsp;&nbsp;");
		var lbound = Math.max(Math.floor(this.currentPage / 7) * 7, 1);
		var ubound = Math.min(lbound + 6, this.totalPages);
		if (lbound >= 7) str.push("...&nbsp;&nbsp;&nbsp;");
		var i = lbound;
		while (i <= ubound) {
			str.push("<a class=\"pagination-navigation", (i == this.currentPage ? " selected" : ""), "\" href=\"#\">" + i + "</a> ");
			i++;
		}
		if (ubound < this.totalPages) str.push("... ");
		if (this.currentPage < this.totalPages) str.push("<a class=\"navigation pagination-next\" href=\"#\">Next <span>&gt;</span></a>");
		var parent = this;
		$pagination.html(str.join(""));
		$pagination.find(".pagination-prev").click(function() {
			parent.previousPage();
			return false;
		});
		$pagination.find(".pagination-next").click(function() {
			parent.nextPage();
			return false;
		});
		$pagination.find(".pagination-navigation").click(function() {
			parent.fetch($(this).text());
			return false;
		});
	}
};

SPiN.scroller.prototype.scrollLeft = function(x, callback) {
	if (typeof animator != "undefined") window.clearInterval(animator);
	var countBehind = this.node.scrollLeft / this.ratio;
	if (countBehind != 0) {
		if (!x) x = this.node.scrollLeft - this.ratio * Math.min(countBehind, this.count);
		animator = window.setInterval(function(node, speed) {
			return function() {
				node.scrollLeft = Math.max(node.scrollLeft - speed, x);
				if (node.scrollLeft == x) {
					window.clearInterval(animator);
					if (typeof callback != "undefined") callback();
				}
			};
		}(this.node, this.speed), this.interval);
	}
};

SPiN.scroller.prototype.scrollRight = function(callback) {
	if (typeof animator != "undefined") window.clearInterval(animator);
	var countAhead = (this.node.scrollWidth / this.ratio) - ((this.node.scrollLeft / this.ratio) + this.count);
	if (countAhead != 0) {
		var x = this.node.scrollLeft + this.ratio * Math.min(countAhead, this.count);
		animator = window.setInterval(function(node, speed) {
			return function() {
				node.scrollLeft = Math.min(node.scrollLeft + speed, x);
				if (node.scrollLeft == x) {
					window.clearInterval(animator);
					if (typeof callback != "undefined") callback();
				}
			};
		}(this.node, this.speed), this.interval);
	}
};

$(document).ready(function() {
	$("a[rel='lightbox']").click(function() {
		SPiN.lightbox.apply(this);
		return false;
	});
	$("form").not(".script").each(function() {
		$(this).validate();
	});
	$(".lightbox input[type=submit]").click(function() {
		var $form = $(this).parents("form");
		if ($form.valid()) {
			var $el = $form.parents(".lightbox");
			$el.prepend("<div class=\"lightbox-loadingindicator\"></div>");
			SPiN.request("POST", $form.attr("action"), SPiN.input.serialize($form), function() {
				alert("Thanks for getting in touch! Someone from our team will get back to you shortly.");
				$el.find(".lightbox-footer-close").click();
			});
		}
		return false;
	});
	$(".lightbox-footer-close, .lightbox-header-close").click(function() {
		$(this).parent().parent().fadeOut(500, function() {
			$(this).find(".lightbox-loadingindicator").remove();
			$("#overlay").hide();
		});
		var $el = $.browser.safari ? $("body") : $("html");
		$el.animate({
			scrollTop: y
		}, 500);
		return false;
	});
	$(".newsletter-submit").click(function() {
		var $el = $(this);
		var $form = $el.parents("form");
		if ($form.valid()) {
			$el.hide().after("<span class=\"newsletter-status loadingindicator\">Subscribing...</span>");
			SPiN.request("POST", "commands/mailinglist.php", SPiN.input.serialize($form), function() {
				$el.next().removeClass("loadingindicator").text("Thank you!");
			}, function(error) {
			// $el.next().remove();
			// $el.show();
			// alert(error);
			});
		}
		return false;
	});
	$("#header-club-newsletter").click(function(e) {
		if ($(e.target).closest("form").length == 0) {
			if ($(this).hasClass("out")) $(this).animate({
				right: "-380px"
			}, 500, function() {
				$(this).removeClass("out");
			});
			else $(this).animate({
				right: "0"
			}, 500, function() {
				$(this).addClass("out");
			});
		}
	});
});
