function ajaxLoader() {
	return "<div class=\"ajax_loader\"></div>";
}

function fixBoxes(div) {
	
	divs = (div || document.body).getElements("div.box1");
	if(!divs) return;

	// fix box1 div classes
	divs.each(function(el) {
		
		var a = el.getElement("a.bottom");		
		var b = new Element("div",{"class":"box1_bottom"});
		var l = new Element("div",{"class":"box1_left"});
		var r = new Element("div",{"class":"box1_right"});
		
		if(a != null) a.inject(r);
		l.inject(b);
		r.inject(l);
		b.inject(el,"after");
		
	});
	
}


// panel object
var Panel = {
	
	accordion:null,
	
	display:function(tab) {
		var p = this;
		new Ajax({
			url:BASE_URL + "panel",
			complete:function(html) {
				$("panel").set("html",html);
				fixBoxes($("panel"));
				p.setup(tab);
			}
		}).send('misc=' + $time());
	},
	
	setup:function(tab) {
		var dl = $("panel").getElement("dl");
		if(dl != null) {
			
			accordion = new Accordion(dl);
			dl.getElements("dt").each(function(el) {
				el.addEvents({
					mouseover:function(){
						this.setStyle("background-color","#e0f0c1");
					},
					mouseout:function() {
						this.setStyle("background-color","#fff");
					}
				});
			});
			
			this.getBadges(false);
			this.getGames(0,false,(tab == "games"));
			this.getFriends(0,false,(tab == "friends"));
			this.getSubmitted(0,false,(tab == "submitted"));
			
		} else {
			
			var form = document.forms["panel"];
			GOOP.extend([form.username,form.password],["events"]);
			form.username.addEvent("keypress",function(e) {
				if(new Event(e).code == 13)
					Panel.login();
			});
			form.password.addEvent("keypress",function(e) {
				if(new Event(e).code == 13)
					Panel.login();
			});
			
		}
	},
	
	login:function() {
		var form = document.forms["panel"];
		new Ajax({
			url:BASE_URL + "gamers/login",
			complete:function(html) {
				
				if(html == "inactive") {
					Growl.smoke({
						title:"Account Inactive",
						message:"Sorry, your account is inactive",
						_class:"bad"
					});
				} else if(html == "no") {
					Growl.smoke({
						title:"Incorrect",
						message:"Sorry, your Username and/or Password is incorrect",
						_class:"bad"
					});
				} else {
					USER_ID = html;
					if(window.rateGame) rateGame();
					Panel.display();
				}
				
			}
		}).send("username=" + form.username.value + "&password=" + form.password.value);
	},
	
	saveAccount:function() {
		var form = document.forms["panel_account"];
		new Ajax({
			url:BASE_URL + "panel/account",
			complete:function(html) {
				
				if(html == "ok") {
					Growl.smoke({
						title:"Account",
						message:"Your Account information was saved",
						_class:"good"
					});
				} else {
					Growl.smoke({
						title:"Account",
						message:"Your Account information was not saved!</p><br /><p><strong>There is a duplicate Username.</strong>",
						_class:"bad"
					})
				}
				
			}
		}).send("username=" + form.username.value + "&email=" + form.email.value + "&password=" + form.password.value);
	},
	
	sendReferrers:function() {
		var form = $(document.forms["refer_friends"]);
		var emails = '';
		form.getElements("input[type=text]").each(function(el) {
			if(el.value != '') {
				if(!Validate.email(el.value)) {
					Growl.smoke({
						title:"Bad Email Adress",
						message:"You have entered a bad email address",
						_class:"bad"
					});
				} else {
					emails += el.value + "::";
				}
			}
		});
		if(emails != '') {
			new Ajax({
				url:BASE_URL + "panel/refer",
				complete:function() {
					Growl.smoke({
						title:"Sent Emails",
						message:"We have sent your friends an email.<br />Thank you for referring us",
						_class:"good"
					});
					form.getElements("input[type=text]").each(function(el) { el.value = ''; });
					form.message.value = "Check out Zumspiel (to play), it has awesome games!";
				}
			}).send("emails=" + emails + "&message=" + form.message.value);
		}
	},
	
	saveContactAbout:function() {
		var form = document.forms["panel_contact"];
		var gender = (form.gender[0].checked ? form.gender[0].value : '') + (form.gender[1].checked ? form.gender[1].value : '');
		new Ajax({
			url:BASE_URL + "panel/contact",
			complete:function(html) {
				Growl.smoke({
					title:"Contact / About",
					message:"Your Contact / About information was saved",
					_class:"good"
				});
			}
		}).send("gender=" + gender + 
				"&location=" + form.loc.value + 
				"&website=" + form.website.value + 
				"&msn=" + form.msn.value + 
				"&twitter=" + form.twitter.value + 
				"&facebook=" + form.facebook.value + 
				"&yahoo=" + form.yahoo.value + 
				"&aim=" + form.aim.value + 
				"&steam=" + form.steam.value + 
				"&about=" + form.about.value);
	},
	
	getBadges:function(flag) {
		new Ajax({
			url:BASE_URL + "panel/badges",
			complete:function(html) {
				var el = $("panel").getElement("dd.badges").getElement("div.content");
				el.set("html",html);
				if(flag) Panel._resize(el.parentNode);
			}
		}).send('misc=' + $time());
	},
	
	getGames:function(page,flag,show) {
		new Ajax({
			url:BASE_URL + "panel/games/view",
			complete:function(html) {
				var el = $("panel").getElement("dd.games").getElement("div.content");
				el.set("html",html);
				if(flag) Panel._resize(el.parentNode);
				if(show) $("panel").getElement("dt.games").doEvent("click");
			}
		}).send("page=" + page);
	},
	
	getFriends:function(page,flag,show) {
		new Ajax({
			url:BASE_URL + "panel/friends/view",
			complete:function(html) {
				var el = $("panel").getElement("dd.friends").getElement("div.content");
				el.set("html",html);
				if(flag) Panel._resize(el.parentNode);
				if(show) $("panel").getElement("dt.friends").doEvent("click");
			}
		}).send("page=" + page);
	},
	
	getSubmitted:function(page,flag,show) {
		new Ajax({
			url:BASE_URL + "panel/submitted",
			complete:function(html) {
				var el = $("panel").getElement("dd.submitted").getElement("div.content");
				el.set("html",html);
				if(flag) Panel._resize(el.parentNode);
				if(show) $("panel").getElement("dt.submitted").doEvent("click");
			}
		}).send("page=" + page);
	},
	
	_resize:function(el) {
		var i, h = 0;
		el.getElements("div.preview",[]).each(function(div) {
			h += div.offsetHeight + 10;
		});
		h += 30;
		el.setStyle("height",h);
	}
	
};


// games
var Games = {
	
	_page:0,
	_sortby:"plays",
	_genre:"all",
	_asc:false,
	
	setup:function() {
		if($("toprated_games") == null) return;
		this.topRatedGames(0,true);
		this.justReleasedGames(0,true);
		this.otherGames(true);
	},
	
	page:function(page) {
		this._page = page;
		this.otherGames();
	},
	
	sortby:function(sortby) {
		if(sortby == this._sortby) {
			this._asc = !this._asc;
		} else {
			this._asc = (sortby == "title" ? true : false);
		}
		this._sortby = sortby;
		this.otherGames();
	},
	
	otherGames:function(init) {
		$("other_games").set("html",ajaxLoader());
		new Ajax({
			url:BASE_URL + "games/grabgames/",
			complete:function(html) {
				$("other_games").set("html",html);
				if(!init) window.location.href = "#other";
			}
		}).send("page=" + this._page + "&sortby=" + this._sortby + "&genre=" + this._genre + "&asc=" + this._asc);
	},
	
	justReleasedGames:function(page,init) {
		$("justreleased_games").set("html",ajaxLoader());
		new Ajax({
			url:BASE_URL + "games/grabgames/",
			complete:function(html) {
				$("justreleased_games").set("html",html);
				if(!init) window.location.href = "#justreleased";
			}
		}).send("page=" + page + "&sortby=created&genre=" + this._genre + "&asc=false");
	},
	
	topRatedGames:function(page,init) {
		$("toprated_games").set("html",ajaxLoader());
		new Ajax({
			url:BASE_URL + "games/grabgames/",
			complete:function(html) {
				$("toprated_games").set("html",html);
				if(!init) window.location.href = "#toprated";
			}
		}).send("page=" + page + "&sortby=overall&genre=" + this._genre + "&asc=false");
	}
	
};


// comments
var Comments = {
	
	id:null, // id of game,user
	
	load:function(id) {

		this.id = id;

		new Ajax({
			url:BASE_URL + "comments/" + (window.location.toString().indexOf("games/play") > -1 ? "game/" : "gamer/") + "view/" + this.id,
			complete:function(html) {
				$("comments").set("html",html);
			}
		}).send('misc=' + $time());
		
	},
	
	save:function() {

		var p = this;
		var form = $(document.forms["comments"]);
		
		if(Validate.empty(form.comment.value)) return false;
		
		if(USER_ID == '') {
			Growl.smoke({
				title:"Not Logged In",
				message:"You must log in to post a comment",
				_class:"bad"
			});
			return false;
		}

		new Ajax({
			url:BASE_URL + "comments/" + (window.location.toString().indexOf("games/play") > -1 ? "game/" : "gamer/") + "save/" + this.id,
			complete:function(html) {
				if(html == "ok") {
					form.comment.value = '';
					Comments.load(p.id);
				} else if(html == "bad") {
					Growl.smoke({
						title:"Bad Words Used",
						message:"Your Comment was not submitted",
						_class:"bad"
					});
				}
			}
		}).send("comment=" + form.comment.value);
		
	}
	
};


// user actions
var Gamer = {
	
	saveGame:function(id) {
		if(USER_ID == '') {
			Growl.smoke({
				title:"Not Logged In",
				message:"You must log in order to save this game to your Favorites",
				_class:"bad"
			});
			return;
		}
		new Ajax({
			url:BASE_URL + "gamers/save/game",
			complete:function() {
				Growl.smoke({
					title:"Game Saved",
					message:"The game was added to your Favorites",
					_class:"good"
				});
				if($("save_remove_game")) {
					$("save_remove_game").set({
						"href":"javascript:Gamer.removeGame(" + id + ")",
						"html":"<img src=\"" + BASE_URL + "assets/icons/controller_delete.png\" /> Remove Game &nbsp; &nbsp; "
					});
				}
				Panel.getGames(0,true);
			}
		}).send("game_id=" + id);
	},
	
	removeGame:function(id,flag) {
		new Ajax({
			url:BASE_URL + "gamers/remove/game",
			complete:function(html) {
				if(html == "ok") {
					Growl.smoke({
						title:"Game Removed",
						message:"The game was removed from your Favorites",
						_class:"good"
					});
					if($("save_remove_game")) {
						$("save_remove_game").set({
							"href":"javascript:Gamer.saveGame(" + id + ")",
							"html":"<img src=\"" + BASE_URL + "assets/icons/controller_add.png\" /> Add Game &nbsp; &nbsp; "
						});
					}
					if(flag) Panel.display("games"); 
					else Panel.getGames(0,true);
				} else {
					Growl.smoke({
						title:"Game Not Removed",
						message:"You are not logged in",
						_class:"bad"
					});
				}
			}
		}).send("game_id=" + id);
	},
	
	saveFriend:function(id) {
		if(USER_ID == '') {
			Growl.smoke({
				title:"Not Logged In",
				message:"You must log in order to save them to your Favorites",
				_class:"bad"
			});
			return;
		}
		new Ajax({
			url:BASE_URL + "gamers/save/friend",
			complete:function() {
				Growl.smoke({
					title:"Friend Saved",
					message:"The friend was added to your Favorites",
					_class:"good"
				});
				if($("save_remove_friend")) {
					$("save_remove_friend").set({
						"href":"javascript:Gamer.removeFriend(" + id + ")",
						"html":"<img src=\"" + BASE_URL + "assets/icons/user_delete.png\" /> Remove Friend"
					});
				}
				Panel.getFriends(0,true);
			}
		}).send("user_id=" + id);
	},
	
	removeFriend:function(id,flag) {
		new Ajax({
			url:BASE_URL + "gamers/remove/friend",
			complete:function(html) {
				if(html == "ok") {
					Growl.smoke({
						title:"Friend Removed",
						message:"The friend was removed from your Favorites",
						_class:"good"
					});
					if($("save_remove_friend"))	{
						$("save_remove_friend").set({
							"href":"javascript:Gamer.saveFriend(" + id + ")",
							"html":"<img src=\"" + BASE_URL + "assets/icons/user_add.png\" /> Add Friend"
						});
					}
					if(flag) Panel.display("friends"); 
					else Panel.getFriends(0,true);
				} else {
					Growl.smoke({
						title:"Friend Not Removed",
						message:"You are not logged in",
						_class:"bad"
					});
				}
			}
		}).send("user_id=" + id);
	}
	
}


function bookmark(title,url) {
	title = "Zumspiel (to play) - " + title;
	if(window.all) {
		window.external.AddFavorite(url,title);
	} else if(window.sidebar) {
		window.sidebar.addPanel(title, url, "");
	} else {
		Growl.smoke({
			title:"Can Not Bookmark",
			message:"Your browser doesn't support automatic Bookmarks. You will have to do it manually.",
			_class:"bad"
		});
	}
}


//
var ts;
DOM.ready(function() {
	
	// fix pngs
	fixPNG.path = BASE_URL + "assets/images/transparent.gif";
	fixPNG.init($("logo"));
	($$("div#spotlight div.exclusive", false) || []).each(function(el) {
		fixPNG.init(el.parentNode);
	});
	
	// fix the boxes
	fixBoxes();
	
	// display the panel
	Panel.display();
	
	// set up the games
	Games.setup();
	
	// search
	new AutoComplete("search", {
		path:BASE_URL + 'games/search',
		limit:10
	});
	$("search").addEvents({
		focus:function() {
			if(this.value == 'Search for Game(s)') this.value = '';
			this.setStyle('color', '#333');
		},
		blur:function() {
			if(this.value == '') this.value = 'Search for Game(s)';
			this.setStyle('color', '#999');
		}
	}).value = 'Search for Game(s)';
	
	// spotlight games
	if($("spotlight")) {
		
		var spotlight_games_div = $$("div#spotlight div.spotlight");
		spotlight_games_div[0].setStyle("display","block");
		
		var spotlight_games_li = $$("div#spotlight ul li");
		spotlight_games_li[0].addClass("current");
		
		$$("div#spotlight ul a").each(function(el,i) {
			el._set("index",i).addEvent("mouseover",function() {
				spotlight_games_div.each(function(e,j) {
					e.setStyle("display",j == el._get("index") ? "block" : "none");
				});
				spotlight_games_li.each(function(e,j) {
					if(j == el._get("index"))
						e.addClass("current");
					else
						e.removeClass("current");
				});
			});
		});
	}
	
	// sortable table for lists view
	if($("tablesort")) {
		var sorton;
		($$('table#tablesort thead th') || []).each(function(el, i) {
			if(el.get('html').trim().toLowerCase().indexOf('submitted') > -1 || el.get('html').trim().toLowerCase().indexOf('date') > -1)
				sorton = i;
		});
		ts = new TableSorter("tablesort",{
			sort:sorton || undefined,
			order:sorton !== undefined ? 'desc' : undefined,
			perpage:10,
			paginate:true,
			_ids:["tablesort_current","tablesort_max"],
			start:function() {
				this.setStyle("opacity",50);
			},
			complete:function() {
				this.setStyle("opacity",100);
				$('tablesort_current_2').set('html', $('tablesort_current').get('html'));
				$('tablesort_max_2').set('html', $('tablesort_max').get('html'));
			}
		});
	}
	
	// register effect
	if(document.forms["register"]) {
		
		var reg_ajax = new Ajax({
			url:BASE_URL + "gamers/check",
			complete:function(html) {
				$("register_username_ok").setStyle("display","none");
				$("register_username_bad").setStyle("display","none");
				$("register_username_" + (html == "ok" ? "ok" : "bad")).setStyle("display","inline");
			}
		});
		
		$(document.forms["register"].username).addEvent("keyup",function() {
			if(this.value.length < 2) {
				$("register_username_ok").setStyle("display","none");
			   	$("register_username_bad").setStyle("display","none");
				return;
			}
			reg_ajax.send("username=" + this.value);
		});
		
	}
	
});