// --------------------------- AJAX CUSTOM DATABASE RETRIEVAL CODE -----------------------
// --------------------------- GLOBAL VARIABLES -------------------------------------------

var MAXIMUM_WAITING_TIME = 10000; // milliseconds?

var urlLoginState = 		"/grapheety/auth.logon.controller?username="; // The server-side script
var urlLogout = 			"/grapheety/auth.logoff.controller?username="; // The server-side script

var urlGetUserInfo = 		"/grapheety/user.info.controller?username="; // The server-side script

var urlPostStory = 			"/grapheety/story.add.controller"; // serer side script

var urlDeleteStory = 		"/grapheety/story.delete.controller?username="; // serer side script


var urlGetGrapheetyInCoords="/grapheety/coords.controller?username="; // serer side script

var urlGetFriends = 		"/grapheety/friends.view.controller?username="; // serer side script

var urlCreateFriend = 		"/grapheety/friends.add.controller?username="; // serer side script
var urlDeleteFriend = 		"/grapheety/friends.delete.controller?username="; // serer side script
var urlGetCoordinatesOfStory="/grapheety/story.info.controller?username="; // serer side script
var urlGetRandomStories = 	"/grapheety/random.coords.controller?username="; // serer side script
var urlGetPostComment = 	"/grapheety/comments.add.controller?username=";
var urlGetSearchFriends = 	"/grapheety/search.user.controller?&searchfor=user&searchby=username&username=";
var urlGetSearchFriendsStory="/grapheety/friend.info.controller?username=";
var urlGetStats = 			"/grapheety/Stats?username=";
var urlGetRateStory = 		"/grapheety/ratings.add.controller?username=";
var urlGetCheckLoginStatus= "/grapheety/auth.status.controller?username=";
var urlGetStoryRating = 	"/grapheety/ratings.view.controller?username=";

var urlGetIfStoryRated = 	"/grapheety/ratings.view.controller?username=";
var urlGetSaveStory = 		"/grapheety/story.add.controller?&username=";
var urlDeleteImage = 		"/grapheety/image.delete.controller?username="; // serer side script

var urlGetMessages = 		"/grapheety/message.view.controller?username=";
var urlDeleteMessages =		"/grapheety/message.delete.controller?username=";

var urlSavePreferences = 	"/grapheety/prefs.edit.controller";
var urlGetPreferences = 	"/grapheety/prefs.view.controller";

var urlSendChangePassword = 	"/grapheety/reset.pass.controller";

var urlShareStorySend =		"/grapheety/story.share.controller";


var loggedInHash = ""; // store the session variable passed from updateLoginState()

var resultsViewHTML = "resultsViewHTML data";
var results = "results data";

var viewHTML = "View HTML";
var grapheetyHTML = "<table height='100%' width='100%' border=0><tr>" + 
					"Your <span class='grapheetyLogo'>Grapheety</span>:" + 
					"<div id='results'></div>" + 
					"</td></tr></table>";
var friendsHTML = "<table height='100%' width='100%' border=0><tr><td valign='top'><div id='friendsLoggedIn' class='divShow'>" +
				  "List of your <span class=\"grapheetyLogo\">Grapheety</span> friends:</div>" +
				  "<div id='friendsResults' class='divShow'>(Insert friend code here)</div></td></tr></table>";
var profileHTML = "Profile HTML";
var friendProfileHTML = "Friend Profile HTML";

var randomCoords;

var searchCoordsString = "";

var alphabet = ["A","B","C","D","E","F","G","H","I","J","K"];

var jsonHome = {"restaurants": [
        {"title": "Murray's",
        "id": "100",
        
        "moved": false,
	 "description": "Great Silver Butterknife",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"},
        {"title": "Manny's",
        "id": "200",
        "moved": false,
	 "description": "Old school atmosphere",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"}
    ]
};



var jsonUserProfile = {"profile": [
		{"username": "gavinpquinn",
		 "birthday": "9/23/07",
		 "sex": "Male",
		 "email": "gavinpquinn@gmail.com",
		 "website":  "http://www.gavinpquinn.com",
		 "aim": "gavinqpuinn",
		 "activities":"Cooking, etc.",
		 "interests":"AJAX",
		 "music": "Rock",
		 "books": "Da Vinci Code",
		 "movies": "Lost in Translation",
		 "about":"I am 301",
		 "school":"University of Minnesota"
		}
	]
};
var jsonLegend = {"coords": [
        {"title": "Puebddsfexas",
         "id": "100",
         "author":"Franky 3 Fingers",
         "hasImage":true,
         "imageSrc":"/grapheety/image.view.controller?imageid=99&size=thumb",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
        {"title": "Pueblo, Texas",
         "id": "101",
         "author":"Franky 2 Fingers",
         "hasImage":false,
         "imageSrc":"",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }      
    ]
};

var jsonArtists = {"artists": [
        {"name": "gavinpquinn",
         "id": 2,
         "about": "gavinpquinn is one of the founders of Grapheety. He has travelled to Paris, Rome, and many cities in the U.S. He is from Minneapolis and posts often about daily Minneapolis life.",
         "imageSrc":"/grapheety/image.view.controller?imageid=1&size=thumb"
        },
        {"name": "jonathono2000",
         "id": 21,
         "about": "jonathono2000 is the graphic designer for Grapheety. He just moved to Denver. His posts are around Wisconsin, a few ski trips. He also detailed a lot of unique places in Minneapolis. Stay tuned for his Denver ski profiles.",
         "imageSrc":"/grapheety/image.view.controller?imageid=1167&size=thumb"
        },  
        {"name": "nmeverden",
         "id": 5,
         "about": "nmeverden is the Java programmer for Grapheety. He has posted his trips to NY, as well as many unique automotive experiences around the U.S.",
         "imageSrc":"/grapheety/image.view.controller?imageid=1165&size=thumb"
        },  
        {"name": "moto",
         "id": 10,
         "about": "Moto is another Java programmer for Grapheety. He is the most travelled of us and posts beautiful pictures from Africa, Europe, Asia, and currently resides in Buenos Aires where he is posting some unique experiences.",
         "imageSrc":"/grapheety/image.view.controller?imageid=1166&size=thumb"
        }  
    ]
};

var jsonHome = {"restaurants": [
        {"title": "Murray's",
        "id": "100",
        
        "moved": false,
	 "description": "Great Silver Butterknife",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"},
        {"title": "Manny's",
        "id": "200",
        "moved": false,
	 "description": "Old school atmosphere",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"}
    ]
};

var jsonMyTags = {"mytags": [
        {"title": "Murray's",
         "id": "101",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
          {"title": "Murr32s",
         "id": "1032563",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
         {"title": "Murr32s",
         "id": "1054563",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
         {"title": "Murr32s",
         "id": "103233",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
         {"title": "Murr32s",
         "id": "1031233",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }, 
        {"title": "Murr32s",
         "id": "19903",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }, 
        {"title": "Murr32s",
         "id": "131203",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }, 
        {"title": "Murr32s",
         "id": "10333",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }, 
        {"title": "Murr32s",
         "id": "1033",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        },
          {"title": "Murr33",
         "id": "105",
         "lat":40.0292246448198,
         "lng":4.09026145935059
        }
    ]
};

var jsonHome = {"restaurants": [
        {"title": "Murray's",
        "id": "100",
        
        "moved": false,
	 "description": "Great Silver Butterknife",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"},
        {"title": "Manny's",
        "id": "200",
        "moved": false,
	 "description": "Old school atmosphere",
	 "phone": "612-313-1311",
	 "address": "33 S. 8th St, Minneapolis, MN 55313",
	 "comments": "This place is super kewl"}
    ]
};

var jsonFriends = {"friends": [
        {"username": "nick"},
        {"username": "brett"},
        {"username": "jon"}
    ]
};

var jsonMessages = {"messages": [
        {
         "id": "100",
         "from": "Nick",
	 	 "action": "function()",
	 	 "text": "Added as new friend",
	 	 "date": "9/23/07",
	 	 "type": "add"},
        {
         "id": "101",
         "from": "Nick3",
	 	 "action": "function()",
	 	 "text": "created grapheety",
	 	 "date": "9/28/07",
	 	 "type": "friendrequest"}
    ]
};

var friendsStoriesArray = new Array(); // so that visibility works in firefox.

var coordsSetIndex = 0;
function getCoordsIndex(){
	return coordsSetIndex;
}
function setCoordsPage(index){
	//alert("Going to page: " + index);
	coordsSetIndex = parseInt(index)-1;
	map.clearOverlays();
	refreshMap(); // i think.
}

function stripHTML(string){
	return string.replace(/<\S[^><]*>/g, "")
}

function removeColumnInfos(div){
	var cell;
	if (div) { 
		cell = div; 
	}
	else {
		cell = document.getElementById('columninfos');
	}
	if ( cell.hasChildNodes() )
	{
	    while ( cell.childNodes.length >= 1 )
	    {
	        cell.removeChild( cell.firstChild );
	    }
	}
}

function updateGrapheety() {

	
	if (!document.getElementById('mecontent')) return;
	
	removeColumnInfos(document.getElementById('mecontent'));
	
	var myDiv = document.getElementById('mecontent');
	
	if (!loggedin){
		var tempDiv = document.createElement('div');
		tempDiv.style.cssText = 'margin:10px';
		
		var aLogin = document.createElement('A');
		aLogin.setAttribute('href','/newuser.html');
		aLogin.appendChild(document.createTextNode('New User'));
		tempDiv.appendChild(aLogin);
		tempDiv.appendChild(document.createTextNode(' or Sign In to see your tags.'));
		myDiv.appendChild(tempDiv);
		
	} else {
		
		
		// preferences area
		var preferencesDiv = document.createElement('div');
		//preferencesDiv.style.cssText = 'margin:10px';
		preferencesDiv.setAttribute((document.all ? 'className' : 'class'),'preferencesTab');
		
		var preferencesButton = document.createElement('input');
		preferencesButton.setAttribute('type','button');
		preferencesButton.onclick=new Function('openPreferences()');
		preferencesButton.setAttribute('value','Prefs');
		preferencesButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
		preferencesDiv.appendChild(preferencesButton);
		
		/*
		// wait until we get this ready.
		var profileButton = document.createElement('input');
		profileButton.setAttribute('type','button');
		profileButton.onclick=new Function('openProfile()');
		profileButton.setAttribute('value','Profile');
		profileButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
		preferencesDiv.appendChild(document.createTextNode(' '));
		preferencesDiv.appendChild(profileButton);
		
		*/ 
		myDiv.appendChild(preferencesDiv);
		
		var containerDiv = document.createElement('div');
		containerDiv.setAttribute('id','displaymystoriesdiv');
		containerDiv.style.cssText = 'vertical-align:middle;height:55px;white-space:nowrap;overflow:auto;overflow-x:auto;background:white;margin:10px;padding:10px;';
		if (document.all) { // check if IE
			containerDiv.style.width = parseInt(document.getElementById('outside').style.width.substring(0,3)) - 32;
			containerDiv.style.height = '65';
		}
		
		containerDiv.appendChild(document.createTextNode('My Grapheety: '));
		// add my tags
		for (var i=0;i<jsonMyTags.mytags.length;i++) {
			var tempDiv = document.createElement('span');
			tempDiv.setAttribute((document.all ? 'className' : 'class'),'infoRowReturn');
		
			
			var rowTitleDiv = document.createElement('span');
			rowTitleDiv.setAttribute((document.all ? 'className' : 'class'),'infoRowReturnTitle');
			rowTitleDiv.appendChild(document.createTextNode(jsonMyTags.mytags[i].title));
			tempDiv.appendChild(rowTitleDiv);
			
			var rowTitleAction = document.createElement('span');
			rowTitleAction.setAttribute((document.all ? 'className' : 'class'),'infoRowReturnAction');
			
			
			var aView = document.createElement('A');
			aView.setAttribute('href','javascript:void(0)');
			aView.onclick=new Function('showLocationCoords(' +jsonMyTags.mytags[i].lat + ',' + jsonMyTags.mytags[i].lng + ',' + jsonMyTags.mytags[i].id + ')');
			aView.appendChild(document.createTextNode('View'));
			rowTitleAction.appendChild(aView);
			rowTitleAction.appendChild(document.createTextNode(' | '));
		
			var aDelete = document.createElement('A');
			aDelete.setAttribute('href','javascript:void(0)');
			aDelete.onclick=new Function('deleteStory(' + jsonMyTags.mytags[i].id + ')');
			aDelete.appendChild(document.createTextNode('Delete'));
			rowTitleAction.appendChild(aDelete);
			
			tempDiv.appendChild(rowTitleAction);
			
			containerDiv.appendChild(tempDiv);
			myDiv.appendChild(containerDiv);
		}
	}
		
}

function updateFriends(){
	var myDiv = document.getElementById('friendcontent');
	removeColumnInfos(myDiv);
	
	// show 4-5 top artists
	var topArtistGroupDiv = document.createElement('div');
	topArtistGroupDiv.setAttribute((document.all ? 'className' : 'class'),'famousartistarea');
	topArtistGroupDiv.appendChild(document.createTextNode('Famous Grapheety Artists'));
	myDiv.appendChild(topArtistGroupDiv);
	
	// add the top artists.
	var myTopArtistTable = document.createElement('table');
	var myTopArtistTableBody = document.createElement('tbody');
	var myTopArtistTableRow = document.createElement('tr');
	
	for (var i = 0;i<jsonArtists.artists.length;i++){
		var thisArtistDiv = document.createElement('td');
		//thisArtistDiv.setAttribute((document.all ? 'className' : 'class'),'famousartist');
		/*
		var aProfile = document.createElement('A');
		aProfile.href = 'javascript:void(0)';
		aProfile.onclick=new Function('viewUserProfile(' + jsonArtists.artists[i].id + ')');
		aProfile.appendChild(document.createTextNode(jsonArtists.artists[i].name));
		thisArtistDiv.appendChild(aProfile);
		*/
		thisArtistDiv.appendChild(document.createTextNode(jsonArtists.artists[i].name));
		thisArtistDiv.style.verticalAlign = "top";
		var thisArtistPicture = document.createElement('IMG');
		thisArtistPicture.style.margin = "5px";
		thisArtistPicture.src = jsonArtists.artists[i].imageSrc;
		thisArtistDiv.appendChild(document.createElement('BR'));
		thisArtistDiv.appendChild(thisArtistPicture);
		thisArtistDiv.appendChild(document.createElement('BR'));
		thisArtistDiv.appendChild(document.createTextNode(jsonArtists.artists[i].about));
		thisArtistDiv.appendChild(document.createElement('BR'));
		
		thisArtistDiv.appendChild(document.createElement('BR'));
		var aArtist = document.createElement('A');
		aArtist.setAttribute('href','javascript:void(0)');
		aArtist.onclick=new Function('searchFriendsStory("' + jsonArtists.artists[i].name + '")');
		aArtist.appendChild(document.createTextNode('View Stories'));
		thisArtistDiv.appendChild(aArtist);
		
		myTopArtistTableRow.appendChild(thisArtistDiv);
	}
	myTopArtistTableBody.appendChild(myTopArtistTableRow);
	myTopArtistTable.appendChild(myTopArtistTableBody);
	myDiv.appendChild(myTopArtistTable);
	
	
	if (!loggedin){
		// anything?
		
	} else {	
		

		
		var containerDivMsg = document.createElement('div');
		containerDivMsg.style.cssText = 'clear:left;display:block;max-height:350px;overflow:auto;overflow-y:auto;overflow-x:hidden;background:white;margin:10px;';
		if (jsonMessages.messages.length == 0) {
			containerDivMsg.style.cssText = 'display:none;';
		} else {
			// add the header
			var thisMessageDiv = document.createElement('div');
			thisMessageDiv.setAttribute((document.all ? 'className' : 'class'),'famousartistarea');
			thisMessageDiv.appendChild(document.createTextNode("Your Messages"));
			myDiv.appendChild(thisMessageDiv);
		}

		for (var i = 0;i<jsonMessages.messages.length;i++){
			var messageDiv = document.createElement('div');
			messageDiv.setAttribute((document.all ? 'className' : 'class'),'messageRowReturn');
			messageDiv.style.cssText = 'margin:10px;';
			
			var messageDivTitle = document.createElement('div');
			messageDivTitle.setAttribute((document.all ? 'className' : 'class'),'messageRowReturnUserName');
			messageDivTitle.appendChild(document.createTextNode(jsonMessages.messages[i].from + " on " + jsonMessages.messages[i].date));
			messageDiv.appendChild(messageDivTitle);
			
			var messageDivMessage = document.createElement('div');
			messageDivMessage.setAttribute((document.all ? 'className' : 'class'),'messageRowReturnMessage');
			messageDivMessage.appendChild(document.createTextNode(jsonMessages.messages[i].title + " :: " + jsonMessages.messages[i].text));
			messageDiv.appendChild(messageDivMessage);
			
			var messageDelete = document.createElement('input');
			messageDelete.setAttribute('type','button');
			messageDelete.setAttribute((document.all ? 'className' : 'class'),'mybutton');
		
			messageDelete.setAttribute('value','Shred');
			messageDelete.onclick=new Function('deleteMessage(' + jsonMessages.messages[i].id + ')');
			messageDiv.appendChild(messageDelete);
			containerDivMsg.appendChild(messageDiv);
		}
		
		myDiv.appendChild(containerDivMsg);
		
		var friendSearchDiv = document.createElement('div');
		friendSearchDiv.setAttribute((document.all ? 'className' : 'class'),'searchFriendsTab');
		//friendSearchDiv.style.cssText = 'margin:10px;';
		var friendSearchText = document.createElement('span');
		friendSearchText.style.cssText = 'color:#FFFFFF;';
		friendSearchText.appendChild(document.createTextNode('Find a Friend: '));
		friendSearchDiv.appendChild(friendSearchText);
		var friendSearchInput = document.createElement('input');
		friendSearchInput.setAttribute((document.all ? 'className' : 'class'),'textinputblue textEntryBoxSearch');
		friendSearchInput.style.cssText = 'width:180px;';
		friendSearchInput.setAttribute('type','text');
		friendSearchInput.setAttribute('id','addFriendText');
		friendSearchDiv.appendChild(friendSearchInput);
		friendSearchDiv.appendChild(document.createTextNode(' ')); // space
		var friendSearchButton = document.createElement('input');
		friendSearchButton.setAttribute('type','button');
		friendSearchButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
		friendSearchButton.setAttribute('value','Search');
		
		friendSearchButton.onclick=new Function('searchFriends()');
		friendSearchDiv.appendChild(friendSearchButton);
		var friendSearchResultDiv = document.createElement('div');
		friendSearchResultDiv.setAttribute('id','friendTabSearch');
		friendSearchResultDiv.style.cssText = 'margin:10px;display:none;';
		friendSearchDiv.appendChild(friendSearchResultDiv);
		
		myDiv.appendChild(friendSearchDiv);
		
		var containerDivFriends = document.createElement('div');
		containerDivFriends.style.cssText = 'vertical-align:middle;height:55px;white-space:nowrap;overflow:auto;overflow-x:auto;background:white;margin:10px;padding:10px;';
		
		// fix width for IE
		if (document.all) { // check if IE
			containerDivFriends.style.width = parseInt(document.getElementById('outside').style.width.substring(0,3)) - 32;
			containerDivFriends.style.height = '65';
		}
		
		containerDivFriends.appendChild(document.createTextNode("Your Friends: "));
		// cycle through friends
		for (var i=0;i<jsonFriends.friends.length;i++){
			var friendRowDiv = document.createElement('span');
			friendRowDiv.setAttribute((document.all ? 'className' : 'class'),'friendRowReturn');
			friendRowDiv.style.cssText = 'margin:10px;';
			var friendRowUserName = document.createElement('span');
			friendRowUserName.setAttribute((document.all ? 'className' : 'class'),'friendRowReturnUserName');
			friendRowUserName.appendChild(document.createTextNode(jsonFriends.friends[i].username));
			friendRowDiv.appendChild(friendRowUserName);
			
			var friendRowAction = document.createElement('span');
			friendRowAction.setAttribute((document.all ? 'className' : 'class'),'friendRowReturnAction');
			
			var aView = document.createElement('a');
			aView.setAttribute('href','javascript:void(0)');
			aView.onclick=new Function('searchFriendsStory("' + jsonFriends.friends[i].username + '")');
			aView.appendChild(document.createTextNode('View All Stories'));
			
			friendRowAction.appendChild(aView);
			
			friendRowAction.appendChild(document.createTextNode(' | '));
			
			var aDump = document.createElement('a');
			aDump.setAttribute('href','javascript:void(0)');
			aDump.onclick=new Function('deleteFriend("' + jsonFriends.friends[i].username + '")');
			aDump.appendChild(document.createTextNode('Dump'));
			friendRowAction.appendChild(aDump);
			
			friendRowDiv.appendChild(friendRowAction);
			containerDivFriends.appendChild(friendRowDiv);
		}
	
	
		myDiv.appendChild(containerDivFriends);
		
		
	}	
	var friendView = document.createElement('div');
		friendView.style.cssText = 'border:1px solid #336699;border-bottom:0px;display:none;vertical-align:middle;height:55px;white-space:nowrap;overflow:auto;overflow-x:auto;background:white;padding:10px;';
		friendView.setAttribute('id','friendTabSearchTags');
				// fix width for IE
		if (document.all) { // check if IE
			friendView.style.width = parseInt(document.getElementById('outside').style.width.substring(0,3)) - 32;
			friendView.style.height = '65';
		}
		myDiv.appendChild(friendView);
}

function submitStory(number){
	// number is the iteration
	//var number = currentIteration;
	//alert("gstory: currentIteration: " + number);
	var story = document.getElementById('gstory' + number).value;
	var title = document.getElementById('gname' + number).value;
	
	if (title=='A Distinguished Title') {
		alert("Please add a nice title for your story. Every good story has a good title.");
		return;	
	}

	if (story=='Tell everyone a good story...') {
		alert("Tell us a good story. Everyone wants to know the story for your corner of the world.");
		return;	
	}	
	
	document.getElementById('gstory' + number).readOnly = true;
	document.getElementById('gname' + number).readOnly = true;
	story = stripHTML(story);
	title = stripHTML(title);
	title = title.replace("&","&amp;");
	story = story.replace("&","&amp;");	
	var gstatus; // business or pedestrian

	for (var i=0; i < document.getElementById('gform'+ number).gstatus.length; i++)
	{
		if (document.getElementById('gform' + number).gstatus[i].checked)
		{
			//alert("value: " + document.getElementById('gform' + number).gstatus[i].value);
			gstatus = document.getElementById('gform' + number).gstatus[i].value;
		}
	}

	document.getElementById('storyTabDiv' + number).style.display = "none";
	document.getElementById('storyTabDivSubmit' + number).style.display = "none";
	document.getElementById('storyTabDivSuccess' + number).style.display = "block";
	// write the story to the database
	postStoryData(story,title,currentPoint.lat(),currentPoint.lng(),gstatus);

}

function sendPreferences(){
   var http = createXMLHttpRequest();
    var username = document.getElementById("username").value;
    var password = "";	
   http.open("POST",urlSavePreferences);  
   http.setRequestHeader("Content-Type", "text/xml");
   
   if (document.getElementById('newpassword').value != 
   	   document.getElementById('newpassword2').value) {
   		alert("Please fix Password");
   		return;
   } else {
   	password = document.getElementById('newpassword').value;
   }
   var getemails = 0;
   if (document.getElementById('emailUpdatesGrapheety').checked){
   	getemails = 1;
   }
   
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to save preferences: " + http.responseText);				
		}
		else {
			document.getElementById('preferencesStatus').innerHTML = "Saved";
		}	
	};
    
    
    	var xmlString = "";
			xmlString += "<preferences>";
			xmlString += 	"<username>" + username + "</username>";
			xmlString += 	"<password>" + password + "</password>";
			xmlString += 	"<getemails>" + getemails + "</getemails>";
			xmlString += "</preferences>";
			
	    http.send(xmlString);
}

function sendProfile(){
   var http = createXMLHttpRequest();
    var username = document.getElementById("username").value;

   http.open("POST","/grapheety/user.profile.controller?action=update", true);  
   http.setRequestHeader("Content-Type", "text/xml");
   
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to save profile: " + http.responseText);				
		}
		else {
			document.getElementById('profileStatus').innerHTML = "Saved";
		}	
	};
    
    
    	var xmlString = "";
			xmlString += "<profile>" + 
							"<birthday>" + document.getElementById('myprofileitem_birthday').value + "</birthday>" +
							"<sex>" + document.getElementById('myprofileitem_sex').value + "</sex>" +
							"<aim>" + document.getElementById('myprofileitem_aim').value + "</aim>" +
							"<activities>" + document.getElementById('myprofileitem_activities').value + "</activities>" +
							"<interests>" + document.getElementById('myprofileitem_interests').value + "</interests>" +
							"<music>" + document.getElementById('myprofileitem_music').value + "</music>" +
							"<books>" + document.getElementById('myprofileitem_books').value + "</books>" +
							"<movies>" + document.getElementById('myprofileitem_movies').value + "</movies>" +
							"<about>" + document.getElementById('myprofileitem_about').value + "</about>" +
							"<school>" + document.getElementById('myprofileitem_school').value + "</school>" +
						"</profile>";
			
	    http.send(xmlString);
}

function sendChangePassword(){
   var http = createXMLHttpRequest();

   http.open("POST",urlSendChangePassword);  
   http.setRequestHeader("Content-Type", "text/xml");
   
   if (document.getElementById('emailpassword').value.length == 0) {
   		alert("Please add e-mail account like user@host.com");
   		return;
   } 
  
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to send: " + http.responseText);				
		}
		else {
			document.getElementById('emailpasswordstatus').innerHTML = "Sent e-mail";
		}	
	};
    
    
    	var xmlString = "";
			xmlString += "<preferences>";
			xmlString += 	"<email>" + document.getElementById('emailpassword').value + "</email>";
			xmlString += "</preferences>";
			
	    http.send(xmlString);
}

function getPreferences(){
   var http = createXMLHttpRequest();
    var username = document.getElementById("username").value;
    	
    http.open("POST",urlGetPreferences);  
    http.setRequestHeader("Content-Type", "text/xml");
   
   var getemails = document.getElementById('emailUpdatesGrapheety').checked;
   
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to save preferences: " + http.responseText);				
		}
		else {
			var testEmail = false;
			if (http.responseText.match("TRUE")) {
				testEmail = true;
			}
			document.getElementById('emailUpdatesGrapheety').checked = testEmail;
		}	
	};
    
    
    	var xmlString = "";
			xmlString += "<preferences>";
			xmlString += 	"<username>" + username + "</username>";
			xmlString += "</preferences>";
			
	    http.send(xmlString);
}

function getProfile(){
	// function for getting your own profile to edit
	
	// first update with your own information
	getMyUserProfile();
}


function buildFriendResults(){
	
	getFriendsData();

}

function addFriend(friend){
	//alert("add friend logic...");
	
	if (!loggedin){
		document.getElementById("friendTabSearch").innerHTML = "You cannot add " + friend + " until you Login or <a href='/CreateUser.html'>Create an Account.</a>";
	} else {
		createFriendData(friend);
	}
	
}



function initLogin(){
	
	loggedin=true;
	// update login screens
	
	document.getElementById('loggedout').style.display = "none";
	document.getElementById('loggedInDiv').innerHTML =  document.getElementById("username").value + " |  <a href='javascript:void(0);' onclick='logoutNow();' >Sign Out</a>";
	document.getElementById('loggedInDiv').style.display = "block";
	
	requestUserData();
	
	// build friends results
	buildFriendResults();
			
	// Call maps user initialization
	initLoginMap(document.getElementById("username").value);
	
	// requests user messages
	requestMessages();
	
}

var flyHomeOnce = true;

function updateLoginState() {
 
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    document.getElementById("loggingInDiv").style.display = "block";  
    document.getElementById("loggedInDiv").style.display = "none";
    document.getElementById("loggedout").style.display = "none";
    
    var http = createXMLHttpRequest();
    http.open("GET", urlLoginState + escape(username) + "&password=" + escape(password) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function() {
    								http.abort();
    								},
    								MAXIMUM_WAITING_TIME);
    
    http.onreadystatechange = function() {
		if (http.readyState != 4) { return; }
		clearTimeout(requestTimer);
		if (http.status != 200) { return; }
		
		if (http.responseText.match("FAILURE")){	
			// bad
			
			//alert("Username or password incorrect. Create an account or login again." + http.responseText);
			
			openChangePassword();
			
			document.getElementById("loggingInDiv").style.display = "none";
	    	document.getElementById("loggedInDiv").style.display = "none";
	   		document.getElementById("loggedout").style.display = "block";
		} else {
			// good
			document.getElementById("loggingInDiv").style.display = "none";
	    	document.getElementById("loggedInDiv").style.display = "block";

			loggedInHash = http.responseText;
			initLogin();
			MyApplication.prototype.onMapClick();
		
		} 
	};
	
    http.send(null);
    return false;
}
function logoutNow() {	
	var username = document.getElementById("username").value;
	
	var http = createXMLHttpRequest();
    http.open("GET", urlLogout + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {
		if (http.readyState != 4) { return; }
		clearTimeout(requestTimer);
		if (http.status != 200) { return; }
		
		if (http.responseText.match("FAILURE")){
			alert("Could not log out.");
		}
		else {
			window.location.href = window.location.href;		
		}
	};
    http.send(null);
}

function shareStorySend(){	
		if (document.getElementById("shareemails").value.length == 0) {
			alert("Please fill in an e-mail");
			return;
		}
			
            var emailMatches = document.getElementById("shareemails").value;
            emailMatches = emailMatches.replace(/\n|\r|\s/g,""); // remove anything funny
            
            var personalmessage = stripHTML(document.getElementById("sharepersonalmessage").value); // make sure its clean
            
			var http = createXMLHttpRequest();
					   	
			http.open("POST", urlShareStorySend);  
			http.setRequestHeader("Content-Type", "text/xml");
			var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    						
			http.onreadystatechange = function () {
				if (http.readyState != 4) { return; }
				    clearTimeout(requestTimer);
				    if (!http || http.status != 200) { 
						return;
					}
					
					if (!http.responseText.match("FAILURE")){
						// good
						document.getElementById("shareemailstatus").innerHTML = "Sent E-mail";
                   
				  	} else {
				  		// failed
						alert("Failed: " + http.responseText);
				  	}				
				};			
			var xmlString = "";
			xmlString += "<message>";
			xmlString += "<personal>" + personalmessage + "</personal>";
			xmlString += "<emails>" + emailMatches + "</emails>";
			xmlString += "<storyid>" + currentStory + "</storyid>";
			xmlString += "</message>";
			
			//alert(xmlString);
	    	http.send(xmlString);
}

function viewUserProfile(id) {
	
	var profileDiv = document.getElementById('userProfile');
	profileDiv.style.cssText = "width:400px;top:100px;left:50%;margin-left:-200px;z-index:9999;background:white;"
	getUserProfile(id); // ajax call for preferences
	
	document.getElementById('userProfile').style.display= "block";

	buildUserProfile();
	document.getElementById('hideIt').style.display = "block";	
	document.getElementById('hideIt').style.height = getPageSize()[1];
	document.getElementById('hideIt').style.width = getPageSize()[0];
}

function buildUserProfile() {
	
	var profileDiv = document.getElementById('userProfile');
	removeColumnInfos(profileDiv); // clean
	
	var closeButton = document.createElement('input');
	closeButton.setAttribute('type','button');
	closeButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
	closeButton.onclick=new Function('closeUserProfile()');
	closeButton.setAttribute('value','Close');
	closeButton.style.cssText = "float:right;";
	profileDiv.appendChild(closeButton);
	
	for (var j in  jsonUserProfile.profile[0]){
		if (jsonUserProfile.profile[0][j] == "") { 
		// next
	 	} else {
			var profileItem = document.createElement('div');
			if (j == "username"){
				profileItem.style.cssText = "margin:10px;font-weight:bold;";	
			} else {
				profileItem.style.cssText = "margin:10px;";
			}
			if (j=="pictureurl"){
				var profilepic = document.createElement('IMG');
				profilepic.src = jsonUserProfile.profile[0][j];
				profileItem.appendChild(profilepic);
			} else {
				profileItem.appendChild(document.createTextNode(j + ": " + jsonUserProfile.profile[0][j]));
			}
			profileDiv.appendChild(profileItem);
	 	}
	}
}

function buildMyUserProfile() {
	
	var profileDiv = document.getElementById('profile');
	removeColumnInfos(profileDiv); // clean
	
	var closeButton = document.createElement('input');
	closeButton.setAttribute('type','button');
	closeButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
	closeButton.onclick=new Function('closeProfile()');
	closeButton.setAttribute('value','Close');
	closeButton.style.cssText = "float:right;";
	profileDiv.appendChild(closeButton);
	
	var usernameItem = document.createElement('div');
	usernameItem.style.cssText = "margin:10px;font-weight:bold;";	
	usernameItem.appendChild(document.createTextNode(jsonUserProfile.profile[0].username));
	profileDiv.appendChild(usernameItem);
	
	var profilepic = document.createElement('IMG');
	profilepic.src = jsonUserProfile.profile[0].pictureurl;
	profilepic.style.cssText = "margin:10px;";
	profileDiv.appendChild(profilepic);
	
	var tempTable = document.createElement('TABLE');
	var tempTableTBODY = document.createElement('TBODY');

	for (var j in  jsonUserProfile.profile[0]){
			if (j == "username" ||  j == "pictureurl"){
				
			} else {
				var profileItem = document.createElement('tr');
			
				var titleSpan = document.createElement('td');
				titleSpan.style.color = "#FFFFFF";
				titleSpan.style.textAlign = "right";
				titleSpan.appendChild(document.createTextNode(j + ": "));
				profileItem.appendChild(titleSpan);
				
				var inputItem = document.createElement('td');
				var thisItem = document.createElement('input');
				thisItem.setAttribute('type','text');
				thisItem.setAttribute('id','myprofileitem_' + j);
				thisItem.setAttribute('value',jsonUserProfile.profile[0][j]);
				inputItem.appendChild(thisItem);
				
				profileItem.appendChild(inputItem);
					
				tempTableTBODY.appendChild(profileItem);
			}
	}
	
	tempTable.appendChild(tempTableTBODY);
	profileDiv.appendChild(tempTable);
	
	var saveButton = document.createElement('input');
	saveButton.setAttribute('type','button');
	saveButton.setAttribute((document.all ? 'className' : 'class'),'mybutton');
	saveButton.onclick=new Function('sendProfile()');
	saveButton.setAttribute('value','Save');
	profileDiv.appendChild(saveButton);
	
	var saveProfileDiv = document.createElement('div');
	saveProfileDiv.setAttribute('id','saveprofilediv');
	profileDiv.appendChild(saveProfileDiv);
	
}

function closeUserProfile() {
	document.getElementById('userProfile').style.display = "none";
	
	document.getElementById('hideIt').style.display = "none";		
}

function getUserProfile(id) {   
    var http = createXMLHttpRequest();
    http.open("GET", "/grapheety/user.profile.controller?action=view&id=" + id + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
		if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
	  	if (http.responseText != ""){	
			jsonUserProfile = eval('(' + http.responseText + ')');
			//alert(http.responseText);
			buildUserProfile();
		} 	
	};
 
    http.send(null);
    
}

// different from the last call - different build function
function getMyUserProfile() {   
    var http = createXMLHttpRequest();
    http.open("GET", "/grapheety/user.profile.controller?action=view&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
		if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
	  	if (http.responseText != ""){	
			jsonUserProfile = eval('(' + http.responseText + ')');
			//alert(http.responseText);
			buildMyUserProfile();
		} 	
	};
 
    http.send(null);
    
}

function requestUserData() {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetUserInfo + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
		if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
	  	if (http.responseText != ""){	
			
			//document.getElementById('grapheetyTabStories').innerHTML = "<div class='preferencesTab'><input type='button' class='mybutton' onclick='openPreferences();' value='Preferences'/>  </div>" + http.responseText;
			jsonMyTags = eval('(' + http.responseText + ')');
			updateGrapheety();
			
			
		} 	
	};
 
    http.send(null);
    
}

function requestMessages() {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetMessages + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
		if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
	  	if (!http.responseText.match("FAILURE")){	
			
			jsonMessages = eval('(' + http.responseText + ')');
			updateFriends();
			
		} else { alert(http.responseText); }
	};
 
    http.send(null);
}

function deleteMessage(messageId) {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlDeleteMessages + escape(username) + "&messageid=" + escape(messageId) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
		if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
	  	if (!http.responseText.match("FAILURE")){	
			requestMessages();
		} 	else { alert(http.responseText); }
	};
 
    http.send(null);
}

function postStoryData(story,title,lat,lng,gstatus) {
    var http = createXMLHttpRequest();
    var username = document.getElementById("username").value;
   
   // http.open("GET", urlPostStory + 
   // 	escape(username) + 
   // 	"&text=" + escape(story)+ 
   // 	"&title=" + escape(title)+ 
   // 	"&public=" + escape(gstatus)+ 	// public or private
   // 	"&lat=" + escape(lat)+ 
    //	"&lng=" + escape(lng)+ 
    	
    //	"&dummy=" + (new Date()).getTime(), true);
    	
   http.open("POST",urlPostStory);  
   http.setRequestHeader("Content-Type", "text/xml");
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to post story: " + http.responseText);
				
		}
		else {
			requestUserData(); // update grapheety.
			// setup the picture frame with returned number.
			var iFrame;
			if (frames['iframeuploadmap' +currentIterationClick]){
				iFrame = frames['iframeuploadmap' + currentIterationClick];
			}
			else {
				iFrame = frames['iframeuploadmarker' + currentIteration];
			}
			iFrame.document.getElementById('storyid').value = http.responseText;
			currentStory = http.responseText;
			iFrame.document.getElementById('username').value = document.getElementById("username").value;
			iFrame.storyUploaded();
		}	
	};
    

    
    	var xmlString = "";
			xmlString += "<story>";
			xmlString += 	"<username>" + username + "</username>";
			xmlString += 	"<title>" + title + "</title>";
			xmlString += 	"<text>" + story + "</text>";
			xmlString += 	"<public>" + gstatus + "</public>"; // 0 or 1
			xmlString += 	"<lat>" + lat + "</lat>";
			xmlString += 	"<lng>" + lng + "</lng>";

			xmlString += "</story>";
			
	    http.send(xmlString);
}

function deleteStory(storyId) {

    var username = document.getElementById("username").value;
    var http = createXMLHttpRequest();
    http.open("GET", urlDeleteStory + 
    	escape(username) + 
    	"&storyid=" + escape(storyId) + "&dummy=" + (new Date()).getTime(), true);
   
    var requestTimer = setTimeout(function(){ 
    								http.abort();},
    							    MAXIMUM_WAITING_TIME);
   
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
	  	clearTimeout(requestTimer);
	  	if (http.status != 200) { return; }
	  	
		if (http.responseText.match("FAILURE")){	
			alert("Failed to Delete story: " + http.responseText);	
		}
		else {
			refreshMap();
			requestUserData(); // update grapheety.	
		}	
	};
    http.send(null);
}

function getGrapheetyInCoords(swlat,swlng,nelat,nelng,set) {
    var username = document.getElementById("username").value;
    var searchString = "";
    if (document.getElementById('searchBarWhat')) {
   		searchString = document.getElementById("searchBarWhat").value;
    }
    if (searchString == "Search") {
    	searchString = "";
    }

	if (swlat == NaN || swlng == NaN || nelat == NaN || nelng == NaN ||
		swlat == "NaN" || swlng == "NaN" || nelat == "NaN" || nelng == "NaN") { return; }
	var http = createXMLHttpRequest();
    http.open("GET", urlGetGrapheetyInCoords + 
    				  escape(username) + 
    				  "&southWestLat=" + escape(swlat)+ 
    				  "&southWestLng=" + escape(swlng)+ 
    				  "&northEastLat=" + escape(nelat)+ 
    				  "&northEastLng=" + escape(nelng) + 
    				  "&set=" + escape(set) +
    				  "&search=" + escape(searchString) +
    				  "&storyid=" + escape(currentStory) +
    				  "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    
    
    http.onreadystatechange = function() { 
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
		// first clear map.
	    if (http.status != 200) { 
	    	return;
	    }
		if (http.responseText != ""){	
			
			jsonLegend = eval('(' + http.responseText + ')');
			//document.getElementById('viewTabContent').innerHTML = http.responseText; // fill the div.

			for (var i=0; i < jsonLegend.coords.length;i++){ // temporary by gavin
						addStoryToMapFromDatabase(jsonLegend.coords[i].lat, 
												  jsonLegend.coords[i].lng, 
												  jsonLegend.coords[i].title, 
												  jsonLegend.coords[i].date,
												  jsonLegend.coords[i].username,
												  i,
												  jsonLegend.coords[i].id,
												  true,
												  jsonLegend.coords[i].rating,
												  jsonLegend.coords[i].votes);		
			}
			
			
			
		}	   	
    };
    http.send(null);
}

function getFriendsData() {
	if (!loggedin) {updateFriends();return;}
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetFriends + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    						
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
		// first clear map.
	    if (!http || http.status != 200) { 
	    	return;
	    }
		if (http.responseText != ""){	
			jsonFriends = eval('(' + http.responseText + ')');
			updateFriends();
		} else {
			alert("FAILED TO POST handleHttpResponseGetGrapheetyInCoords()");	
		}	
	};
    http.send(null);
}

function createFriendData(friend) {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlCreateFriend + escape(username) + "&friendname=" + escape(friend) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    						
    http.onreadystatechange = function handleHttpResponseCreateFriend() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
		// first clear map.
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){	
			buildFriendResults();
		}
		else {
			alert(http.responseText);	
		}	
	};

    http.send(null);
}

function deleteFriend(friendname) {
    var username = document.getElementById("username").value;

	var http = createXMLHttpRequest();
    http.open("GET", urlDeleteFriend + escape(username) + "&friendname=" + escape(friendname) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function handleHttpResponseDeleteFriend() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
		// first clear map.
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){	
			buildFriendResults();
		}
		else {
			alert("User not able to be deleted.");	
		}	
	};
    http.send(null);
}

function getCoordinatesOfStory(story) {
    var username = document.getElementById("username").value;
    currentStory = story; // set this as current.
    //map.clearOverlays();
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetCoordinatesOfStory + escape(username) + "&storyid=" + escape(story) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (!http || http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var coords = http.responseText.split(" ");
			var lat = NaN;
			var lng = NaN;
			
			try {
				lat = parseFloat(coords[0]);
				lng = parseFloat(coords[1]);
				//map.setCenter(new GLatLng(lat,lng,0),currentZoom);
				
			} catch (e) {
				alert("error: " + e);
				getCoordinatesOfStory(story);
				return;
			}
			showLocationCoords(lat,lng,currentStory, "set");
		} else {
			alert("We do not have that story: " + http.responseText);
			map.setCenter(new GLatLng(44.89556,-93.314976,0),currentZoom);
		}	
	};
    http.send(null);
}

function getRandomStories() {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetRandomStories + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var coords = http.responseText.split(",");
			randomCoords = coords;		
			var storyId = parseInt(coords[0]);
			var lat = parseFloat(coords[1]);
			var lng = parseFloat(coords[2]);
			currentStory = storyId;		
			
			showLocationCoords(lat,lng,currentStory, "set");
			map.panBy(new GSize(0,170));
			// getCoordinatesOfStory(storyId);
		}
		else {
			alert("story not in database: " + http.responseText);
			map.setCenter(new GLatLng(44.89556,-93.314976,0),currentZoom);
			map.panBy(new GSize(0,170));
		}	
	};

    http.send(null); 
}


function postComment(storyId,comment) {

    var username = document.getElementById("username").value;
    if (comment.length == 0){
    	alert("Please add a comment before submitting.");
    	return;
    }
    comment = comment.replace("&","&amp;");
	
	
	comment = stripHTML(comment);
	currentStory = storyId;
	
	var http = createXMLHttpRequest();
    http.open("POST", urlGetPostComment); // + 
    http.setRequestHeader("Content-Type", "text/xml");
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var element = "commentFrame" + currentStory;
			var f = document.getElementById('storyFrame' + currentStory); // = "http://dev.grapheety.com/grapheety/comments.view.controller?action=get&storyid=" + currentStory;
			f.src = f.src + "&dummy=" + (new Date()).getTime();
		}
		else {
			alert("Could not post comment: " + http.responseText);
		}	
	};
	
	//escape(username) + "&storyid=" +  escape(storyId) + "&text=" + escape(comment) + "&dummy=" + (new Date()).getTime(), true);
           var xmlString = "";
			xmlString += "<comment>";
			xmlString += 	"<username>" + username + "</username>";
			xmlString += 	"<text>" + comment + "</text>";
			xmlString += 	"<storyid>" + storyId + "</storyid>"; // 0 or 1
	

			xmlString += "</comment>";
			
	    http.send(xmlString);
}

function searchFriends() {
	if (!loggedin) {
		document.getElementById('friendTabSearch').innerHTML = "<a href='/CreateUser.html'><img border='0' src='/Images3/signup_on.gif'></a> or Sign In to see your Friends.";
		return;
	}
	
	
    var username = document.getElementById("username").value;
    var searchText = document.getElementById("addFriendText").value;
    searchText = searchText.replace("&","and");
	searchText = searchText.replace("'","");
	
	var http = createXMLHttpRequest();
    http.open("GET", urlGetSearchFriends + escape(username) + "&searchstring=" +  escape(searchText) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
        if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }	
		if (!http.responseText.match("FAILURE")){
				if (http.responseText != "") {
					document.getElementById('friendTabSearch').innerHTML = http.responseText;
					document.getElementById('friendTabSearch').style.display = "block";
				} else {
					document.getElementById('friendTabSearch').innerHTML = "No search results...";
				}	
		} else {
			alert("Could not search friends: " + http.responseText);
		}	
	};
    http.send(null);
}

function searchFriendsStory(searchText) {
    var username = document.getElementById("username").value;
    searchText = searchText.replace("&","and");
	searchText = searchText.replace("'","");
	
	var http = createXMLHttpRequest();
    http.open("GET", urlGetSearchFriendsStory + escape(username) + "&friendname=" +  escape(searchText) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    						
    http.onreadystatechange = function() {	
        if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }	
		if (!http.responseText.match("FAILURE")){
			document.getElementById('friendTabSearchTags').style.display = "block";
        	//friendsStoriesArray.push('friendTabSearchTags');
     
     		

			document.getElementById('friendTabSearchTags').innerHTML = searchText + "'s Stories: " + http.responseText;
		} else {
			alert("Could not search friends stories: " + http.responseText);
		}	
	};

    http.send(null);
}

function getStats() {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetStats + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
        if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var stats = http.responseText.split(" ");
			var userCount = stats[0];
			document.getElementById('totalUsers').innerHTML = userCount + " ";
			var storyCount = stats[1];
			document.getElementById('totalStories').innerHTML = storyCount + " ";
		}
		else {
			alert("Could not get stats: " + http.responseText);
		}	
	};
    http.send(null);
}

function rateStory(storyid, rating) {
    var username = document.getElementById("username").value;
    var html = "Vote submitted (takes 1 minute to tally): ";
    for (var i = 0; i < parseInt(rating); i++){ 
    	html = html + "<img src='/Images3/star_on.gif'/>";
    }
    //document.getElementById('storyFrame' + storyid).document.getElementById('voteArea' + storyid).innerHTML = html;

    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetRateStory + escape(username) + "&storyid=" + escape(storyid) +"&score=" + escape(rating) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
        if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var storyId = http.responseText;
			var f = document.getElementById('storyFrame' + currentStory); // = "http://dev.grapheety.com/grapheety/comments.view.controller?action=get&storyid=" + currentStory;
		    f.src = f.src + "&dummy=" + (new Date()).getTime();
		} else {
			alert("Could not rate: " + http.responseText);
		}	
	};

    http.send(null);
}

function checkLoginStatus() {
	
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetCheckLoginStatus + escape(username) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			if (http.responseText.match("Guest") || http.responseText == "") {
					loggedin=false;
			} else {
				loggedin=true;
				document.getElementById('username').value = http.responseText;
				document.getElementById("loggingInDiv").style.display = "none";
	    		document.getElementById("loggedInDiv").style.display = "block";
	   			document.getElementById("loggedout").style.display = "none";
						
				initLogin();
						
			}
		} else {
			openChangePassword();
		}
	};
    http.send(null);
    
}

function getStoryRating(storyid){

    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetStoryRating + escape(username) + "&storyid=" + escape(storyid) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
	    if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			var ratings = http.responseText.split(" ");
			var storyid = ratings[0];
			var stars = parseInt(ratings[1]);
			var html = "";
			for (var i=0; i < stars.length; i++){
				html = html + "<img border=0 src='/Images3/star_on.gif'>";
			}
		} else {
			alert("Could not get rating: " + http.responseText);
		}	
	};
    http.send(null);
}

function getIfStoryRated(){
	var storyId = currentStory;
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
    http.open("GET", urlGetIfStoryRated + escape(username) + "&storyid=" + escape(storyId) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);
    http.onreadystatechange = function() {	
	    if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
		if (!http.responseText.match("FAILURE")){
			// already rated
			document.getElementById("voteArea" + storyId).innerHTML = "I already voted!";
		} else {
			// ok, we can rate it.
			document.getElementById("voteArea" + storyId).innerHTML = "Vote by clicking the star: " + 
						   "<a href='javascript:void(0);'  onclick='rateStory(" + storyId + ",1);'><img  src='/Images3/star_on.gif'></a>" +
						   "<a href='javascript:void(0);'  onclick='rateStory(" + storyId + ",2);'><img src='/Images3/star_on.gif' ></a>" + 
						   "<a href='javascript:void(0);'  onclick='rateStory(" + storyId + ",3);'><img src='/Images3/star_on.gif' ></a>" +
						   "<a href='javascript:void(0);'  onclick='rateStory(" + storyId + ",4);'><img src='/Images3/star_on.gif' ></a>" + 
						   "<a href='javascript:void(0);'  onclick='rateStory(" + storyId + ",5);'><img src='/Images3/star_on.gif' ></a>" + 
						   "<div style='float:right;' class='mybutton smallfakewhite' onclick='rateStory(" + storyId + ",-1);'>Flag</div>"; 
		}	
	};
    http.send(null);
}

function saveStory(storyId){
	// need to save.
	
	var iFrame;
	
	if (frames['storyFrame' +storyId]){
		iFrame = frames['storyFrame' + storyId];
	}
	else {
		alert("No story frame?");
	}
			
	var title = "Grapheety Test Title";
	if (iFrame.document.getElementById('title')){
		title = iFrame.document.getElementById('title').value;
	}
	var text = "Grapheety Test Text";
	if (iFrame.document.getElementById('text')){
		text = iFrame.document.getElementById('text').value;
	}
	var tags = "Grapheety Test Tags";
	if (iFrame.document.getElementById('tags')){
		tags = iFrame.document.getElementById('tags').value;
	}
			

    var username = document.getElementById("username").value;
    
    text = stripHTML(text);
	title = stripHTML(title);
	
    title = title.replace("&","&amp;");
	text= text.replace("&","&amp;");
    
    var http = createXMLHttpRequest();		
    
    http.open("POST", urlGetSaveStory);		
    http.setRequestHeader("Content-Type", "text/xml");
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);   			
    http.onreadystatechange = function() {
    	if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }
    	if (!http.responseText.match("FAILURE") && http.responseText != ""){   
		    document.getElementById("storyFrame" + storyId).src= "/grapheety/story.view.controller?storyid=" + storyId + "&dummy=" + (new Date()).getTime();
			//document.getElementById("storyFrame" + storyid).src= "/grapheety/story.view.controller?storyid=" + storyid;
		} else {
			alert("Could not save: " + http.responseText);
		}	
	};

       var xmlString = "";
			xmlString += "<story>";
			xmlString += 	"<username>" + username + "</username>";
			xmlString += 	"<title>" + title + "</title>";
			xmlString += 	"<text>" + text + "</text>";
			xmlString += 	"<storyid>" + storyId + "</storyid>"; // 0 or 1
	

			xmlString += "</story>";
			
	    http.send(xmlString);

	document.getElementById("headerTitle" + storyId).innerHTML = title;	
	document.getElementById("storyEditButton" + storyId).style.display = "block";
	document.getElementById("storySaveButton" + storyId).style.display = "none";

}

function deleteImage(imageid,storyid) {
    var username = document.getElementById("username").value;
    
    var http = createXMLHttpRequest();
  	http.open("GET", urlDeleteImage + escape(username) + "&imageid=" + escape(imageid) + "&dummy=" + (new Date()).getTime(), true);
    var requestTimer = setTimeout(
    						function() {
    							http.abort();
    							// inform user?
    						}, 	
    						MAXIMUM_WAITING_TIME);      
    http.onreadystatechange = function() {	
        if (http.readyState != 4) { return; }
    	clearTimeout(requestTimer);
	    if (http.status != 200) { 
	    	return;
	    }	
    
		if (!http.responseText.match("FAILURE") && http.responseText != ""){	
			
			document.getElementById("storyFrame" + storyid).src = document.getElementById("storyFrame" + storyid).src;
		}
		else {
			alert("Image could not be deleted: " + http.responseText);	
		}	
	};
    http.send(null);
}

function createXMLHttpRequest() {
	try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
	try { return new XMLHttpRequest(); } catch(e) {}
	alert("XMLHttpRequest not supported");
	return null;
}
