var myStatus = "Unknown";
var friends = new Array();
var currentEvent = 0;
var my_id = "";

function setupTime(){
	window.setInterval(getDate(), 1000);
}

function getWhat() {
	
	var what;
	
	if (document.getElementById("whatButton").childNodes[0].nodeValue == "What do you want to do?") {
		what = window.prompt("What do you want to do?", "What's going on?");
	} else {
		what = window.prompt("What do you want to do?", document.getElementById("whatButton").childNodes[0].nodeValue);
	}
	
	if (what == null) return;
	if (what == "") return;
	if (what == "What's going on?") return;
	
	document.getElementById("whatButton").childNodes[0].nodeValue = what;
	storeSessionData("EventWhat", what);

/*
	if (what.length > 15) {
		document.getElementById("whatButton").childNodes[0].nodeValue = what.substring(0, 15).concat("...");
	} else {
		document.getElementById("whatButton").childNodes[0].nodeValue = what;
	}
*/
}

function getWhere() {
	var where;
	
	if (document.getElementById("whereButton").childNodes[0].nodeValue == "Where is it?") {
		where = window.prompt("Where is it?", "Where is the event?");
	} else {
		where = window.prompt("Where is it?", document.getElementById("whereButton").childNodes[0].nodeValue);
	}
				
	if (where == null) return;
	if (where == "") return;
	if (where == "Where is the event?") return;
	
	document.getElementById("whereButton").childNodes[0].nodeValue = where;
	storeSessionData("EventWhere", where);
/*
	if (where.length > 15) {
		document.getElementById("whereButton").childNodes[0].nodeValue = where.substring(0, 15).concat("...");
	} else {
		document.getElementById("whereButton").childNodes[0].nodeValue = where;
	}
*/
}

function getWho() {
	setMode('GET_INVITEES');
	window.location='./invitees.html';
}

function getWhen() {
	window.location='./timeoptions.html';
}

function getInvitees() {
	alert("Invitees Not Implemented");
}

function createEventConfirmation(data){
	if (data.search("Error") == -1) {
		alert("Congratulations, Event " + data + " was created successfully!");
		window.location='./main.html';
	} else {
		alert("There was an error processing your event.  Please try again or make sure that you are logged into your SWARM account.");
		alert(data);
	}
}
		
		
function swarmEvent() {
	var i;
	
	initUser();
	
	var eventWhat = document.getElementById("whatButton").childNodes[0].nodeValue;
	
	
	if (eventWhat == "What do you want to do?") {
		alert("You forgot to enter what you want to do!")
		return;
	}
	
	var eventWhere = document.getElementById("whereButton").childNodes[0].nodeValue;
	
	if (eventWhere == "Where is it?") {
		alert("You forgot to enter your event location!")
		return;
	}
	
	
	if (friends == "") {
		alert("You forgot to select friends!")
		return;
	}
	
	var invitees_list = new Array();
	for (i = 0; i < friends.length; i++) {
		invitees_list.push(friends[i]+"");
	}
	
	
	var start_time_hour = readSessionData("start_time_hour");
	if((start_time_hour == null) || (start_time_hour == "")) {
		alert("You forgot to set the event time!")
		return;
	}
	
	var start_time_hour = readSessionData("start_time_hour");
	var start_time_minute = readSessionData("start_time_minute");
	var start_time_of_day = readSessionData("start_time_of_day");
	var end_time_hour = readSessionData("end_time_hour");
	var end_time_minute = readSessionData("end_time_minute");
	var end_time_of_day = readSessionData("end_time_of_day");
	var event_month = readSessionData("event_month");
	var event_day = readSessionData("event_day");
	var event_year = readSessionData("event_year");
	
	eventStartTime = start_time_hour + ":" + start_time_minute + " " + start_time_of_day;
	eventEndTime = end_time_hour + ":" + end_time_minute + " " + end_time_of_day;
	eventDate = event_month+"-"+event_day+"-"+event_year;
	
	var eventObject = {"sender": my_id, "event": {"name": eventWhat, "organizers":[my_id], "attributes": [{"proposable": false, "alternatives": [{"votes":[], "ballot":[], "name": eventDate}, {"votes":[], "ballot":[], "name": eventStartTime}, {"votes":[], "ballot":[], "name": eventEndTime}], "name": "Time"}, {"proposable": false, "alternatives": [{"votes":[], "ballot":[], "name": eventWhere}], "name": "Location"}], "invitees":invitees_list}, "msgType":"CreateEvent"};
	
	var textOutput = "msg="+JSON.stringify(eventObject);
	
	//testwindow= window.open ("", "testwindow", "location=1,status=1,scrollbars=1,width=100,height=100");
	//testwindow.document.write("<p>"+jsonOutput+"</p>"+"<p>"+textOutput+"</p>");
		
		$.ajax({
			type:"POST",
  			url: "api/mobile/CreateEvent/",
			data: textOutput,
  			dataType: "text",
  			success: createEventConfirmation
  		});
}

function deleteSwarmEventResponseHandler(data) {

}

function deleteSwarmEvent(event_id) {
	initUser();
		
	var jsonObject = {"sender": my_id, "msgType": "DeleteEvent", "event": event_id};
	var textOutput = "msg="+JSON.stringify(jsonObject);
	
		$.ajax({
			type:"POST",
  			url: "api/mobile/DeleteEvent/",
			data: textOutput,
  			dataType: "text",
  			success: deleteSwarmEventResponseHandler
  		});
	  	
}

function queryEventsOrganizingResponseHandler(data) {
	var i;
		
	//document.getElementById("events_list").firstChild.nodeValue = "User Events " + data.EVENTS_ORGANIZING[0];
	var num_events = data[0].EVENTS_ORGANIZING.length;
		
	document.getElementById("events_list").innerHTML = "";
	
	if(num_events == 0) {
		document.getElementById("events_list").innerHTML = "<h4>You Have No<br>Organized Events.</h4>";
		return;
	}
	
	if(num_events > 6) {
		document.getElementById("main_box").style.height = ((num_events-1) * 45) + "px"; 
	}	
	
	for(i=0; i<num_events; i++) {
		addNewMyEventButton(data[0].EVENTS_ORGANIZING[i], data[0].EVENTS_ORGANIZING_NAMES[i]);
	}
}

function querySwarmEventsOrganizing() {
	initUser();
		
	var queryObject = {"sender": my_id, "users": [my_id], "msgType": "QueryUsers", "queries": ["EVENTS_ORGANIZING"]};
	var textOutput = "msg="+JSON.stringify(queryObject);

	//alert(textOutput);

		$.ajax({
			type:"POST",
  			url: "api/mobile/QueryUsers/",
			data: textOutput,
  			dataType: "json",
  			success: queryEventsOrganizingResponseHandler
  		});
		
	document.getElementById("events_list").innerHTML = "<h4>Waiting for<br>response from<br>SWARM Server</h4>";
	  	
}

function querySwarmInvitesResponseHandler(data) {
	var i;
	
	//document.getElementById("events_list").firstChild.nodeValue = "User Events " + data.EVENTS_ORGANIZING[0];
	var num_events = data[0].EVENTS_INVITED.length;
	
	document.getElementById("events_list").innerHTML = "";
	
	
	if(num_events == 0) {
		document.getElementById("events_list").innerHTML = "<h4>You Have No<br>Event Invites</h4>";
		return;
	}
	
	
	if(num_events > 6) {
		document.getElementById("main_box").style.height = ((num_events-1) * 45) + "px"; 
	}	
	
	for(i=0; i<num_events; i++) {
		addNewInvitedEventButton(data[0].EVENTS_INVITED[i], data[0].EVENTS_INVITED_NAMES[i]);		
	}
}

function querySwarmInvites() {
	initUser();
		
	var queryObject = {"sender": my_id, "users": [my_id], "msgType": "QueryUsers", "queries": ["EVENTS_INVITED"]};
	var textOutput = "msg="+JSON.stringify(queryObject);

		$.ajax({
			type:"POST",
  			url: "api/mobile/QueryUsers/",
			data: textOutput,
  			dataType: "json",
  			success: querySwarmInvitesResponseHandler
  		});
  	
	document.getElementById("events_list").innerHTML = "<h4>Waiting for<br>response from<br>SWARM Server</h4>";
}


function queryFriendsStatusResponseHandler(data) {
	

}

function queryFriendsStatus() {
		
	initUser();
	
	var queryObject = {"sender": my_id, "users": [my_id], "msgType": "QueryUsers", "queries": ["STATUS"]};
	var textOutput = "msg="+JSON.stringify(queryObject);

	//alert(textOutput);

		$.ajax({
			type:"POST",
  			url: "api/mobile/QueryUsers/",
			data: textOutput,
  			dataType: "json",
  			success: queryFriendsStatusResponseHandler
  		});
	  	
}

function queryUserStatusResponseHandler(data) {
	
	//alert(data);
	
	if((data[0].STATUS != "Available") &&
	   (data[0].STATUS != "Around") &&
	   (data[0].STATUS != "Busy")) {
	   		document.getElementById("statusDisplay").value = "Unknown";
	   } else {
	   		document.getElementById("statusDisplay").value = data[0].STATUS;
	   }
}

function queryUserStatus() {
		
	initUser();
	
	var queryObject = {"sender": my_id, "users": [my_id], "msgType": "QueryUsers", "queries": ["STATUS"]};
	var textOutput = "msg="+JSON.stringify(queryObject);

	//alert(textOutput);

		$.ajax({
			type:"POST",
  			url: "api/mobile/QueryUsers/",
			data: textOutput,
  			dataType: "json",
  			success: queryUserStatusResponseHandler
  		});
	  	
}

function setUserStatusResponseHandler(data) {
	//alert(data);
}

function setUserStatus(status) {
	initUser();
		
	var jsonObject = {"sender": my_id, "user":my_id, "msgType": "ModifyUser", "STATUS": status};
	var textOutput = "msg="+JSON.stringify(jsonObject);

		$.ajax({
			type:"POST",
  			url: "api/mobile/ModifyUser/",
			data: textOutput,
  			dataType: "text",
  			success: setUserStatusResponseHandler
  		});
	  	
}


function deleteAllEvents() {
	var i;
	for(i = 0; i < 20; i++) {
		deleteSwarmEvent(i);
	}
}

function getDate() {
	cDate = new Date();
	var datetext = cDate.toLocaleString();
	var gmt = datetext.search("GMT");
	document.getElementById("current_time").firstChild.nodeValue = datetext.substring(0, gmt);
}


function addNewMyEventButton(event_id, button_label) {
	var button_id = "event_"+event_id+"_button";
	var button_html = '<button id='+button_id+' onClick="showMyEventDetailsPage('+event_id+');" class="swarm_invites_button">'+button_label+'</button>';
	//document.write(button_html);
	document.getElementById("events_list").innerHTML = document.getElementById("events_list").innerHTML + button_html;
}

function addNewInvitedEventButton(event_id, button_label) {
	var button_id = "event_"+event_id+"_button";
	var button_html = '<button id='+button_id+' onClick="showInvitedEventDetailsPage('+event_id+');" class="swarm_invites_button">'+button_label+'</button>';
	//document.write(button_html);
	document.getElementById("events_list").innerHTML = document.getElementById("events_list").innerHTML + button_html;
}

function queryFriendsListResponseHandler(data) {
	var i;	
	var num_friends = data[0].FRIENDS.length;
	//friends = loadArray('friends', friends);
	
	document.getElementById("friends_list").innerHTML = "";
	
	if(num_friends == 0) {
		document.getElementById("friends_list").innerHTML = "<h4>You Have No<br>SWARM Friends</h4>";
		return;
	}
	
	if(num_friends > 6) {
		document.getElementById("main_box").style.height = ((num_friends-1) * 45) + "px"; 
	}	
	
	for(i=0; i<num_friends; i++) {
		addNewFriendButton(data[0].FRIENDS[i], data[0].FRIENDS_NAMES[i].first, data[0].FRIENDS_NAMES[i].last);
	}
}

function queryFriendsList() {	
	initUser();
		
	var queryObject = {"sender": my_id, "users":[my_id], "msgType": "QueryUsers", "queries": ["FRIENDS"]};
	var textOutput = "msg="+JSON.stringify(queryObject);

	$.ajax({
		type:"POST",
			url: "api/mobile/QueryUsers/",
		data: textOutput,
			dataType: "json",
			success: queryFriendsListResponseHandler
		});
		
	document.getElementById("friends_list").innerHTML = "<h4>Waiting for<br>response from<br>SWARM Server</h4>";
	  	
}

function toggleFriendButton(friend_id){
	if (getMode() == 'GET_INVITEES') {
		if (document.getElementById("friend_" + friend_id + "_button").style.backgroundColor == "rgb(97, 0, 189)") {
			//Unselect Friend
			document.getElementById("friend_" + friend_id + "_button").style.backgroundColor = "rgb(0, 0, 0)";
			removeArrayItem(friends, friend_id);
		}
		else {
			//Unselect Friend
			document.getElementById("friend_" + friend_id + "_button").style.backgroundColor = "rgb(97, 0, 189)";
			addArrayItem(friends, friend_id);
		}
	}
}

function addNewFriendButton(friend_id, first_name, last_name) {
	var button_id = "friend_"+friend_id+"_button";
	var button_html = '<button id='+button_id+' onClick="toggleFriendButton('+ friend_id +');" class="swarm_invites_button">'+first_name+' '+last_name+'</button>';
	document.getElementById("friends_list").innerHTML = document.getElementById("friends_list").innerHTML + button_html;

	if(findFriend(friend_id) != -1) {
		document.getElementById("friend_" + friend_id + "_button").style.backgroundColor = "rgb(97, 0, 189)";
	}
	
}

function addFriendResponseHandler(data) {
	alert(data);
	window.location='./addcontact.html';
}

function addFriend(first_name, last_name, cellphone) {
	initUser();
	
	var jsonObject = {"sender": my_id, "user":my_id, "msgType": "UploadContacts", "contacts": [{
		"firstName": first_name,
		"lastName": last_name,
		"cellphone": cellphone
	}]};
	var textOutput = "msg="+JSON.stringify(jsonObject);
	
	$.ajax({
		type:"POST",
		url: "api/mobile/UploadContacts/",
		data: textOutput,
		dataType: "text",
		success: addFriendResponseHandler
	});
	  	
}

function createUserResponseHandler(data) {
	if (data.search("failed") == -1) {
		alert("Your account has been created. Please login.");
		window.location='./';
	} else {
		alert("Sorry. We could not create your account.  Please try again.");
	}
}

function createUser(first_name, last_name, cellphone, password) {

	if(first_name == "") {
		alert("Please enter your first name.");
		return;
	}
	
	if(last_name == "") {
		alert("Please enter your last name.");
		return;
	}


	if(cellphone == "") {
		alert("Please enter your cellphone number.");
		return;
	}
	
	if(password == "") {
		alert("Please enter your password.");
		return;
	}

	var jsonObject = {"msgType": "CreateUser", "firstName":first_name, "lastName": last_name, "cellphone": cellphone, "password": password};
	var textOutput = "msg="+JSON.stringify(jsonObject);

	$.ajax({
		type:"POST",
		url: "api/mobile/CreateUser/",
		data: textOutput,
		dataType: "text",
		success: createUserResponseHandler
	});

}


function initializeSwarmDB() {
	return;
	alert("Initializing");
	createUser("Carl", "Evans", "cpe3@mac.com", "312.545.2063", "Available", "1234");
	createUser("Bob", "Evans", "bob@mac.com", "312.545.2064", "Available", "1234");
}


function addSliders(sliders) {

	var j;
	var xSlider = new Array(sliders); // horizontal Slider
	var render_class;
	
	if(sliders > 6) sliders = 6;
	
	if(sliders > 3) {
		document.getElementById("main_box").style.height = (sliders*105) + "px"; 
	}	
	
	for (j = 0; j < sliders; j++) {
		var label_html = '<p> Option ' + j + '</p><div class="vote_label"><table border="0"><tr><td width=107px align=left>Really Like</td><td width=107px align=center>Indifferent</td><td width=106px align=right>Really Dislike</td></tr></table></div>';
		
		switch (j) {
			case 0:
				render_class = "horiz_slider0_label";
				break;
			case 1:
				render_class = "horiz_slider1_label";
				break;
			case 2:
				render_class = "horiz_slider2_label";
				break;
			case 3:
				render_class = "horiz_slider3_label";
				break;
			case 4:
				render_class = "horiz_slider4_label";
				break;
			case 5:
				render_class = "horiz_slider5_label";
				break;
			case 6:
				render_class = "horiz_slider6_label";
				break;
			default:
				alert("More than " + (j - 6) + " options not supported in web interface.");
				return;		
		}

		document.getElementById(render_class).innerHTML = label_html;
		
	}
	
		// Create a YUI instance and request the slider module and its dependencies
		YUI().use("slider", function(Y){
		
				for (j = 0; j < sliders; j++) {
				
					// Create a horizontal Slider using all defaults
					xSlider[j] = new Y.Slider({
						axis: 'x',
						min: 0,
						max: 100,
						value: 50,
						length: '260px'
					});
					
					// Pass the input as the 'this' object inside updateInput
					//xSlider.after( "valueChange", updateInput, xInput );
					
					switch(j) {
						case 0:
						    render_class = ".horiz_slider0";
							break;
						case 1:
						    render_class = ".horiz_slider1";
							break;
						case 2:
						    render_class = ".horiz_slider2";
							break;
						case 3:
						    render_class = ".horiz_slider3";
							break;
						case 4:
						    render_class = ".horiz_slider4";
							break;
						case 5:
						    render_class = ".horiz_slider5";
							break;
						case 6:
						    render_class = ".horiz_slider6";
							break;																																			
						default: 
							alert("More than "+(j-6)+" options not supported in web interface.");
							return;
					}
					
					xSlider[j].render(render_class);
					
				}
			
		});
	
}


function manageSessionResponseHandler(data) {
	//alert(data);
	if (data.search("failed") == -1) {
		//
		storeSessionData("swarm_user",data);
		window.location='./main.html';
	} else {
		alert("Sorry. We could not log you in.  Please check your cell number and password.");
	}
	
}

function login(cellphone, password) {
	
	if(cellphone == "") {
		alert("Please enter your cellphone number.");
		return;
	}
	
	if(password == "") {
		alert("Please enter your password.");
		return;
	}

	var jsonObject = {"msgType": "ManageSession", "action": "LOGIN", "cellphone": cellphone, "password": password};
	var textOutput = "msg="+JSON.stringify(jsonObject);
	
	$.ajax({
		type:"POST",
		url: "api/mobile/ManageSession/",
		data: textOutput,
		dataType: "text",
		success: manageSessionResponseHandler
	});
}

function addArrayItem(array_name, item) {
	var i;
	for (i = 0; i < array_name.length; i++) {
		if(array_name[i] == item) {
			alert("Item Already in Array");
			return;
		}
	}
	array_name.push(item);
}

function removeArrayItem(array_name, item) {
	var i, index = -1;
	for (i = 0; i < array_name.length; i++) {
		if(array_name[i] == item) {
			index = i;
			break;
		}
	}
	
	if(index == -1) {
		alert("Item Not Found in Array");
		return;
	}
	
	array_name.splice(index,1);
}

function findFriend(item) {
	var i;
	
	for (i = 0; i < friends.length; i++) {
		if(friends[i] == item) {
			return i;
		}
	}

	return -1;
}

function clearFriends() {
	while(friends.length != 0) {
		toggleFriendButton(friends[0]);
	}
}

function saveFriendsArray() {
	sessionStorage.setItem("friends", friends);
}

function loadFriendsArray() {
	var temp = sessionStorage.getItem("friends");
	if(temp == null) return;
 	temp = temp.split(",");
	for(var i = 0; i < temp.length; i++) {
		if(temp[i] != "") addArrayItem(friends, temp[i]);
	}
}

function initUser() {
	my_id = readSessionData("swarm_user");
	if(my_id == null) {
		window.location='./';	
	}
	//alert("User: " + my_id);
}

function storeSessionData(name,value) {
	sessionStorage.setItem(name, value);                  // defining the session variable
}

function readSessionData(name) {
	return sessionStorage.getItem(name);
}

function eraseSessionData(name) {
	sessionStorage.removeItem(name);
	//sessionStorage.fullname -- This is another way to access data if know the name
}

function setMode(mode) {
	sessionStorage.setItem("mode", mode);
}

function getMode() {
	return sessionStorage.getItem("mode");
}

function initCreatePage() {
	initUser();
	queryUserStatus();
	setWhatButtonLabel();
	setWhereButtonLabel();
	setWhoButtonLabel();
	setWhenButtonLabel();
}

function setWhoButtonLabel() {
	loadFriendsArray();

	if ((friends == null) || (friends == "")) {
		document.getElementById("whoButton").childNodes[0].nodeValue = "Who's coming?"
	} else {
		if (friends.length == 1) {
			document.getElementById("whoButton").childNodes[0].nodeValue = friends.length + " Friend Invited";
		} else {
			document.getElementById("whoButton").childNodes[0].nodeValue = friends.length + " Friends Invited";	
		}
	}
}

function setWhatButtonLabel() {
	var temp = readSessionData("EventWhat"); 
	
	if((temp != null) && (temp != "")) {
		document.getElementById("whatButton").childNodes[0].nodeValue = temp;	
	}
}

function setWhereButtonLabel() {
	var temp = readSessionData("EventWhere"); 
	
	if((temp != null) && (temp != "")) {
		document.getElementById("whereButton").childNodes[0].nodeValue = temp;	
	}	
}

function setWhenButtonLabel() {
	var start_time_hour = readSessionData("start_time_hour");
	var start_time_minute = readSessionData("start_time_minute");
	var start_time_of_day = readSessionData("start_time_of_day");
	var end_time_hour = readSessionData("end_time_hour");
	var end_time_minute = readSessionData("end_time_minute");
	var end_time_of_day = readSessionData("end_time_of_day");
	var event_month = readSessionData("event_month");
	var event_day = readSessionData("event_day");
	
	if ((start_time_hour != null) && (start_time_hour != "")) {
		if ((start_time_hour == end_time_hour) &&
		(start_time_minute == end_time_minute) &&
		(start_time_of_day == end_time_of_day)) {
			document.getElementById("whenButton").childNodes[0].nodeValue = event_month + "/" + event_day + " " + start_time_hour + ":" + start_time_minute + " " + start_time_of_day;
		} else {
			document.getElementById("whenButton").childNodes[0].nodeValue = event_month + "/" + event_day + " " + start_time_hour + ":" + start_time_minute +  " <-> " + end_time_hour + ":" + end_time_minute;
		}
	} else {
		document.getElementById("whenButton").childNodes[0].nodeValue = "When is the event?";
	}
}
function initFriendsPage() {
	initUser();
	queryUserStatus();
	loadFriendsArray();
	queryFriendsList();
}

function initMainPage() {
	initUser();
	queryUserStatus();
	clearSwarmSessionData();
}

function clearSwarmSessionData() {
	eraseSessionData("friends");
	eraseSessionData("EventWhat");
	eraseSessionData("EventWhere");
	eraseSessionData("start_time_hour");
	eraseSessionData("start_time_minute");
	eraseSessionData("start_time_of_day");
	eraseSessionData("end_time_hour");
	eraseSessionData("end_time_minute");
	eraseSessionData("end_time_of_day");
}

function initWhenPage(){
	var currentDate = new Date();
	//alert("Hour: " + currentDate);
	var hour = currentDate.getHours();
	var end_hour = currentDate.getHours();
	var minute = currentDate.getMinutes();
	var display_minute;
	
	if((readSessionData("start_time_hour") != null) && (readSessionData("start_time_hour") != "")) { 
		document.getElementById("start_time_hour").value = readSessionData("start_time_hour");
		document.getElementById("start_time_minute").value = readSessionData("start_time_minute");
		document.getElementById("start_time_of_day").value = readSessionData("start_time_of_day");
		document.getElementById("end_time_hour").value = readSessionData("end_time_hour");
		document.getElementById("end_time_minute").value = readSessionData("end_time_minute");
		document.getElementById("end_time_of_day").value = readSessionData("end_time_of_day");
	} else {
			
		 if(minute < 15) {
		 	display_minute = "15";		
		 } else if ((minute >= 15) && (minute < 30)) {
			display_minute = "30";
		 } else if ((minute >= 30) && (minute < 45)) {
			display_minute = "45";
		 } else {
		 	display_minute = "00";
			hour += 1;
		 }
		 
		 document.getElementById("start_time_minute").value = display_minute;
		 document.getElementById("end_time_minute").value = display_minute;
		 
		 if(hour >= 24) hour -= 24;
		 
		 if (hour < 12) {
		 	document.getElementById("start_time_hour").value = hour+""; 
			document.getElementById("start_time_of_day").value = "am";
		 } else {
			document.getElementById("start_time_hour").value = (hour-12)+""; 
			document.getElementById("start_time_of_day").value = "pm"; 	
		 }
		 
		 end_hour = hour + 2;
		 if(end_hour >= 24) end_hour -= 24;
		 
		 if (end_hour < 12) {
		 	document.getElementById("end_time_hour").value = end_hour+""; 
			document.getElementById("end_time_of_day").value = "am";
		 } else {
			document.getElementById("end_time_hour").value = (end_hour-12)+""; 
			document.getElementById("end_time_of_day").value = "pm"; 	
		 }
		 
	 }
}

function saveTimeOptions() {
	storeSessionData("start_time_hour", document.getElementById("start_time_hour").value);
	storeSessionData("start_time_minute", document.getElementById("start_time_minute").value);
	storeSessionData("start_time_of_day", document.getElementById("start_time_of_day").value);
	storeSessionData("end_time_hour", document.getElementById("end_time_hour").value);
	storeSessionData("end_time_minute", document.getElementById("end_time_minute").value);
	storeSessionData("end_time_of_day", document.getElementById("end_time_of_day").value);
}

function clearTimeOptions() {
	eraseSessionData("start_time_hour");
	eraseSessionData("start_time_minute");
	eraseSessionData("start_time_of_day");
	eraseSessionData("end_time_hour");
	eraseSessionData("end_time_minute");
	eraseSessionData("end_time_of_day");
	eraseSessionData("event_month");
	eraseSessionData("event_day");
	eraseSessionData("event_year");
	initWhenPage();
	window.location='./create.html';
}

function setEventTime() {
	saveTimeOptions();
	window.location='./create.html';
}

function logout() {
	//alert("Logout");
	eraseSessionData("swarm_user");
	clearSwarmSessionData();
	window.location='./';
}

function showMyEventDetailsPage(event_id) {
	storeSessionData("event_number", event_id);
	window.location='./myeventdetails.html';
}

function showInvitedEventDetailsPage(event_id) {
	storeSessionData("event_number", event_id);
	window.location='./invitedeventdetails.html';
}

function initEventDetailsPage() {
	var event_number;
	initUser();
	queryUserStatus();
	event_number = readSessionData("event_number");
	initEventDetailsData(event_number);
}


function initEventDetailsDataHandler(data) {
	var i;
	var votingOpen = data[0].votingOpen;	
	
	document.getElementById("whatDetailsButton").childNodes[0].nodeValue = data[0].name;
	
	if (data[0].inviteesNames.length > 1) {
		document.getElementById("whoDetailsButton").childNodes[0].nodeValue = data[0].inviteesNames.length + " Invitees";
	} else {
		document.getElementById("whoDetailsButton").childNodes[0].nodeValue = data[0].inviteesNames.length + " Invitee";
	}
	
	
	if (votingOpen == true) {
		document.getElementById("whereDetailsButton").childNodes[0].nodeValue = "Voting Still Open";
		document.getElementById("whenDetailsButton").childNodes[0].nodeValue = "Voting Still Open";
	} else {
		for (i = 0; i < data[0].attributes.length; i++) {
			if (data[0].attributes[i].name == "Location") {
				document.getElementById("whereDetailsButton").childNodes[0].nodeValue = data[0].attributes[i].alternatives[0].name;
			}
		}
		document.getElementById("whenDetailsButton").childNodes[0].nodeValue = "-";
	}	
	
}

function initEventDetailsData(event_number) {
	initUser();
	
	var queryObject = {"sender": my_id, "msgType": "QueryEvents", "events": [event_number]};
	var textOutput = "msg="+JSON.stringify(queryObject);

	//alert(textOutput);

		$.ajax({
			type:"POST",
  			url: "api/mobile/QueryEvents/",
			data: textOutput,
  			dataType: "json",
  			success: initEventDetailsDataHandler
  		});
}

function deleteSelectedEvent() {
	var event_number = readSessionData("event_number");
	deleteSwarmEvent(event_number);
	window.location='./events.html';
}


function closeVotingDataHandler(data) {
	window.location='./myeventdetails.html';
}

function endVoting() {
	initUser();
	var event_number = readSessionData("event_number");
	
	var queryObject = {"sender": my_id, "msgType": "CloseVoting", "event": event_number};
	var textOutput = "msg="+JSON.stringify(queryObject);

	//alert(textOutput);

		$.ajax({
			type:"POST",
  			url: "api/mobile/CloseVoting/",
			data: textOutput,
  			dataType: "text",
  			success: closeVotingDataHandler
  		});
}

