// TO JSON JQUERY PLUGIN
(function($){$.toJSON=function(o)
{if(typeof(JSON)=='object'&&JSON.stringify)
return JSON.stringify(o);var type=typeof(o);if(o===null)
return"null";if(type=="undefined")
return undefined;if(type=="number"||type=="boolean")
return o+"";if(type=="string")
return $.quoteString(o);if(type=='object')
{if(typeof o.toJSON=="function")
return $.toJSON(o.toJSON());if(o.constructor===Date)
{var month=o.getUTCMonth()+1;if(month<10)month='0'+month;var day=o.getUTCDate();if(day<10)day='0'+day;var year=o.getUTCFullYear();var hours=o.getUTCHours();if(hours<10)hours='0'+hours;var minutes=o.getUTCMinutes();if(minutes<10)minutes='0'+minutes;var seconds=o.getUTCSeconds();if(seconds<10)seconds='0'+seconds;var milli=o.getUTCMilliseconds();if(milli<100)milli='0'+milli;if(milli<10)milli='0'+milli;return'"'+year+'-'+month+'-'+day+'T'+
hours+':'+minutes+':'+seconds+'.'+milli+'Z"';}
if(o.constructor===Array)
{var ret=[];for(var i=0;i<o.length;i++)
ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]";}
var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")
name='"'+k+'"';else if(type=="string")
name=$.quoteString(k);else
continue;if(typeof o[k]=="function")
continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val);}
return"{"+pairs.join(", ")+"}";}};$.evalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);return eval("("+src+")");};$.secureEvalJSON=function(src)
{if(typeof(JSON)=='object'&&JSON.parse)
return JSON.parse(src);var filtered=src;filtered=filtered.replace(/\\["\\\/bfnrtu]/g,'@');filtered=filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']');filtered=filtered.replace(/(?:^|:|,)(?:\s*\[)+/g,'');if(/^[\],:{}\s]*$/.test(filtered))
return eval("("+src+")");else
throw new SyntaxError("Error parsing JSON, source is not valid.");};$.quoteString=function(string)
{if(string.match(_escapeable))
{return'"'+string.replace(_escapeable,function(a)
{var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16);})+'"';}
return'"'+string+'"';};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'};})(jQuery);




/* Onload Handler */
$(function() {
	// Add an overlay function so we can black out the screen
	(function() {
		var $body = $(document.body),
		$overlay = $("#overlay").bind('click',function(e) {
			if(e.target.id == 'overlay') {
		    	$("#overlay").fadeOut('fast');
		    }
		});
		window.onresize = function() {
			$overlay.width($body.width()).height($body.height());
		};
		// Quickie jquery plugin to handle the overlay
		$.overlay = function(title,content) {
			$overlay.width($body.width()).height($body.height()).fadeIn('fast')
			.find("#overlay_title").click($.overlay.hide).html(title).end().find('#overlay_message').html(content);
		};
		
		$.overlay.hide = function() {
			$("#overlay").fadeOut('fast');
		};
		
		// Change password overlay
		$("#change_password").click(function() {
			var html = $("#overlay_change_password").html();
			$.overlay("Change Password",html);
			// Override the normal password request form
			var $change_password_form = $("#change_password_form", $overlay);
			$change_password_form.submit(function() {
				var values = $change_password_form.serializeArray();
				$.overlay("Change Password", "Saving...");
				$.post("session/",values,function() {
					$.overlay("Change Password", "Your password was changed successfully, next time you log in use your new password.");
				});
				return false;
			});
			return false;
		});
		
		// Create account overlay
		$("#create_account").click(function() {
			var html = $("#overlay_create_account").html();
			$.overlay("Create Account",html);
		});
		
		// Password request overlay
		$("#pw_request").click(function() {
			var html = $("#overlay_request_password").html();
			$.overlay("Request Password",html);
			// Override the normal password request form
			var $pw_request_form = $("#pw_request_form");
			$pw_request_form.submit(function() {
				var values = $pw_request_form.serializeArray();
				$.overlay("Request Password", "Sending...");
				$.post("session/",values,function() {
					$.overlay("Request Password", "A password was sent to your Tap Tap Revenge 3 news feed.<div style='text-align: center; margin-top: 10px;'><img src='resources/images/temp_password.jpg' /></div>");
				});
				return false;
			});
			return false;
		});
	})();
	
	
	// Add the explore games menu hover dropdown
	(function() {
		var $explore = $("#explore_games"), $overlay = $("#explore_games_overlay");
		$explore.mouseover(function() {
			$overlay.show();
		});
		$overlay.mouseleave(function() {
			$overlay.hide();
		});
	})();
	
	
	// Rounded corners
	(function() {
		var $rounded_corners = $(".list, .rounded, .single");
		$rounded_corners.css("position","relative").append("<div class='top_left_corner' /><div class='top_right_corner' /><div class='bottom_left_corner' /><div class='bottom_right_corner' />");
	})();
	
	
	// Expandos (clicking on this will expand the ID set in the title attribute)
	(function() {
		$(".expand").click(function() {
			var $this = $(this),
			text = ($this.text() == "show") ? "hide" : "show",
			el = "#" + $this.text(text).attr('title');
			$(el).slideToggle();
			return false;
		});
	})();
	
	
	// Feature Rotatation
	(function() {
		var $feature = $("#feature");
		
		if($feature.length) {
			// Image transition
			var $items = $("#feature_images"),
			$subtitle = $("#feature_subtitle"),
			$title = $("#feature_title"),
			interval = 5200;
			// Set up the interval
			setInterval(function() {
				$items.width($items.find("li").length * $feature.width()).animate({"left":-$feature.width()},"slow",function() {
					$items.find("li:first-child").remove().appendTo($items).end().end().css("left",0);
				});
				$subtitle.fadeOut("fast", function() {
					$subtitle.find("li:first-child").remove().appendTo($subtitle);
				}).fadeIn("fast");
				$title.fadeOut("fast", function() {
					$title.find("li:first-child").remove().appendTo($title);
				}).fadeIn("fast");
				interval = 6200;
			},interval);			
		} 
	})();
	
	
	// Charts switcher
	(function() {
		var $charts = $("#charts_subcategories");
		if($charts.length) {
			var current = '',cache = {}, $display = $("#chart_data"), $title = $("#chart_title"),
			show = function(res) {
					cache[current] = res;
					var html = [];
					for(var i in res) {
						html.push("<li class='clearfix'>");
						html.push("<span class='num'>" + (parseInt(i) + 1) + ". " + "</span>");
						if(res[i]['avatar'] != null) {
							html.push("<img src='" + res[i]['avatar'] + "' />");
						}
						html.push(res[i]['username']);
						html.push("<div class='float_right'>" + res[i].chart_data + "</div>")
						html.push("</li>");
					}
					$display.html(html.join(''));
			},
			change = function() {
				$title.text($charts.find(":selected").text());
				current = $charts.val();
				if(cache[current]) {
					show(cache[current]);
					return;
				}
				$.getJSON("json/charts.php",{"type":current},show);
			};
			$charts.change(change);
			change();
		}
	})();
	
	
		// Accordians
	(function($) {
		$.fn.accordian = function() {
			var $accordian = $(this);
			$accordian.each(function() {
				$(this).find(".accordian_title").each(function(i) {
					if(i > 0) {
						$(this).addClass("inactive").next().hide();
					} else {
						$(this).addClass("active");
					}
				}).not(".unavailable").click(function() {
				    var $this = $(this);
					$this.closest(".accordian").find(".accordian_title").addClass("inactive");
					$this.removeClass("inactive").addClass("active").closest(".accordian").find("ul")
						 .not("#" + $this.attr("title")).slideUp()
						 .end().end().find("#" + $this.attr("title")).slideDown();
				});
			});
		};
	})(jQuery);
	
	
	// Tournament Chart
	(function() {
		$.getJSON("json/charts.php",{"type":"roadtrip"},function(res) {
			$.each(res,function() {
								
				var el = $("<ul id='" + this.name.replace(' ','') + "'></ul>");
				if(this.scores.length == 0) {
					el.filter("div").addClass('unavailable');
				} else {
					$.each(this.scores, function(i) {

						var html = "<li class='clearfix'>" + (i + 1) + ". " + this.username + "<div class='float_right'>" + this.field + "</div></li>";
						el.filter("ul").append(html);
					});
				}
				if (parseInt(this.type) == 1) {
					$("#topplayers").append(el);
				} else {
					$("#allplayers").append(el);
				}
				
				// NEW CODE
				/*var el = $("<ul></ul>");
				if(this.scores.length == 0) {
					var html = "<li>Coming Soon!</li>";
					el.filter("ul").append(html);
				} else {
					$.each(this.scores, function(i) {
						var html = "<li class='clearfix'>" + (i + 1) + ". " + this.username + "<div class='float_right'>" + this.field + "</div></li>";
						el.filter("ul").append(html);
					});
				}
				$("#world").append(el);*/
			});
			$(".accordian").accordian();
		});
	})();
	
	
	// Sign in Widget
	var $sign_in_form = $("#sign_in_form");
	if($sign_in_form.length) {
		// Remove error message on key up
		$sign_in_form.find("input").keyup(function() {
			$sign_in_form.find(".error").slideUp("fast");
		});
		
		// Override the normal form submit so we don't have to refresh the whole page
		$sign_in_form.submit(function() {
			// Store the values in an array
			var values = $sign_in_form.serializeArray();
			// Let it know that it's an ajax request
			values.push({'name':'ajax','value':1});
			// Make the request
			$.post("session/",values,function(res) {
				if(!!parseInt(res)) {
					window.location.reload();
				} else {
					$sign_in_form.find(".error").slideDown("fast");
				}
			});
			// Make sure it doesn't submit the normal way
			return false;
		});
	}
	
	// Tweets Widget
	if($("#twitter_box").length) {
		$.getJSON("http://search.twitter.com/search.json?callback=?&q=%40taptaprevenge&rpp=3",function(tweets) {
			var html = [];
			for(var tweet in tweets.results) {
				html.push("<li>" + tweets.results[tweet].from_user + "<p>" + tweets.results[tweet].text + "</p></li>");
			}
			$("#twitter_box").find("ul").empty().html(html.join(''));
		});
		$("#twitter_box .image_button").click(function() {
			window.location.href = "http://twitter.com/taptaprevenge";
		});
	}
});