// On page load
$j(document).ready(function(){
	// DEBUG helper function
	$j("img").click(function() {
	
	});
	
	 $j("#loading-img").bind("ajaxSend", function(){
		this.innerHTML = ('<img src="templates/portal/css/cream/images/loading.gif" alt="Loading" title="Loading" width="16" height="16" />');
	 }).bind("ajaxComplete", function(){
		this.innerHTML = '';
	 });

	
	// Make the blanket invisible for when it's shown
	$j("#blanket").css({ opacity: 0, height: "100%" });
	
	
	//Login fields
	if (!cfg.loggedIn) {
		$j("#btn-login").click(function(e) {
			ajax.login.check(($e('inp_login_user').value), ($e('inp_login_pass').value));
		});
		$j("#header .login input").keydown(function(e) {
			if (!($e("btn-login").disabled)) {
				if (e.keyCode == 13) { // Enter
					ajax.login.check(($e('inp_login_user').value), ($e('inp_login_pass').value));
				}
			}
		});
		// Clear the login fields if they recieve focus
		$j("#inp_login_user").focus(function() {
			template.login.clear("username");
		});
		$j("#inp_login_pass").focus(function() {
			template.login.clear("password");
		});
	}
	
	// Search auto-suggestiong
	$j("#search-text").keydown(function(e) {
		// Enter
		if (e.keyCode == 13) {
			template.searchSuggest.choose($e("search-text").value);
		}
	});
	$j("#search-text").keyup(function(e) {
		// Down arrow
		if (e.keyCode == 40) {
			template.searchSuggest.move("down");
		}
		// Up arrow
		else if (e.keyCode == 38) {
			template.searchSuggest.move("up");
		} else {
		
			if ($e("search-text").value != "")
				ajax.search.suggestions.find($e("search-text").value);
			else
				$j("#search-suggest").hide();
		}
	});
	$j("#search-text").blur(function() {
		template.searchSuggest.timeout = setTimeout("template.searchSuggest.hide();", 1000);
	});
	$j("#search-text").focus(function() {
		clearTimeout(template.searchSuggest.timeout);
	});
	
	// Helper sliding
	$j(".helper .header").click(function() {
		$j(this).parent().find(".content").slideToggle("slow");
		if ($j(this).find(".collapse img").css("display") == "none") {
			$j(this).find(".collapse img").fadeIn("fast");
		} else {
			$j(this).find(".collapse img").fadeOut("fast");
		}
	});
	
	// Button decorating
	$j(".btn").hover(function(){},
		function() {
			$j(this).removeClass('btn-mousedown');
		});
	$j(".btn").mousedown(function() {
		$j(this).addClass('btn-mousedown');
	});
	$j(".btn").mouseup(function() {
		$j(this).removeClass('btn-mousedown');
	});
});

// Template object
var template = {

	// Any button element
	"button":{
		"disable": function(b) {
			b.disabled = true;
			b.className = "";
			$j(b).addClass("btn").addClass("btn-disabled").css("cursor", "default");
		},
		"enable": function(b) {
			b.disabled = false;
			b.className = "";
			$j(b).addClass("btn").addClass("btn-mouseout").css("cursor", "pointer");
		}
	},
	
	// Overlay (formerly notification)
	"overlay":{
		"active": false,
		"timeout": "",
		
		// Defaults
		"defaults": {
			"width": 500,
			"height": 0,
			"title": "Message",
			"content": "",
			"draggable": false,
			"blanket": {
				"active": true,
				"opacity": 0.7
			},
			"advert": true
		},
		
		"parse": function(msg) {
			if (!this.active) {
				this.active = true;
				
				if (typeof(msg.title) != "undefined") {
					$e("overlay-header").innerHTML = msg.title;
				} else {
					$e("overlay-header").innerHTML = this.defaults.title;
				}
		
				if ((typeof(msg.content) == "string") || (typeof(msg.content) == "object")) {
					$e("overlay-content").update(msg.content);
				} else {
					$e("overlay-content").innerHTML = this.defaults.content;
				}
				
				if (typeof(msg.advert) != "undefined") {
					var advert = msg.advert;
				} else {
					var advert = this.defaults.advert;
				}
				if (advert)
					$j("#overlay-advert").show();
				else
					$j("#overlay-advert").hide();

				// Display
				if (typeof(msg.width) != "undefined")
					$j("#overlay").css("width", msg.width);
				else
					$j("#overlay").css("width", this.defaults.width);
					
				if (typeof(msg.height) != "undefined") {
					$j("#overlay").css("height", msg.height);
				} else {
					if (this.defaults.height == 0) {
						$j("#overlay").css("height", "");
					} else {
						$j("#overlay").css("height", this.defaults.height);
					}
				}
				
				
				// Compute the margin
				$j("#overlay").css("opacity", 0);
				$j("#overlay-wrap").show();
				$target = ($j(window).height()-25 - $j("#overlay").height()) / 2;
				$j("#overlay").css("marginTop", $target);
				$j("#overlay").hide();
				$j("#overlay").css("opacity", 1);
				
				if (typeof(msg.blanket) != "undefined") {
					var blanket = msg.blanket;
				} else {
					var blanket = this.defaults.blanket;
				}
				if (blanket) {
					$j("#blanket").show();
					$j("#blanket").fadeTo("slow", this.defaults.blanket.opacity, function() {
						$j("#overlay").hide();
						$j("#overlay-wrap").show();				
						$j("#overlay").slideDown("slow");
					});
				} else {
					$j("#overlay").hide();
					$j("#overlay-wrap").show();
					$j("#overlay").slideDown("slow");
				}
				
				if (typeof(msg.draggable) != "undefined") {
					var draggable = msg.draggable;
				} else {
					var draggable = this.defaults.draggable;
				}
				//if (draggable) {
					//$j("#overlay").draggable({ handle: "#overlay-header" });
					//$j("#overlay-header").css("cursor", "move");
				//} else {
					$j("#overlay-header").css("cursor", "default");
				//}
				
				if (typeof(msg.timeout) != "undefined") {
					this.timeout = setTimeout("template.overlay.hide()", msg.timeout);
				}
			}
		},
		
		"hide": function() {
			clearTimeout(this.timeout);
		
			$j("#overlay").slideUp("fast", function() { 
				$j("#overlay-wrap").hide();
				$j("#blanket").fadeTo("fast", 0, function() {
					$j("#blanket").hide();
				});
			});
			
			$j("#overlay").draggable("destroy");
			
			this.active = false;
		},
		"message": {
			"error": function(type){
				
				template.overlay.header = "Error";
				
				switch (type) {
				case "server":
					var message = "Sorry, but there was an error with our servers.  The error was on our servers and nothing to do with your computer.<br /><br />You can try logging in again, or if you continue to experience problems, <a href=\"contact.php\">let us know</a>.";
				break;
				}
				
				template.overlay.parse({
					"title": "Error",
					"content": message,
					"width": 400,
					"draggable": true
				});
			},
			"misc": function(type) {
			
				switch (type) {
				case "favourite":
					template.overlay.parse({
						"title": "Favourite Added",
						"content": "This item has been added to your favourites.",
						"width": 400,
						"draggable": true,
						"timeout": 5000
					});
				break;
				}
			}
		},
		"play": function(title, filename, width, height) {
			this.parse({
				"title": "Now Playing: " + title,
				"content": '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" id="flash5329731" width="' + width + '" height="' + height + '"><param name="allowScriptAccess" value="never"><param name="allowFullScreen" value="false"><param name="movie" value="flash/' + filename + '"><param name="quality" value="high"><param name="wmode" value="window"><embed src="flash/' + filename + '" quality="high" wmode="window" name="flash5329731" allowscriptaccess="never" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" width="' + width + '" height="' + height + '"></object>',
				"advert": true,
				"width": width,
				"draggable": true
			});
		}
	},
	
	// Status bar at the bottom
	"status": {
		"message": {
			"timeout": "",
			"parse": function(msg) {
				clearTimeout(this.timeout);
				$e("status-content").innerHTML = msg.content;
				$j("#status-content").show().effect("highlight", {}, 1500);
				this.timeout = setTimeout('$j("#status-content").fadeOut(1000)', $e("status-content").innerHTML.length * 100);
			}
		}
	},
	
	// Login section in the header
	"login":{
		// Show a "Loading..." message underneath the login form
		"showLoading": function(message) {
			var b = $e("btn-login");
			template.button.disable(b);
			
			if (typeof(message) == "undefined")
				message = "Loading...";
			$e("login-text").innerHTML = message;
			$j("#login-text").removeClass("error-text");
			
			$j(b.parentNode).animate({marginTop: "5px"}, 200);
			$j("#login-text").fadeIn(200);
		},
		// Show a custom message under the login form
		"showLoaded": function(message, className) {
			$j("#login-text").fadeOut(100, function() {
				var b = $e("btn-login");
				setTimeout('template.button.enable($e("btn-login"))', 500);
					
				$e("login-text").innerHTML = message;
				if (typeof(className) == "undefined")
					className = "error-text"
				$j("#login-text").addClass(className);
				
				if ($j("#login-text").css("display") == "none")
					$j(b.parentNode).animate({marginTop: "5px"}, 200);
				$j("#login-text").fadeIn(200);
			});
		},
		// Clear the login fields of their default values on focus
		"clearedUsername": false,
		"clearedPassword": false,
		"clear": function(field) {
			if ((field == "username") && (!this.clearedUsername)) {
				var e = $e("inp_login_user");
				e.value = "";
				e.style.color = "";
				this.clearedUsername = true;
			} else if ((field == "password") && (!this.clearedPassword)) {
				var e = $e("inp_login_pass");
				e.value = "";
				e.style.color = "";
				this.clearedPassword = true;
			}
		}
	},

	// Search suggestions
	"searchSuggest":{
		"disabled": false,
		"originalInput": "", // Stores the user's original input for when it's overwritten
		"selected": -1,
		"matches": [],
		"timeout": "",
		"show": function(matches) {
			if (!(this.disabled)) {
				this.originalInput = $e("search-text").value;
				this.matches = matches;
				
				if (this.matches.length > 0) {
					
					this.selected = -1;
							
					var frag = document.createDocumentFragment();
					for (var i = 0; i < matches.length; i++) {
						var d = document.createElement("div");
						d.innerHTML = matches[i].itm_title_f;
						d.id = matches[i].itm_title;
						d.onclick = new Function("template.searchSuggest.choose(this.id);");
						frag.appendChild(d);
					}
					
					var d = document.createElement("div");
					d.innerHTML = "Hide search suggestions";
					d.onclick = new Function("template.searchSuggest.disable();");
					$j(d).css({ "color": "#888888", "text-align": "right", "paddingRight": "5px" });
					frag.appendChild(d);
					
					$e("search-suggest").removeChildren();
					$e("search-suggest").appendChild(frag);
					
					$j("#search-suggest").css("left", $j("#search-text").offset().left);
					$j("#search-suggest").show();
					
					
				} else {
					$j("#search-suggest").hide();
				}
			}
		},
		"hide": function() {
			$j("#search-suggest").hide();
		},
		"disable": function() {
			this.disabled = true;
			this.hide();
		},
		"move": function(dir) {
			$j("#search-suggest").find(".hilit").removeClass("hilit");
			if (dir == "down") {
				if (this.selected < this.matches.length-1) {
					this.selected++;
					$e("search-text").value = this.matches[this.selected]['itm_title'];
					$j("#search-suggest").children().eq(this.selected).addClass("hilit");
				} else {
					this.selected = -1;
					$e("search-text").value = this.originalInput;
				}
			} else {
				if ((this.selected > 0) || (this.selected == -1)) {
					if (this.selected == -1) 
						this.selected = this.matches.length-1;
					else
						this.selected--;
					$e("search-text").value = this.matches[this.selected]['itm_title'];
					$j("#search-suggest").children().eq(this.selected).addClass("hilit");
				} else {
					this.selected = -1;
					$e("search-text").value = this.originalInput;
				}
			}
		},
		"choose": function(choice) {
			choice = choice.replace(" ", "+");
			window.location = "search.php?s=" + choice;
		}
	},

	
}