var Site = {
	init: function(){
		Site.tab = new Tabs($("#navigation ul"));
		
		// IRL
		var changer = new SituationChanger($("#irl-dropdown"), $("#irl-content"));
		changer.bind("complete", IRL.onSitutationChanged);
		changer.bind("follow", Site.follow);
		IRL.init();
		
		Site.general();
		
		$(".situation-select").each(function(){
			$(this).click(function(e){
				e.preventDefault();
				var link = $(e.target);
				if(!IRL.isTabSelected()){
					Site.tab.select("#tab-irl");
				}
				IRL.onSituationSelected();
				changer.load(link.attr("href"));
			});
		});
		$(".situation-back").each(function(){
			$(this).click(function(e){
				e.preventDefault();
				Site.tab.select("#tab-irl");
				IRL.onTabSelected();
			});
		});
		
		$("ul.downloads li a").each(function(){
			$(this).click(function(e){
				e.preventDefault();
				var win = window.open(e.target);
				if(win) win.focus();
			});
		});
		
		// Adress
		Site.address = new Adress();
		if(Site.address.hash.indexOf("#tab") > -1){
			Site.tab.select(Site.address.hash.replace("/", "-"));
		}else if(Site.address.hash.indexOf("#/") > -1){
			if(!IRL.isTabSelected()){
				Site.tab.select("#tab-irl");
			}
			IRL.onSituationSelected();
			changer.load(Site.address.hash.replace("#", ""));
		}
		Site.tab.bind("follow", Site.follow);
	},
	follow: function(e, hash){
		Site.address.follow(hash);
	},
	general: function(){
	    $(".tab-select").each(function(){
			$(this).click(function(e){
				e.preventDefault();
				var l = $(e.target);
				if(l.context.nodeName != "A"){
					l = l.parents("a");
				}
				var href = l.attr("href");
				Site.tab.select(href);
				if(href == "#tab-irl"){
					IRL.onTabSelected();
				}
			});
		});
	}
};
var IRL = {
	init: function(){
		IRL.wrapper = $("#irl-situations");
		IRL.comments = new Comments($("ol.comments"));
		IRL.form = new CommentsForm($("div.comment-form form"));
		IRL.formSituation = new SituationForm($("div.situation-form form"));
		IRL.tab = $("#tab-irl");
		IRL.start = $("#irl-start");
		IRL.situations = $("#irl-situations");
		IRL.start.addClass("js-active");
		IRL.situations.addClass("js-active");
		if(!IRL.situations.hasClass("selected")){
			IRL.start.addClass("selected");
		}
	},
	onTabSelected: function(){
		if(IRL.situations.hasClass("selected")){
			IRL.situations.removeClass("selected");
			IRL.start.addClass("selected");
		}
	},
	onSituationSelected: function(){
		if(!IRL.situations.hasClass("selected")){
			IRL.situations.addClass("selected");
			IRL.start.removeClass("selected");
		}
	},
	isTabSelected: function(){
		return IRL.tab.hasClass("page-sel");
	},
	onSitutationChanged: function(e){
		IRL.comments = new Comments($("ol.comments", IRL.wrapper));
		IRL.form = new CommentsForm($("div.comment-form form", IRL.wrapper));
		IRL.formSituation = new SituationForm($("div.situation-form form", IRL.wrapper));
		Site.general();
		swfobject.embedSWF("http://media.spotlesscomeback.com.s3.amazonaws.com/swf/color-select.swf", "theme-flash", "90", "85", "9", null, null, { wmode: "transparent", allowScriptAccess: "always" });
	}
};
var ThemeSelector = {
	select: function(theme){
		$("#comment-theme").val(theme);
		ThemeSelector.avatar = $(".avatar-select");
		if(ThemeSelector.theme){
			ThemeSelector.avatar.removeClass(ThemeSelector.theme);
		}
		ThemeSelector.theme = theme;
		ThemeSelector.avatar.addClass(theme);
	}
};
var AvatarSelect = function(el){
	this.el = $("ul", el);
	this.el.click($.fnbind(this.open, this));
	this.el.mouseover($.fnbind(this.over, this));
	this.el.mouseleave($.fnbind(this.out, this));
	this.avatars = $("li", this.el);
	this.event = $({});
	this.avatars.loop(function(el){
		el = $(el);
		var value = $("img", el).attr("alt");
		if(el.hasClass(this.css.selected)){
			this.selected = el;
		}
		el.mouseover($.fnbind(function(e){
			el.addClass(this.css.over);
		}, this))
		.mouseleave($.fnbind(function(e){
			el.removeClass(this.css.over);
		}, this))
		.click($.fnbind(function(e){
			if(this.isOpen){
				e.stopPropagation();
				if(this.selected){
					this.selected.removeClass(this.css.selected);
				}
				this.selected = el;
				this.selected.addClass(this.css.selected);
				this.event.trigger("change", value);
				this.close();
			}
		}, this));
	}, this);
};
AvatarSelect.prototype = {
	delay: 500,
	css: {
		open: "open",
		over: "hover",
		selected: "sel"
	},
	over: function(e){
		clearTimeout(this.timer);
	},
	out: function(e){
		this.timer = $.timeout(this.close, this.delay, this);
	},
	open: function(){
		this.el.addClass(this.css.open);
		this.isOpen = true;
	},
	close: function(){
		clearTimeout(this.timer);
		this.el.removeClass(this.css.open);
		this.isOpen = false;
	},
	bind: function(e, fn){
		this.event.bind(e, fn);
	}
};
var SituationChanger = function(drop, container){
	this.container = container;
	this.drop = new DropDown(drop);
	this.drop.bind("change", $.fnbind(this.change, this));
	this.event = $({});
};
SituationChanger.prototype = {
	address: true,
	css: {
		loading: "loading"
	},
	change: function(e, target){
		this.load($(target).attr("href"));
	},
	load: function(url){
		this.drop.select(url);
		this.container.addClass(this.css.loading);
		this.container.load(url + " #" + this.container.attr("id"), $.fnbind(this.complete, this));
		if(this.address){ this.event.trigger("follow", url.indexOf("/") != 0 ? "#/" + url : url); }
	},
	complete: function(html,status){
		this.container.removeClass(this.css.loading);
		if(status == "success"){ this.event.trigger("complete"); }
	},
	bind: function(e, fn){
		this.event.bind(e, fn);
	}
};
var Adress = function(){
	this.init();
};
Adress.prototype = {
	init: function(){
		this.hash = unescape( location["hash"]);
	},
	follow: function(val){
		if(typeof(val) != typeof(undefined)){
			this.hash = val;
			location["hash"] = escape( this.hash );
		}
		return this.hash;
	}
};
var Tabs = function(el){
	this.el = el;
	this.pages = [];
	this.links = $("a", this.el);
	this.links.loop(function(a){
		a = $(a);
		this.pages.push({"link":  a, "page": $(a.attr("href")) });
	}, this);
	this.pages = $(this.pages);
	this.pages.loop(function(obj, i){
		obj.page.addClass(this.css.script);
		obj.link.click($.fnbind(this.click, this));
		var parent = obj.link.parent();
		if(parent.hasClass(this.css.selected)){
			obj.page.addClass(this.css.active);
			parent.addClass(this.css.selected);
		}
	}, this);
	this.event = $({});
};
Tabs.prototype = {
	address: true,
	css: {
		script: "page-js-active",
		active: "page-sel",
		selected: "sel"
	},
	click: function(e){
		e.preventDefault();
		var href = $(e.target).attr("href");
		this.select(href);
	},
	select: function(href){
		this.pages.loop(function(obj){
			obj.page.removeClass(this.css.active);
			if(href == obj.link.attr("href")){
				$("li", this.el).removeClass(this.css.selected);
				obj.link.parent().addClass(this.css.selected);
				obj.page.addClass(this.css.active);
				pageTracker._trackPageview("tabs:" + href);
				if(this.address){ this.event.trigger("follow", href.replace("-", "/").replace("#", "")); }
			}
		}, this);
	},
	bind: function(e, fn){
		this.event.bind(e, fn);
	}
};
var Comments = function(el){
	this.el = el;
	this.el.addClass(this.css.script);
	this.comments = $("li", this.el);
	this.pages = Math.ceil(this.comments.length / this.perPage);
	this.paging = $("<ul class=\"" + this.css.paging + "\" />").insertAfter(this.el);
	for(var i=0;i<this.pages;i++){
		var page = i + 1;
		this.paging.append(
			$("<li />").append(
				$("<a href=\"" + this.pageLinkPrefix + page + "\">" + page + "</a>").click($.fnbind(this.click, this))
			)
		);
	}
	this.paging = $("li", this.paging);
	this.goToPage(1);
	this.reportText = $("input#comment-reported").val();
	$("p.alert a", this.el).click($.fnbind(this.report, this));
};
Comments.prototype = {
	css: {
		script: "comments-js-active",
		active: "active",
		paging: "comments-paging",
		selected: "sel"
	},
	pageLinkPrefix: "#page",
	reportLinkPrefix: "#report-",
	reportUrl: "/spotless/reportComment.ashx",
	perPage: 6,
	goToPage: function(page){
		var end = page * this.perPage;
		var start = end -  this.perPage;
		start = start < 0 ? 0 : start;
		end = end > this.comments.length ? this.comments.length : end;
		this.comments.loop(function(comment){ $(comment).removeClass(this.css.active); }, this);
		for(var i = start ;i < end; i++){ $(this.comments[i]).addClass(this.css.active); }
		this.paging.removeClass(this.css.selected);
		$(this.paging[page-1]).addClass(this.css.selected);
		this.page = page;
	},
	click: function(e){
		e.preventDefault();
		this.goToPage($(e.target).attr("href").replace(this.pageLinkPrefix, ""));
	},
	report: function(e){
		e.preventDefault();
		var id = $(e.target).attr("href").replace(this.reportLinkPrefix, "");
		$.post(this.reportUrl, { "c": id }, $.fnbind(function(obj){
			alert(this.reportText); //alert(obj.response);
		}, this), "json")
	}
};
var DropDown = function(el){
	this.el = el;
	this.el.hide();
	this.wrap = $("<div />").addClass("dropdown-js").insertBefore(this.el).append(this.el);
	this.items = $("a", this.el);
	this.selected = $("li.sel a", this.el);
	if(this.selected.length == 0){
		this.selected = $(this.items.get(0));
	}
	this.items.click($.fnbind(this.click, this));
	this.wrap.mouseenter($.fnbind(this.enter, this));
	this.wrap.mouseleave($.fnbind(this.leave, this));
	this.top = $("<p />").addClass("top").html(this.selected.text()).insertBefore(this.el);
	this.top.hover(this.hover, this.hover);
	this.top.click($.fnbind(this.open, this));
	this.selected = this.selected.parent();
	this.selected.addClass("sel");
	$(document.body).click($.fnbind(this.close, this));
	this.event = $({});
};
DropDown.prototype = {
	click: function(e){
		e.stopPropagation();
		e.preventDefault();
		var target = $(e.target);
		this.select(target.attr("href"));
		this.event.trigger("change", target);
		this.close();
	},
	select: function(url){
		var target = $("a[href=" + url + "]", this.el);
		this.selected.removeClass("sel");
		this.selected = target.parent();
		this.selected.addClass("sel");
		this.top.html(target.text());
	},
	hover: function(){
		$(this).toggleClass("hover");
	},
	enter: function(){
		if(this.timer){ clearTimeout(this.timer); }
	},
	leave: function(){
		this.timer = $.timeout(this.close, 1000, this);
	},
	open: function(e){
		e.stopPropagation();
		this.top.addClass("open");
		this.el.slideDown(200);
	},
	close: function(){
		this.top.removeClass("open");
		this.el.slideUp(200);
	},
	bind: function(e, fn){
		this.event.bind(e, fn);
	}
};
var Form = function(form){
	this.form = form;
	this.form.submit($.fnbind(this.submit, this));
	this.error = $(this.selectors.error, this.form).hide();
	this.success = $(this.selectors.success, this.form).hide();
	this.fields = {
		text: $("input.field, textarea", this.form),
		checkbox: $("input:checkbox", this.form)
	};
	this.event = $({});
};
Form.prototype = {
	css: {
		error: "error"
	},
	selectors: {
		fields: ".data",
		error: "div.error-dialog",
		success: "div.success-dialog"
	},
	submit: function(e){
		e.preventDefault();
		if(this.validate()){
			this.error.hide();
			$.post(this.form.attr("action"), this.form.serialize(), $.fnbind(this.complete, this), "json");
			this.reset();
		}else{
			this.error.animate({
				opacity: "show",
				height: "show"
			}, 500);
		}
	},
	complete: function(obj){
		if(typeof(obj) == "object"){
			this.event.trigger("submit", obj.response);
		}else{
			$("p", this.success).text(obj.response);
		}
		this.success.fadeIn();
	},
	validate: function(){
		var ret = true;
		this.fields.text.loop(function(el){
			var el = $(el);
			if(el.val() == ""){
				el.addClass(this.css.error);
				ret = false;
			}else{
				if(el.hasClass(this.css.error)){
					el.removeClass(this.css.error);
				}
			}
		}, this);
		this.fields.checkbox.loop(function(el){
			var el = $(el);
			var parent = el.parent()
			if(!el.attr("checked")){
				parent.addClass(this.css.error);
				ret = false;
			}else{
				if(parent.hasClass(this.css.error)){ parent.removeClass(this.css.error); }
			}
		}, this);
		return ret;
	},
	reset: function(){
		this.fields.text.loop(function(el){
			$(el).val("");
		}, this);
		this.fields.checkbox.loop(function(el){
			$(el).attr("checked", false);
		}, this);
	},
	bind: function(e, fn){
		this.event.bind(e, fn);
	}
};
var CommentsForm = function(form){
	this.form = new Form(form);
	this.form.bind("submit", $.fnbind(this.complete, this));
	this.avatar = $(this.selectors.avatarInput, form);
	this.avatarSelect = $(this.selectors.avatarSelect, form);
	var avatar = new AvatarSelect(this.avatarSelect);
	avatar.bind("change", $.fnbind(this.avatarChange, this));
};
CommentsForm.prototype = {
	selectors: {
		comments: "ol.comments",
		avatarSelect: ".avatar-select",
		avatarInput: "#comment-avatar"
	},
	avatarChange: function(e, val){
		this.avatar.val(val);
	},
	complete: function(e, obj){
		$(this.selectors.comments).prepend(
			"<li id=\"comment-" + obj.id + "\" class=\"" + obj.theme + " active\">" + 
			"<div class=\"avatar\"><img src=\"/img/" + obj.avatar + ".png\" /></div>" +
			"<p class=\"header\"><span class=\"name\">" + obj.name + "</span> " + obj.wrote + "</p>" +
			"<p>" + obj.comment + "</p>" + 
			"</li>"
		);
	}
};
var SituationForm = function(form){
	this.form = new Form(form);
	this.handle = $("h2", form);
	this.handle.click($.fnbind(this.toggle, this));
	this.content = $("div.toggle-content", form);
	this.content.hide();
	this.hidden = true;
};
SituationForm.prototype = {
	toggle: function(){
		if(this.hidden){
			this.handle.addClass("open");
			this.content.slideDown();
			this.hidden = false;
		}else{
			this.handle.removeClass("open");
			this.content.slideUp()
			this.hidden = true;
		}
	}
}
$(document).ready(Site.init);
