Navleft = Class.create();

Navleft.prototype = {

	initialize: function() {
		this.pane = new Pane('mainNavLeft');
		this.pages =['main',
								 'profile',
								 'spots',
								 'login',
								 'help'
								 ];

		this.eventListener = function(event,arr) {
			theNavleft.refreshCurrentPage();
			theNavleft.msg(event + ' change');
		};
		this.RESULTS_PER_PAGE = 10;
		this.msgDown = false;
		this.highestRatedSpotsDiv = "highestRatedSpotsDiv";
		this.mostRecentSpotsDiv = "mostRecentSpotsDiv";
		this.profileSpotListDiv = "profileSpotListDiv";
		this._isShowing = false;
	},
	

	/**
	 * Main entry point.  This will load everything needed.
	 * TODO: Move elsewhere because we aren't just loading the
	 */
	load: function() {
		var page = 'main';
		
		this.loadPage(page);

		// show the main liks
		this.msg('loading links');
		$A(['main','help']).each(function(l) {appear(theNavleft.link(l));});
		this.fadeLinks('main');

		// links in nav left and top right thingy
		if (loggedIn) {
			showLoggedInLinks();
		} else {
			hideLoggedInLinks(); 			
		}

		// register for adding and removing listeners
		this.msg('registering listeners');
		theEvents.addListener('add', this.eventListener);
		theEvents.addListener('delete', this.eventListener);	
		theEvents.addListener('edit', this.eventListener);

		this.loadPage(page);
		this._isShowing = true;
	},

	isShowing: function() {
		return this._isShowing;
	},


	msg: function(s,t) {
		show('navMsg');
		if (!t) t = 2000;
		$('navMsg').innerHTML = s;
		//
		// create a fade out to fade this msg out in 't' milliseconds
		// if the message panel still reads this msg
		//
		setTimeout('theNavleft.fadeOutMsg("' + s + '")', t);
	},
	
	fadeOutMsg: function(s) {
		var txt = $('navMsg').innerHTML;
		if (txt != s) return;
		hide('navMsg');
	},

	loadPage: function(page) {
		if      (page == 'profile') this.loadProfile(theUsername);
		else if (page == 'spots')   this.loadSpots(theUsername);
		else if (page == 'main')    this.loadMain(theUsername);
		else if (page == 'help')    this.loadHelp(theUsername);
		else if (page == 'login')   this.loadLogin();
		else                        this.loadDummy(page);
	},
	 
	loadDummy: function(page) {
		this.removeMainContent(page);
		var html = "no <em>" + page + "</em> for you!";
		
		this.showContent(page,html);
	},

	loadLogin: function() {
		var page = 'login';
		html = this.removeMainContent(page);
		html += '<form action="" method="post" onSubmit="return loginCheckForm(this)">';
		html += '<table border=0 cellpadding=0 cellspacing=1>';

		html += '<tr><td>Username:</td><td>';
		html += '<input id="unametext" class=formfield type="text" name="uname" maxlength="40">';
		html += '</td>';
		html += '</tr><tr><td><span class=errorMsgSmall id=unamediv></span>';
		html += '</td></tr>';

		html += '<tr><td>Password:</td><td>';
		html += '<input id="passwdtext" class=formfield type="password" name="passwd" maxlength="50">';
		html += '</td>';
		html += '</tr><tr><td><span class=errorMsgSmall id=passwddiv></span>';
		html += '</td></tr>';

		html += '<tr><td colspan=2>'
		html += '<table border=0 cellpadding=0 cellspacing=0 width=100%>';
		html += '<tr><td>'
		html += 'Rember me <input class=formfield type=checkbox name=remember value=remember>';
		html += '</td><td align=right>';
		html += '<input class=formsubmit type="submit" name="submit" value="Login">';
		html += '</td></tr>';
		html += '<tr><td colspan=2>'
		html += '<small>What is ' + linkWhatsACookie('this') + '?</small>';
		html += '</td></tr>';
		html += '</table>';

		html += '</table>';

		html += '</form>';
		html += '<div style="min-height: 50px"><span id="loginMsg"></span></div>';
		html += '<small>Not registered, yet?  You can do it ' + linkRegister("here"); + '</a>';

		this.showContent(page,html);
		$('unametext').focus();
	},

	loadHelp: function(username) {
		var page = 'help';
		html = this.removeMainContent(page);
		html += "<div class=navleftheader>Here is our extensive help</div>";
		html += theCommon.helpContent();
		this.showContent(page,html);
	},
 
	loadProfile: function(username) {
		var page = 'profile';
		var html = this.removeMainContent(page);
		var where;
		var rest;
		if (username) {
			where = "`username` = '" + username + "'";
			rest = "";
		} else {
			where = "1";
			rest = "&current_user=1";
		}
		var title = "user";
		var reqURL = fullPath("db.php") +
		"?where=" + where + 
		rest +
		"&spud=trooper" +
		"&title=" + title +
		"&db=users" +
		"";
		function processLoadUser(res) {
			var user = res.getElementsByTagName(title)[0];
			var name = user.getAttribute("username");
			var img = user.getAttribute("has_image");
			var imgSrc;
			if (img || img == "0") {
				imgSrc = "usericons/" + name;
			} else {
				imgSrc = "images/unknown_user.gif";
			}
			
			var since = user.getAttribute("regdate");

			var loc = "";
			
			var city = user.getAttribute("city");
			if (city && city!='""') {if (loc) loc += ", "; loc += city;}

			var state = user.getAttribute("state");
			if (state && state!='""') {if (loc) loc += ", "; loc += state;}

			var country = user.getAttribute("country");
			if (country && country!='""') {if (loc) loc += ", "; loc += country;}

			if (!loc || loc=="") loc = "Unknown";
			//
			// Fill in the details
			//
			var m = "&nbsp;";
			var mm = m+"</td><td>";
			html += "<table border=0 cellpadding=0 cellspacing=0>";
			html += "<tr><td>";
			html += "<img width=100 height=100 src='" + imgSrc + "' />";
			html += "</td><td valign=top>";
			html += m+"</td><td valign=top>";
			html += "<b>" + name + "</b>";
			html += "<br/><em>" + loc + "</em>";
			html += "<br/><em>" + formatDate(since,true) + "</em>";
			html += "</td></tr>";
			html += "</table>";
			html += "<br/>";
			html += "<p>";
			if (name != theUsername) {
				html += "See this user's " + theNavleft.linkKSpots(name, "KathySpots") + ".";
			} else {
				html += "Change your " + linkChangeProfile('profile') + ".";
			}
			html += "</p>";
			theNavleft.showContent(page,html);
		}
		this.doAjax('profile',reqURL, processLoadUser);
	},

	linkKSpots: function(name,text) {
		return "<a href=\"javascript:theNavleft.loadSpots('" + name + "');\">" + text + "</a>";
	},



	loadHighestRated: function(start) {
		if (!start) start=0;
		var stop = start+this.RESULTS_PER_PAGE;
		function processLoadMain(res) {   
			note("processLoadMain()");
			if (!res || res=='') {
				note("invalid response");
				return;
			}
			var info = res.getElementsByTagName("info")[0];
			var kspots = res.getElementsByTagName("kspot");		
			var html = theNavleft.kspotList(kspots,info,true,true,start,stop, 
																			"theNavleft.loadHighestRated");
			$(theNavleft.highestRatedSpotsDiv).innerHTML = html;
		}
		var reqURL = fullPath("db.php") +
		"?where=1" +
		"&stop=" + stop +
		"&start=" + start +
		"&sortby=rating" +
		"&spud=trooper" +
		"&count=1" +
		"&title=kspot" +
		"&db=kmaps" +
		"&sortkind=DESC" +
		"";
		ajaxXML(reqURL, processLoadMain,counter(this.highestRatedSpotsDiv));		
	},


	loadMostRecent: function(start) {
		if (!start) start=0;
		var stop = start+this.RESULTS_PER_PAGE;
		function processLoadMain2(res) {   
			note("processLoadMain2()");
			if (!res || res=='') {
				note("invalid response");
				return;
			}
			var info = res.getElementsByTagName("info")[0];
			var kspots = res.getElementsByTagName("kspot");
			var html = theNavleft.kspotList(kspots,info,true,true,start,stop,
																			"theNavleft.loadMostRecent");
			$(theNavleft.mostRecentSpotsDiv).innerHTML = html;

		}
		var reqURL2 = fullPath("db.php") +
		"?where=1" +
		"&stop=" + stop +
		"&start=" + start +
		"&sortby=dateadded" +
		"&sortkind=DESC" +
		"&spud=trooper" +
		"&count=1" +
		"&title=kspot" +
		"&db=kmaps" +
		"";
		ajaxXML(reqURL2, processLoadMain2,counter(this.mostRecentSpotsDiv));		
	},

	loadMain: function(username) {
		var page = 'main';
		var html = this.removeMainContent(page);
	
		// the main html
		html += "<div class=navleftheader>Here are the highest rated KathySpots</div>";
		html += "<div id=\"" + this.highestRatedSpotsDiv + "\">";
		html += "</div>";
		html += "<br/><div class=navleftheader>Here are the most recent KathySpots</div>";
		html += "<div id=\"" + this.mostRecentSpotsDiv + "\">";
		html += "</div>";
		this.showContent(page,html);
	
		this.loadHighestRated();
		this.loadMostRecent();
	
	},


	loadSpots: function(username) {

		var page = 'spots';
		var html = this.removeMainContent(page);

		html += "<div class=navleftheader>Here are the KathySpots "
		+ userLinkPlus(theUsername,username,false,"have","has") 
		+ " created</div>";
		html += "<div id=" + this.profileSpotListDiv + "></div>";
		this.showContent(page,html);
		this.loadSpotsForUser(username);
	},

	loadSpotsForUser: function(username,start) {
		if (!start) start=0;
		var stop = start+this.RESULTS_PER_PAGE;
	
		var title = 'kspot';
		var where;
		var rest;
		if (username) {
			where = "`username` = '" + username + "'";
			rest = "";
		} else {
			where = "1";
			rest = "&current_user=1";
		}

		var reqURL = fullPath("db.php") +
		"?where=" + where +
		"&spud=trooper" +
		"&title=kspot" +
		"&db=kmaps" +
		"&count=1" +
		"&start=" + start +
		"&stop=" + stop +
		rest +
		"&title=" + title +
		"&db=kmaps" +
		"";
		function processLoadSpots(res) {

			var info = res.getElementsByTagName("info")[0];
			// these are for every query
			var query = info.getAttribute("query");
			var logged_in = info.getAttribute("logged_in");
			// the main XML element
			var kspots = res.getElementsByTagName(title);
			var html = theNavleft.kspotList(kspots,info,false,false,start,stop,
																			"theNavleft.loadSpotsForUser('" 
																			+ username + "',");
			$(theNavleft.profileSpotListDiv).innerHTML = html;
		}
		this.doAjax('spots',reqURL, processLoadSpots);
	},

	// fName: must be the name (or string around)
	kspotList: function(kspots,info,showUser,showOnMap,start,stop,fName) {
		var html = "";
		var totalItems = info.getAttribute('totalitems');
		var N = stop-start;

		html += "<div class=kspotList>";
		html += "<table border=0 cellpadding=0 cellspacing=0 class=\"kspots\">";

		var i=start+1;
		$A(kspots).each
		(function(s) {
			var tit = s.getAttribute("title");
			var id = s.getAttribute("id");
			var lat = s.getAttribute("lat");
			var lon = s.getAttribute("lon");
			html += "<tr><td class=klistItem>";
			html += "<div>";
			html += i;
			html += "</div>";
			html += "</td><td>";
			html += '&nbsp;';
			html += "</td><td>";
			html += "<a href=\"javascript:showKSpot('" + id + "');\">";
			html += tit;
			html += "</a>";
			if (showUser) {
				html += " <em> by " + userLink(theUsername,s.getAttribute("username")) + "</em>";
			}
			html += "</td></tr>";
			if (showOnMap) {
				var logged_in = info.getAttribute("logged_in");
				var username = info.getAttribute("username");
				createMarkerFromDomElement(s,theUsername,logged_in,id);
			}
			i++;
		});

		html += "<tr><td></td><td colspan=2 align=left >";
		var db = false;
		if (db) html += "start="+start + " stop="+stop + " N="+N +" totalItems="+totalItems + "<br/>";
		if (totalItems && totalItems>N) {
			//
			// add a lparen to functions that don't have one
			// this is for functions with one argument, i.e. the start index
			//
			if (!fName.match(/\(/)) fName += "(";

			var min = start/N-5;
			var max = stop/N+5;

			if (db) html += "min="+min + " max="+max + " start="+start + " stop="+stop 
				+ " N="+N +" totalItems="+totalItems + "<br/>";
			for (var i=min; i<max; i++) {
				if (db) html += "("+i+")";
				if (i < 0) continue;
				if (i > (totalItems-1)/N) continue;
				var p =i+1;
				if (start/N < p && p <= stop/N) {
					html += p + " ";
				} else {
					html += "<a href=\"javascript:" + fName + "" + i*N + ")" + "\">";
					html += p;
					html += "</a> ";
				}
			}
		}
		html += "</td></tr>";

		html += "</table>";
		html += "</div>";

		return html;
	},

	getCounter: function() {
		return counter(this.pane.pane('mainNavLeft'));
	},


	doAjax: function(page,url, f, debug) {
		ajaxXML(url, f, this.getCounter());
		if (debug) ajaxDump(url);
	},

	removeMainContent: function(page) {
		this.msg('loading ' + page);
		return "";
	},

	fadeLinks: function(newP) {
		$A(this.pages).each
		(function(page) {
			var p = theNavleft.link(page);
			if ($(p) && p != newP) fadeOut(p);
		});
		fadeIn(this.link(newP));
	},

	refreshCurrentPage: function() {		
		this.loadPage(this.pane.currentPage);
	},
	
	showContent: function(page,html) {
		this.pane.showContent(page,html,function(){theNavleft.fadeLinks(page);});
	},

	link: function(page) {
		return 'href_'+page;
	}

};

// singleton
theNavleft = new Navleft();

function getNavleft() {
	return theNavleft;
}

