/* AppController object
	-initializes and manages the database search and map interaction
*/
function AppController(admin,userId,signIn)
{
	this.admin = (admin ? admin : false);
	// set up the web-service
	this.ws = new Locator_WS(this);
	this.userId = userId;
    this.signedIn = signIn;
	this.mc = new MapController();
	this.results = [];
	this.requestInProgress = false;
	this.lat = 0;
	this.lng = 0;
	this.radius = 0;
	this.zip=null;
	this.meetingId=0;
	this.host=false;
	this.print=false;
	
	// for embedURL and rss meeting map
	this.embedURLZoomLevel = 0;
	this.embedURLCenterlat = 0;
	this.embedURLCenterlng = 0;
	this.rssMeetingId = 0;
	
}



/*************************************************************************************/

AppController.prototype.initializeprintscreen = function(map_div, latitude, longitude, zoom,rad,occ)
{
	// set up the map
	this.mc.initialize(map_div, latitude, longitude, zoom);
	

	// set filter flags to default values
	this.onlySched = false;
	this.hideBooked = true;
	this.hideAssigned = true;
	this.codeFilter = occ;
	this.print=true;

	// get date
	var radius = rad;
	var startDate = '01/01/08';
	var endDate = '01/01/41';
   
	if (lat != 0 && lon != 0) {				
			this.lat = lat;
			this.lng = lon;
			this.meetingId = meetingId;
			APP_CONTROLLER.mc.centreOnAddress(latitude, longitude, radius);

			//store lat lng rad to draw the circle
			APP_CONTROLLER.lat = latitude;
			APP_CONTROLLER.lng = longitude;
			APP_CONTROLLER.radius = radius;		
			
			// do search
			APP_CONTROLLER.requestInProgress = true;
			
			APP_CONTROLLER.ws.searchLocations(startDate, endDate, latitude, longitude, radius, this.print, this.onlySched);
				
    }	
	else
	{ 
		alert ("No address provided, using current center point of map to locate meetings");
	
	}

	
}


AppController.prototype.initializehost = function(map_div, latitude, longitude, zoom,host)
{
	// set up the map
	this.mc.initialize(map_div, latitude, longitude, zoom);
	document.getElementById("orgID").value = "";

	// set filter flags to default values
	this.onlySched = false;
	this.hideBooked = true;
	this.hideAssigned = true;
	this.codeFilter = null;
	this.host=host;
	// for some reason these don't get reset

	// initialize admin fields
	if (this.host) {
		document.getElementById("hideAssigned").checked = true;
		this.currentMtg = null;
		this.assignedGuests = 0;
	}
}
// doFind function is called when the search form is submitted
AppController.prototype.doFindHostArea = function(lat,lon,meetingId,rad,print) {
	if (this.requestInProgress) return;

	// clean up old results--remove marker objects
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].marker) delete this.results[i].marker;
	}
	
	// get date
	var radius = rad;
	var startDate = '01/01/08';
	var endDate = '01/01/41';
   
	if (lat != 0 && lon != 0) {				
			this.lat = lat;
			this.lng = lon;
			this.meetingId = meetingId;
			APP_CONTROLLER.mc.centreOnAddress(lat, lon, radius);

			//store lat lng rad to draw the circle
			APP_CONTROLLER.lat = lat;
			APP_CONTROLLER.lng = lon;
			APP_CONTROLLER.radius = radius;		
			
			// do search
			APP_CONTROLLER.requestInProgress = true;
			APP_CONTROLLER.setMessage("Searching...");
			APP_CONTROLLER.ws.searchLocations(startDate, endDate, lat, lon, radius, this.host, this.onlySched);
				
    }	
	else
	{ 
		alert ("No address provided, using current center point of map to locate meetings");
	
	}
}

AppController.prototype.showHost = function(peopleArray) {
	// clear map and found list
	this.mc.clearMap();
	
	if (!peopleArray || peopleArray.length == 0) {
		this.setMessage("No Meetings Found");
		return;
	}
	// clear the selected meeting and assigned guests
	if (this.host) {
		//this.currentMtg = null;
		this.assignedGuests = 0;

	}
	
	
	document.getElementById("foundContainer").innerHTML = "";
	// initialize holders for list html
	var listHtml = "";
	var guestHtml = "";
	var printGuestHtml = "<table width=740 align=center>";
	var j =1;
	
	// set up the admin list headers
	if (this.host) {
		listHtml = '<div id="foundMeetingsReport"><table><tr><td width=260 colspan=2><b>Meetings</b></td><td><b>Date and Time</b></td></tr>';
		guestHtml = '<div id="foundGuestsReport"><table><tr><td width=360 colspan=3><b>Unassigned Guests Nearest Your Meeting<br/> (select one or more for email)</b></td></tr>';
		
	}
	else {
		listHtml = "<table><tr><td><b>Meetings</b></td><td><b>Date and Time</b></td></tr>";
	}
	// get ooc filter here since the onchange function isn't working
	this.codeFilter = this.validateOOC(document.getElementById("orgID").value);

	// this is for finding the currentMtg in the new results (admin only)
	var foundCurrent = null;
	
	var centerPoint = new GLatLng(this.lat, this.lng);
	
	
   
	peopleArray.sort(function(a,b)
		{
		adist = centerPoint.distanceFrom(new GLatLng(a.lat,a.lng));
		bdist = centerPoint.distanceFrom(new GLatLng(b.lat,b.lng));
		return adist - bdist});
	
	// for each person in the results, add marker to the map and an entry in list
	for (var i=0; i<peopleArray.length; i++) {
		 
		// do filtering...
		// make sure this is a host if not in admin
		if (!this.host ) 
			continue;
		// if only scheduled flag, don't want blank meeting dates
		if (this.onlySched && peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].sched == "") 
			continue;
		// check ooc
		if (this.codeFilter && this.codeFilter != peopleArray[i].ooc && peopleArray[i].hId != peopleArray[i].gId) 
			continue;
		// if hide guests with sched meeting
		if (this.host && this.hideAssigned && peopleArray[i].hId != peopleArray[i].gId && peopleArray[i].sched != "") 
			continue;
		// if hide meetings with completed/cancelled status 
		if ( peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].meetingId != Number(this.meetingId) ) 			
			continue;
        

		// add to map
		var html = "";
		var marker = null;
		
		
		var point = new GLatLng(peopleArray[i].lat, peopleArray[i].lng);
		 
		 if(peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].meetingId == Number(this.meetingId)){
						
		    html = this.buildInfoWinHostHtml(peopleArray[i], point); 
			var full = peopleArray[i].sched != "" && peopleArray[i].accomm <= peopleArray[i].numGuests;
			var completed = peopleArray[i].meetingstatus >=6 && peopleArray[i].meetingstatus <=8;
			marker = this.mc.addHostMarker(point, html, peopleArray[i].sched,completed, full);
			this.currentMtg = peopleArray[i];
			
		 }
		 else
		{
			// guests
			html = this.buildInfoWinGuestHtml(peopleArray[i],i);
			
			//build the print page

			if(j%2){
			 printGuestHtml +="<tr>";
			 printGuestHtml += this.buildInfoWinPrintGuestHtml(peopleArray[i],i,centerPoint);
            }
			else
            {
			  printGuestHtml += this.buildInfoWinPrintGuestHtml(peopleArray[i],i,centerPoint);
			  printGuestHtml +="</tr>";
			}
			j++;
			var assigned = peopleArray[i].sched != "";
			marker = this.mc.addGuestMarker(point, html, assigned);
		}
		peopleArray[i].marker = marker;
        
		// add to list
		if (!this.host) 
			listHtml += this.buildListItemHtml(peopleArray[i], i);
		else if (peopleArray[i].hId != peopleArray[i].gId) 
			guestHtml += this.buildHostGuestListHtml(peopleArray[i], i);
		else if (peopleArray[i].sched != "") {
			listHtml += this.buildHostMtgListHtml(peopleArray[i], i, false);
		}
	}
  
     printGuestHtml +="</table>";
	printGuestHtml = printGuestHtml.replace(/\'/g, "\\'");		
	
	// show list
	if (this.host) {
		listHtml += "</table></div>" + guestHtml + "</table></div>";
		
	}
	
	
	printLinkHtml = "<div class=\"click2print\"><a href=\"#\" onClick=\"printtext('"+printGuestHtml+"')\"><b>Print current map view</b></a></div>";		
	document.getElementById("foundContainer").innerHTML = listHtml;
	if(printGuestHtml.length > 1){
	 document.getElementById("printContainer").innerHTML = printLinkHtml;
	 document.getElementById("emailContainer").innerHTML = "<div style=\"width:145px;\" class=\"click2email\"><a href=\"#\" onClick=\"APP_CONTROLLER.doEmail()\"><b>Send Email Invitations</b></a></div>";
	}

	// if the old current meeting is still on the map, scroll to it
	if (foundCurrent != null) {
		// get the row element offset
		var listItemRow = document.getElementById("mtgRow" + foundCurrent);
		var mtgList = document.getElementById("foundMeetings");
		mtgList.scrollTop = listItemRow.offsetTop - mtgList.offsetTop;
		// fix already assigned guest checks
		this.refreshGuestList();
	}
	//else this.currentMtg = holdMeeting;
}


/*****************************################################################## Sep 11 2009 #########################***********************************************************/

AppController.prototype.printPoint = function(peopleArray) {
	
	
	// clear map and found list
	this.mc.clearMap();
	
	if (!peopleArray || peopleArray.length == 0) {
		this.setMessage("No Meetings Found");
		return;
	}
	// clear the selected meeting and assigned guests
	if (this.print) {
		this.assignedGuests = null;
	}	
	var centerPoint = new GLatLng(this.lat, this.lng);	
   
	peopleArray.sort(function(a,b)
		{
		adist = centerPoint.distanceFrom(new GLatLng(a.lat,a.lng));
		bdist = centerPoint.distanceFrom(new GLatLng(b.lat,b.lng));
		return adist - bdist});
	
	// for each person in the results, add marker to the map and an entry in list
	for (var i=0; i<peopleArray.length; i++) {
		 
		// do filtering...
		// make sure this is a host if not in admin
		if (!this.print ) 
			continue;
		// if only scheduled flag, don't want blank meeting dates
		if (this.onlySched && peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].sched == "") 
			continue;
		
		// check ooc
		if (this.codeFilter && this.codeFilter != peopleArray[i].ooc && peopleArray[i].hId != peopleArray[i].gId) 
			continue;
        // Hide already assigned Guests
		if (this.hideAssigned && peopleArray[i].hId != peopleArray[i].gId && peopleArray[i].sched != "") 
			continue;
		
		// if hide meetings with completed/cancelled status 
		if ( peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].meetingId != Number(this.meetingId) ) 			
			continue;
        

		// add to map
		var html = "";
		var marker = null;
		
		var point = new GLatLng(peopleArray[i].lat, peopleArray[i].lng);
		 
		 if(peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].meetingId == Number(this.meetingId)){
			//This meeting
			var full = peopleArray[i].sched != "" && peopleArray[i].accomm <= peopleArray[i].numGuests;		
			var completed = peopleArray[i].meetingstatus >=6 && peopleArray[i].meetingstatus <=8;
			marker = this.mc.addHostMarker(point, html, peopleArray[i].sched,completed, full);
		 }
		 else
		{
			// guests			
			var assigned = peopleArray[i].sched != "";
			marker = this.mc.addGuestMarker(point, html, assigned);
		}
		peopleArray[i].marker = marker;
        
		
   } 



}

/*************************************************************************************/








AppController.prototype.initialize = function(map_div, latitude, longitude, zoom)
{
	// set up the map
	this.mc.initialize(map_div, latitude, longitude, zoom);

	// reset all fields in search -- how do I reset dates?
	try{
	document.getElementById("zipCode").value = "";
	document.getElementById("radius").selectedIndex = 0;
	document.getElementById("location_confirmed").checked = true;
	document.getElementById("hideBooked").checked = false;
	document.getElementById("orgID").value = "";
	}catch(e)
	{
	}
	// set filter flags to default values
	this.onlySched = true;
	this.hideBooked = false;
	this.hideAssigned = (this.admin ? true : null);
	this.codeFilter = null;
	// for some reason these don't get reset
	try{
	document.getElementById("startdate_Year_ID").disabled = false;
	document.getElementById("enddate_Year_ID").disabled = false;
	}catch(e)
	{
	}
	// initialize admin fields
	if (this.admin) {
		document.getElementById("hideAssigned").checked = true;
		this.currentMtg = null;
		this.assignedGuests = 0;
	}
}
// doFindMeeting function is called when the search form is submitted
AppController.prototype.doFindMeeting = function(meetingIdReq) {
	if (this.requestInProgress) return;
	// clean up old results--remove marker objects
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].marker) delete this.results[i].marker;
	}
	if (meetingIdReq != null && meetingIdReq != "") {
	APP_CONTROLLER.requestInProgress = true;
	APP_CONTROLLER.setMessage("Searching...");
	
	this.rssMeetingId = Number(meetingIdReq); // RSS center on meeting requirement!!
	
	APP_CONTROLLER.ws.findMeeting(meetingIdReq);
	}
	
}
// doFind function is called when the search form is submitted
AppController.prototype.doFind = function(fm) {
	if (this.requestInProgress) return;

	// clean up old results--remove marker objects
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].marker) delete this.results[i].marker;
	}
	// get form values for search
	if (!fm) fm = document.getElementById("selectMeeting");
	var zip = fm.zipCode.value;
	var sel = fm.radius.selectedIndex;
	var radius = fm.radius.options[sel].value;
	this.onlySched = fm.locations[0].checked;
	// get date
	var startDate = fm.startdate.value;
	var endDate = fm.enddate.value;

	if (zip != "" && radius != "999") {
		this.mc.geocoder.getLocations(zip, function(result) {
				if (result.Status.code == G_GEO_SUCCESS) {
					var point = result.Placemark[0].Point.coordinates;
					APP_CONTROLLER.mc.centreOnAddress(point[1], point[0], radius);

					//store lat lng rad to draw the circle
					APP_CONTROLLER.lat = point[1];
					APP_CONTROLLER.lng = point[0];
					APP_CONTROLLER.radius = radius;		
					APP_CONTROLLER.zip = zip;
					// do search
					APP_CONTROLLER.requestInProgress = true;
					APP_CONTROLLER.setMessage("Searching...");
					APP_CONTROLLER.ws.searchLocations(startDate, endDate, point[1], point[0], radius, APP_CONTROLLER.admin, APP_CONTROLLER.onlySched);
//					this.searchLocations("OK", TESTDATA);	
				}
				else {
					// an error has occurred -- give a better message
					alert ("Geocoding error: " + MapController.getGeocodeErrorMsg(result.Status.code));
				}
			});
	}
	else { 
		// do search from current center
		if (radius != "999") alert ("No address provided, using current center point of map to locate meetings");
		
		//dont draw a circle
		this.radius = 0;	
		this.mc.centreOnAddress(null, null, radius);
		var point = this.mc.map.getCenter();
		this.requestInProgress = true;
		this.setMessage("Searching...");
		this.ws.searchLocations(startDate, endDate, point.lat(), point.lng(), radius, this.admin, this.onlySched);
//		this.searchLocations("OK", TESTDATA);	
	}
}

AppController.prototype.doSearch = function(searchParams) {
	if (this.requestInProgress) return;

	// clean up old results--remove marker objects
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].marker) delete this.results[i].marker;
	}
	// get form values for search
	var zip = searchParams['zip'];
	var radius = searchParams['radius'];;
//	this.onlySched = false; // check out later
	// get date
	var startDate = searchParams['startDate'];
	var endDate =  searchParams['endDate'];
	
//	alert (zip);
	if (zip != "" && radius != "999") {
		this.mc.geocoder.getLocations(zip, function(result) {
				if (result.Status.code == G_GEO_SUCCESS) {
					var point = result.Placemark[0].Point.coordinates;
					APP_CONTROLLER.mc.centreOnAddress(point[1], point[0], radius);

					//store lat lng rad to draw the circle
					APP_CONTROLLER.lat = point[1];
					APP_CONTROLLER.lng = point[0];
					APP_CONTROLLER.radius = radius;		
					APP_CONTROLLER.zip = zip;
					// do search
					APP_CONTROLLER.requestInProgress = true;
				//	APP_CONTROLLER.setMessage("Searching...");
					APP_CONTROLLER.ws.searchLocations(startDate, endDate, point[1], point[0], radius, APP_CONTROLLER.admin, APP_CONTROLLER.onlySched);
//					this.searchLocations("OK", TESTDATA);
				}
				else {
					// an error has occurred -- give a better message
					alert ("Geocoding error: " + MapController.getGeocodeErrorMsg(result.Status.code));
				}
			});
	}
	else { 
		// do search from current center
		if (radius != "999") alert ("No address provided, using current center point of map to locate meetings");
		
		//dont draw a circle
		this.radius = 0;	
		this.mc.centreOnAddress(null, null, radius);
		var point = this.mc.map.getCenter();
		this.requestInProgress = true;
		//this.setMessage("Searching...");
		this.ws.searchLocations(startDate, endDate, point.lat(), point.lng(), radius, this.admin, this.onlySched);
//		this.searchLocations("OK", TESTDATA);	
	}
	this.embedURLZoomLevel = searchParams['zoom'];
	this.embedURLCenterlat = searchParams['lat'];
	this.embedURLCenterlng = searchParams['lng'];
	
}


// searchLocations is the callback from web-service function of same name
AppController.prototype.searchLocations = function(message, points) {
	this.requestInProgress = false;
	// check message?
	if (message != "OK") {
		alert ("Search failed! Web Service returned error message: " + message);
		return;
	}
	// save current results
	this.results = points;
	// display the results
	if(!this.host && !this.print){
	 this.show(points);
	}
	else if(this.host)
	{
	this.showHost(points);
	}
	else
	this.printPoint(points);
	
	//draw circle
	 if(!this.host && !this.print)
	  APP_CONTROLLER.mc.drawAddressCircle(this.lat,this.lng, this.radius,this.zip);
	 else
	 APP_CONTROLLER.mc.drawAddressCircle(this.lat,this.lng, this.radius,'');
	  this.lat = 0;
	  this.lng = 0;
	  this.radius = 0;
	
	// embed URL and rss
	
	
	if(this.embedURLZoomLevel > 0)
	  {
	  	var zoomParam = parseInt(this.embedURLZoomLevel);
	  	APP_CONTROLLER.mc.map.setCenter(new GLatLng(this.embedURLCenterlat, this.embedURLCenterlng));
	  	APP_CONTROLLER.mc.map.setZoom(zoomParam);
	  	this.embedURLZoomLevel = 0;
	  }
	  if(this.rssMeetingId != 0)
	  {
	  	var point = new GLatLng(points[0].lat, points[0].lng);
	  	this.mc.map.setCenter(point, 17); // 17 is initial requirement. 
	  	this.rssMeetingId = 0;
	  }
}
// Admin functions:
// selectMeeting is called when the user clicks on a meeting radio button (admin only)
AppController.prototype.selectMeeting = function(mtgID) {
	// check if this is the same current meeting
	if (this.currentMtg != null && this.currentMtg.ccf_id == this.results[mtgID].ccf_id) return;
	this.currentMtg = this.results[mtgID];
	// remove any old checked guests and check the guests already assigned to the new meeting
	this.refreshGuestList();
	// initialize assigned guests
	this.assignedGuests = 0;
}

AppController.prototype.refreshGuestList = function() {
	if (!this.currentMtg) return;
	for (var i=0; i<this.results.length; i++) {
		var checkbox = document.getElementById("guest_" + this.results[i].ccf_id);
		if (!checkbox) continue;
		if (checkbox.checked) checkbox.checked = false;
		if (checkbox.disabled) checkbox.disabled = false;
		if (!this.hideAssigned && this.currentMtg.numGuests > 0 && !this.results[i].host && this.results[i].hgc == this.currentMtg.hgc && this.results[i].sched == this.currentMtg.sched) {
		// in words: if showing assigned guests and there are some assigned to this meeting and the current record is not a host and the host group code and scheduled time match those of the currently selected meeting then we have a match!
			checkbox.checked = true;
			checkbox.disabled = true;
		}
	}
}

// assignGuest is called when the user clicks on a guest checkbox (admin only)
AppController.prototype.assignGuest = function(index, checkbox) {
	if (this.currentMtg == null) {
		alert ("Sorry, you must select a meeting before you can assign guests");
		checkbox.checked = false;
		return;
	}
	this.mc.updateGuestMarker(this.results[index].marker, checkbox.checked);

	// set fields in guest record here or later? -- I think later, push to array for now
	if (checkbox.checked) this.assignedGuests++;
	else this.assignedGuests--;
}
// assignGuest is called when the user clicks on a guest checkbox (admin only)
AppController.prototype.assignGuestEmail = function(index, checkbox) {
	
	// set fields in guest record here or later? -- I think later, push to array for now
	if (checkbox.checked) this.assignedGuests++;
	else this.assignedGuests--;
}
// checkGuest is called when the 'assign' button on a guest's info window is clicked (admin only)
AppController.prototype.checkGuest = function(index) {
	// find the checkbox for this guest
	var checkbox = document.getElementById("guest_" + this.results[index].ccf_id);
	checkbox.checked = true;
	this.assignGuest(index, checkbox);
}
// doAssign is called when the 'assign Guests' button is pressed to save the assigned guests to the database (admin only)
AppController.prototype.doEmail = function() {
	if (this.requestInProgress) return;
	if (this.currentMtg == null || this.assignedGuests == 0) {
		alert ("Cannot Email Guests: either no meeting is selected or no guests are selected for the meeting");
		return;
	}
	
	// set the host fields in the guest records for info window use
	this.guestArray = [];
	var count = 0;
	
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].host) continue;
		var checkbox = document.getElementById("guest_" + this.results[i].ccf_id);
		if (!checkbox || checkbox.disabled || !checkbox.checked) continue;
		this.results[i].assignedPhone = this.currentMtg.phone;
		this.results[i].assignedName = this.currentMtg.first + " " + this.currentMtg.last;
		this.results[i].hgc = this.currentMtg.hgc;
		this.results[i].sched = this.currentMtg.sched;
		// save the guest list so we can report errors just in case
		this.guestArray.push({id:this.results[i].gId});
			
		count++
	}
	if (count != this.assignedGuests){
		// this is more for debugging purposes--shouldn't happen
		//alert ("Found " + count + " guests checked, but expecting " + this.assignedGuests);
		//this.assignedGuests = count;
	}
	

	// update database with meeting and guest records
	this.requestInProgress = true;
	this.ws.email(this.currentMtg.meetingId, this.guestArray);
}
// doAssign is called when the 'assign Guests' button is pressed to save the assigned guests to the database (admin only)
AppController.prototype.doAssign = function() {
	if (this.requestInProgress) return;
	if (this.currentMtg == null || this.assignedGuests == 0) {
		alert ("Cannot Assign Guests: either no meeting is selected or no guests are selected for the meeting");
		return;
	}
	
	// set the host fields in the guest records for info window use
	this.guestArray = [];
	var count = 0;
	
	for (var i=0; i<this.results.length; i++) {
		if (this.results[i].host) continue;
		var checkbox = document.getElementById("guest_" + this.results[i].ccf_id);
		if (!checkbox || checkbox.disabled || !checkbox.checked) continue;
		this.results[i].assignedPhone = this.currentMtg.phone;
		this.results[i].assignedName = this.currentMtg.first + " " + this.currentMtg.last;
		this.results[i].hgc = this.currentMtg.hgc;
		this.results[i].sched = this.currentMtg.sched;
		// save the guest list so we can report errors just in case
		this.guestArray.push({id:this.results[i].gId,email:this.results[i].email,first:this.results[i].first,last:this.results[i].last,
			ccfid:this.results[i].ccf_id,snailm:this.results[i].snailmail,phone:this.results[i].phone,alPhone:this.results[i].alPhone,
			gAdd:this.results[i].gAddr,gUnit:this.results[i].gUnit,gCity:this.results[i].gCity,gState:this.results[i].gState,gZip:this.results[i].gPostCode});
			
		count++
	}
	if (count != this.assignedGuests){
		// this is more for debugging purposes--shouldn't happen
		alert ("Found " + count + " guests checked, but expecting " + this.assignedGuests);
		this.assignedGuests = count;
	}
	if(this.currentMtg.accomm - this.currentMtg.numGuests == 0){
	   alert("This meeting is full, you can't assign any more guests to this meeting!");
	   return;
	}
	if(this.assignedGuests > (this.currentMtg.accomm - this.currentMtg.numGuests)){
		alert("This meeting only has "+(this.currentMtg.accomm - this.currentMtg.numGuests)+" capacity,\n you are assigning "+this.assignedGuests+" guests, please adjust to the right number!");
		return;
	}
	this.currentMtg.numGuests += count;

	// update database with meeting and guest records
	this.requestInProgress = true;
	this.ws.update(this.currentMtg.meetingId, this.guestArray);
}
// update is the callback from the web-service function of the same name
AppController.prototype.update = function(message, response) {
	this.requestInProgress = false;
	// check message?
	if (message != "OK") {
		alert ("Update failed! Web Service returned error message: " + message);
		return;
	}
	if (this.assignedGuests != response.length) {
		alert ("Response from Web Service does not match request, some guest assignments may not be recorded in the database.  Please check your changes.");
	}
	var errors = [];
	for (var i=0; i<response.length; i++) {
		if (response[i] != "OK") {
			errors.push(this.guestArray[i]);
		}
	}
	if (errors.length > 0) {
		var msg = "Meeting assignment failed for the following guests:\n";
		for (i=0; i<errors.length; i++) {
			msg += error[i].first + " " + error[i].last + "\n";
		}
	}
	this.assignedGuests = 0;
	this.guestArray = null;
	// don't de-select currentMtg...
	//this.currentMtg = null;
	// redraw the map and list
	this.show(this.results);
}

// Join Meeting is the callback from the web-service function of the same name
AppController.prototype.joinMeeting = function(message, response) {
	this.requestInProgress = false;
	// check message?
	if (message != "OK") {	
		if(message == "CHANGE"){
		   //	Parse response
          message = response[1];	
		  uId = response[2];
		  mId = response[3];
		  if( confirm (message)){
            APP_CONTROLLER.ws.changeProfile(uId,mId);
		  }
		  else		
		 return;
		}
		else
		if(message == "SWITCHM"){
		   //	Parse response
          message = response[1];	
		  uId = response[2];
		  mId = response[3];
		  if( confirm (message)){
            APP_CONTROLLER.ws.switchM(uId,mId);
		  }
		  else		
		 return;
		}
		else
		{
	     //	Parse response
	    message = response[1];		
		
		alert (message);
		
		return;
		}
	}
	
	else if (message == "OK") {	
	     //	Parse response
		
	    message = response[0];		
		alert (message);
		return;
	}
	
}

// EmailResponse is the callback from the web-service function of email
AppController.prototype.emailResponse = function(message, response) {
	this.requestInProgress = false;
	// check message?
	if (message != "OK") {	
		
	     //	Parse response
	    message = response[1];		
		
		alert (message);
		
		return;
		
	}
	
	else if (message == "OK") {	
	     //	Parse response
		
	    message = response[0];		
		alert (message);
		return;
	}
	
}
// Change profile is the callback from the web-service function of the same name
AppController.prototype.changeProfile = function(message, response) {
	this.requestInProgress = false;
	// check message?
	if (message != "OK") {	
		
	     //	Parse response
	    message = response[1];		
		
		alert (message);
		
		return;
		
	}
	
	else if (message == "OK") {	
	     //	Parse response
		
	    message = response[0];		
		alert (message);
		return;
	}
	
}
// showCodeWindow is called when the user clicks on the link to open an iframe with a code list
AppController.prototype.showCodeWindow = function(e) {
	if (!e) e = event;
	this.setElemPosition(e, "codeWin");
	var codeWin = document.getElementById("codeWin");
	var html = '<div id="codeWinHeader"><a href="#" onclick="APP_CONTROLLER.hideCodeWindow();return false;">Close Window</a></div><iframe src="';
	if (this.admin) html += '../';
	html += 'MAP Org Codes.html" scrolling="auto" width="100%" height="332" frameborder="0"></iframe>';
	codeWin.innerHTML = html;
	codeWin.style.visibility = "visible"
}
// hideCodeWindow is called when the close link is clicked on the code window
AppController.prototype.hideCodeWindow = function() {
	var codeWin = document.getElementById("codeWin");
	codeWin.innerHTML = "";
	codeWin.style.visibility = "hidden"
}
// selectMarker is called to open a marker's info window when the associated list item is clicked
AppController.prototype.selectMarker = function(index) {
	this.mc.selectMarker(this.results[index].marker);
}
// setLocations is called to hide or show the date range selections depending on the locations radio buttons
AppController.prototype.setLocations = function(flag) {
	this.onlySched = !flag;
//	if (this.results) this.show(this.results);

	document.getElementById("startdate_Month_ID").disabled = flag;
	document.getElementById("startdate_Day_ID").disabled = flag;
	document.getElementById("startdate_Year_ID").disabled = flag;
	document.getElementById("startdate_ID_Link").onclick = (flag ? "return false;" : "");
	document.getElementById("enddate_Month_ID").disabled = flag;
	document.getElementById("enddate_Day_ID").disabled = flag;
	document.getElementById("enddate_Year_ID").disabled = flag;
	document.getElementById("enddate_ID_Link").onclick = (flag ? "return false;" : "");
	document.getElementById("dateInput").className = (flag ? "greyout" : "regular");
}
// toggleHideBooked is called to set flag and update list when 'hide booked' is checked/unchecked
AppController.prototype.toggleHideBooked = function() {
	this.hideBooked = !this.hideBooked;
	if (this.results.length > 0) this.show(this.results);
}
// toggleHideAssigned is called to set flag and update list when 'hide assigned' is checked/unchecked
AppController.prototype.toggleHideAssigned = function() {
	this.hideAssigned = !this.hideAssigned;
	if (this.results.length > 0) this.show(this.results);
}
// setOOC is called when a value is enterred in the OOC field -- Note: this is not working right now!
AppController.prototype.setOOC = function(ooc) {
	if (ooc == null || ooc == "") return;
	this.codeFilter = this.validateOOC(ooc);
	if (this.results.length > 0) 
	 if(!this.host){
	  this.show(this.results);
	  }
	else
	  {
	  this.showHost(this.results);
	 }	
	
}

// PRIVATE METHODS

AppController.prototype.validateOOC = function(ooc) {
	if (ooc == null || ooc == "") return null;
	var val = Number(ooc);
	if (ooc.length > 3 || isNaN(val)) {
		alert ("You have entered an invalid Organization Code.  Please see the Code List for assistance.");
		return null;
	}
	return val;
}

AppController.prototype.show = function(peopleArray) {
	// clear map and found list
	this.mc.clearMap();
	if (!peopleArray || peopleArray.length == 0) {
		this.setMessage("No Meetings Found");
		return;
	}
	// clear the selected meeting and assigned guests
	if (this.admin) {
//		this.currentMtg = null;
		this.assignedGuests = null;
	}
	document.getElementById("foundContainer").innerHTML = "";
	// initialize holders for list html
	var listHtml = "";
	var guestHtml = "";
	// set up the admin list headers
	if (this.admin) {
		listHtml += '<div id="foundMeetings"><table><tr><td width=260 colspan=2><b>Meetings</b></td><td><b>Date and Time</b></td></tr>';
		guestHtml = '<div id="foundGuests"><table><tr><td width=260 colspan=2><b>Guests</b></td><td><b>Date and Time</b></td></tr>';
	}
	else {
		listHtml = "<table><tr><td><b>Meetings</b></td><td><b>Date and Time</b></td></tr>";
	}
	// get ooc filter here since the onchange function isn't working
	this.codeFilter = this.validateOOC(document.getElementById("orgID").value);

	// this is for finding the currentMtg in the new results (admin only)
	var foundCurrent = null;

	// for each person in the results, add marker to the map and an entry in list
	for (var i=0; i<peopleArray.length; i++) {
		// do filtering...
		// make sure this is a host if not in admin
		if (!this.admin && peopleArray[i].hId != peopleArray[i].gId) 
			continue;
		// if only scheduled flag, don't want blank meeting dates
		if (this.onlySched && peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].sched == "") 
			continue;
		// if hide fully booked meetings don't want host with a full meeting
		if (this.hideBooked && peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].sched != "" && peopleArray[i].numGuests >= peopleArray[i].accomm) 
			continue;
		// check ooc
		if (this.codeFilter && this.codeFilter != peopleArray[i].ooc) 
			continue;
		// if hide guests with sched meeting
		if (this.admin && this.hideAssigned && peopleArray[i].hId != peopleArray[i].gId && peopleArray[i].sched != "") 
			continue;
		// if hide meetings with completed/cancelled status 
		if (!this.admin && peopleArray[i].hId == peopleArray[i].gId && peopleArray[i].meetingstatus >= 9) 
			continue;


		// add to map
		var html = "";
		var marker = null;
		var point = new GLatLng(peopleArray[i].lat, peopleArray[i].lng);
		if (peopleArray[i].hId == peopleArray[i].gId ) {
			html = this.buildInfoWinHostHtml(peopleArray[i],point);
			// if meeting is full, make it red
			var full = peopleArray[i].sched != "" && peopleArray[i].accomm <= peopleArray[i].numGuests;
			
			var completed = peopleArray[i].meetingstatus >=6 && peopleArray[i].meetingstatus <=8;
			marker = this.mc.addHostMarker(point, html, peopleArray[i].sched,completed, full);
		}
		else {	// guests
			html = this.buildInfoWinGuestHtml(peopleArray[i],i);
			var assigned = peopleArray[i].sched != "";
			marker = this.mc.addGuestMarker(point, html, assigned);
		}
		peopleArray[i].marker = marker;

		// add to list
		if (!this.admin) 
			listHtml += this.buildListItemHtml(peopleArray[i], i);
		else if (peopleArray[i].hId != peopleArray[i].gId) 
			guestHtml += this.buildAdminGuestListHtml(peopleArray[i], i);
		else if (peopleArray[i].sched != "") {
			// check if currentMtg is in the new list
			if (foundCurrent == null && this.currentMtg != null && this.currentMtg.ccf_id == peopleArray[i].ccf_id) {
					foundCurrent = i;
			}
			listHtml += this.buildAdminMtgListHtml(peopleArray[i], i, (foundCurrent == i));
		}
	}
	// show list
	if (this.admin) {
//		listHtml += guestHtml + "</table></div>";
		listHtml += "</table></div>" + guestHtml + "</table></div>";
	}
	else
		listHtml += "</table>";
	document.getElementById("foundContainer").innerHTML = listHtml;

	// if the old current meeting is still on the map, scroll to it
	if (foundCurrent != null) {
		// get the row element offset
		var listItemRow = document.getElementById("mtgRow" + foundCurrent);
		var mtgList = document.getElementById("foundMeetings");
		mtgList.scrollTop = listItemRow.offsetTop - mtgList.offsetTop;
		// fix already assigned guest checks
		this.refreshGuestList();
	}
	else this.currentMtg = null;
}

AppController.prototype.buildInfoWinHostHtml = function(person, point) {
	
	var html = "<div height='280px' style='text-align:left;'>";
	html += "<b>" + person.subject + "</b><br />";
	if(this.signedIn){
	if (person.sched != "") {
		html += "<b>" + person.sched + "</b>";
		html += "<br />" + person.hAddr + " " + person.hUnit;
	}
	else {
		html += "<b>" + person.hAddr + " " + person.hUnit + "</b>";
		
	}
	html += "<br />" + person.hCity + ", " + person.hState + " " + person.hPostCode + "";
	if(person.note){
	      html += "<br /><br /><b>Message from the host</b>:<br/ ><div style=\"width:250px;height:65px;overflow-x:auto;overflow-y:auto;background-color:#FFFFCC;\">" + person.note+"</div>";
	    }
	if (person.accomm > 0 && person.numGuests >= person.accomm) {
		html += "<br /><br /><span class='red'>FULLY BOOKED</span>";
	}

	html += "<br /><br />Host Group Code: " + person.hgc;
	html += "<br /><br />First Name: " + person.first;
	html += "<br />Last Name: " + person.last;
	html += "<br />Contact Phone: " + person.phone;
	//html += "<br />Willing to host: " + (person.host ? "Yes" : "No");
	html += "<br />Host can accommodate: " + person.accomm;
	html += "<br />Number of guests already assigned: " + person.numGuests;
	html += "<br />Optional Organization Code: " + person.ooc;
	html += "<br />Meeting Status: " + person.sText;
	
	var prop ="none";
	if (!this.host &&!this.admin && person.accomm > 0 && person.numGuests < person.accomm && person.meetingstatus==3) {
		html += "<br /><br /><center><button onclick='APP_CONTROLLER.ws.joinMeeting("+this.userId+","+person.meetingId+",this.style);'>Join this Meeting</button></center>";
	}
	if (!this.admin && !this.host)

		 
	     html += "<br /><br />Get directions: <a href='http://maps.google.com/maps?saddr="+document.getElementById("zipCode").value+"&daddr=" + person.hAddr +','+person.hCity+','+person.hState + "' target ='_blank'>To here</a> - <a href='http://maps.google.com/maps?saddr=" + person.hAddr +','+person.hCity+','+person.hState + "&daddr="+document.getElementById("zipCode").value+"' target ='_blank'>From here</a>";
		//html += "<br /><br />Get directions: <a href='http://maps.google.com/maps?saddr=&daddr=" + point.toUrlValue() + "' target ='_blank'>To here</a> - <a href='http://maps.google.com/maps?saddr=" + point.toUrlValue() + "&daddr=' target ='_blank'>From here</a>";
	   
	if (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.indexOf("Mac") != -1) {
		html += "<br /> <br /> <br /> <br />";
	}
	
	}
	else if(!this.signedIn)
	{
	 if (person.sched != "") {
		html += "<b>" + person.sched + "</b>";
		html += "<br />" + person.hAddr + " " + person.hUnit;
	}
	else {
		html += "<b>" + person.hAddr + " " + person.hUnit + "</b>";
	}
	html += "<br />" + person.hCity + ", " + person.hState + " " + person.hPostCode + "";
	if(person.note){
	      html += "<br /><br /><b>Message from the host</b>:<br/ ><div style=\"width:250px;height:65px;overflow-x:auto;overflow-y:auto;background-color:#FFFFCC;\">" + person.note+"</div>";
	    }
	if (person.accomm > 0 && person.numGuests >= person.accomm) {
		html += "<br /><br /><span class='red'>FULLY BOOKED</span>";
	}	
	html += "<br />Host can accommodate: " + person.accomm;
	html += "<br />Number of guests already assigned: " + person.numGuests;
	html += "<br />Optional Organization Code: " + person.ooc;
	html += "<br />Meeting Status: " + person.sText;
	//confirmmsg = "Are you sure you want to attend this meeting?";
	if (person.accomm > 0 && person.numGuests < person.accomm && person.meetingstatus==3) {
	//	html += "<br /><br /><center>Click <a href="+signInURL+"?meetingId="+person.meetingId+">here</a> to Sign up/Sign in and join this meeting!</center>";
		html += "<br /><br /><center>Click <a href=/c/portal/login?meetingId="+person.meetingId+" target='_blank'>here</a> to Sign up/Sign in and join this meeting!</center>";
	
	}
	if (!this.admin)
		
	    html += "<br /><br />Get directions: <a href='http://maps.google.com/maps?saddr="+document.getElementById("zipCode").value+"&daddr=" + person.hAddr +','+person.hCity+','+person.hState + "' target ='_blank'>To here</a> - <a href='http://maps.google.com/maps?saddr=" + person.hAddr +','+person.hCity+','+person.hState + "&daddr="+document.getElementById("zipCode").value+"' target ='_blank'>From here</a>";

		//html += "<br /><br />Get directions: <a href='http://maps.google.com/maps?saddr=&daddr=" + point.toUrlValue() + "' target ='_blank'>To here</a> - <a href='http://maps.google.com/maps?saddr=" + point.toUrlValue() + "&daddr=' target ='_blank'>From here</a>";
	if (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.indexOf("Mac") != -1) {
		html += "<br /> <br /> <br /> <br />";
	}

	}
	html += "</div>";
	return html;

}

AppController.prototype.buildInfoWinGuestHtml = function(person, index) {
	// TODO make sure to use guest hAddr info
	var html = "<b>" + person.subject + "</b>";
	html += "<br /><b>" + person.gAddr + " " + person.gUnit + "</b>";
	html += "<br />" + person.gCity + ", " + person.gState + " " + person.gPostCode + "";
	html += "<br /><br />First Name: " + person.first;
	html += "<br />Last Name: " + person.last;
	html += "<br />Contact Phone: " + person.phone;
	html += "<br />Willing to assist: " + (person.assist ? "Yes" : "No");
	html += "<br />Optional Organization Code: " + person.ooc;
	html += "<br />User ID: " + person.email;
	html += "<br />CCF-ID: " + person.ccf_id;
	if (person.sched != "") {
		html += "<br /><br />Assigned Host Group Code: " + person.hgc;
		html += "<br /><span class='nowrap'>Assigned Host Contact Name: " + person.assignedName + "</span>";
		html += "<br /><span class='nowrap'>Assigned Host Contact Phone: " + person.assignedPhone + "</span>";
		html += "<br /><span class='nowrap'>Meeting Scheduled Date: " + person.sched + "</span>";
	}
	
	else if(!this.host){
		html += "<br /><center><button onclick='APP_CONTROLLER.checkGuest(" + index + ");'>Assign to current Meeting</button></center>";
	}
	if (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.indexOf("Mac") != -1) {
		html += "<br /> <br /> <br />";
	}
	return html;
}
AppController.prototype.buildInfoWinPrintGuestHtml = function(person, index, centerPoint) {
	// TODO make sure to use guest hAddr info
	
	//calculate the distance from the meeting and print it
	var distance = centerPoint.distanceFrom(new GLatLng(person.lat,person.lng));
	var distanceMiles = distance / 1609.344;

	var html = "<td width=50%>";
	html += "<br /><b>Name: " + person.first +" "+ person.last+ " ( " + distanceMiles.toFixed(2) + " mi)</b>";
	html += "<br />Address: " + person.gAddr + " " + person.gUnit + "";
	html += "<br />" + person.gCity + ", " + person.gState + " " + person.gPostCode + "";	
	html += "<br />Contact Phone: " + person.phone;
	html += "<br />Willing to assist: " + (person.assist ? "Yes" : "No");
	html += "<br />Optional Organization Code: " + person.ooc;
	html += "<br />User ID: " + person.email;
	html += "<br />CCF-ID: " + person.ccf_id;
	html += "</td>";
	if (navigator.appName.indexOf("Netscape") != -1 && navigator.appVersion.indexOf("Mac") != -1) {
		html += "";
	}
	return html;
}
AppController.prototype.buildListItemHtml = function(person, i) {
	var addrStr = person.hAddr + " " + person.hUnit + ", " + person.hCity + ", " + person.hState + " " + person.hPostCode;
	var html = "<tr><td width=260><div class='foundListItem'><a href='#' class='listItem' id='listItem" + i + "' onmouseover='tooltip(\"" + addrStr + "\");' onmouseout='exit();' onclick='APP_CONTROLLER.selectMarker(" + i + ");return false;'>" + addrStr + "</a></div></td>";
	var dateStr = (person.sched != "" ? person.sched : "unconfirmed");
	html += "<td width=100><div class='dateListItem' onmouseover='tooltip(\"" + dateStr + "\");' onmouseout='exit();'>" + dateStr + "</div></td></tr>";
	return html;
}

AppController.prototype.buildAdminMtgListHtml = function(person, i, check) {
	var addrStr = person.hAddr + " " + person.hUnit + ", " + person.hCity + ", " + person.hState + " " + person.hPostCode;
	var html = "<tr id='mtgRow" + i + "'><td><input type='radio' id='mtg_" + person.ccf_id + "' onclick='APP_CONTROLLER.selectMeeting(this.value);' name='meetings' value='" + i + "' " + (check ? "CHECKED" : "") + " /></td>";
	html += "<td width=230><div class='adminListItem'><a href='#' style='color:" + (person.numGuests <= 1 ? "green" : "black") + "' id='mtgListItem" + i + "' onmouseover='tooltip(\"" + addrStr + "\");this.style.color=\"blue\";' onmouseout='exit();this.style.color=\"" + (person.numGuests <= 1 ? "green" : "black") + "\";' onclick='APP_CONTROLLER.selectMarker(" + i + ");document.getElementById(\"mtg_" + person.ccf_id + "\").checked=true;APP_CONTROLLER.selectMeeting(" + i + ");return false;'>" + addrStr + "</a></div></td>";
	html += "<td width=100><div class='dateListItem' onmouseover='tooltip(\"" + person.sched + "\");' onmouseout='exit();'>" + person.sched + "</div></td></tr>"; 
	return html;
}
AppController.prototype.buildHostMtgListHtml = function(person, i, check) {
	var addrStr = person.hAddr + " " + person.hUnit + ", " + person.hCity + ", " + person.hState + " " + person.hPostCode;
	var html = "<tr><td width=230><div class='adminListItem'><a href='#' style='color:" + (person.numGuests <= 1 ? "green" : "black") + "' id='mtgListItem" + i + "' onmouseover='tooltip(\"" + addrStr + "\");this.style.color=\"blue\";' onmouseout='exit();this.style.color=\"" + (person.numGuests <= 1 ? "green" : "black") + "\";' onclick='APP_CONTROLLER.selectMarker(" + i + ");APP_CONTROLLER.selectMeeting(" + i + ");return false;'>" + addrStr + "</a></div></td>";
	html += "<td colspan=2 width=100><div class='dateListItem' onmouseover='tooltip(\"" + person.sched + "\");' onmouseout='exit();'>" + person.sched + "</div></td></tr>"; 
	return html;
}
AppController.prototype.buildAdminGuestListHtml = function(person, i) {
	var addrStr = person.gAddr + " " + person.gUnit + ", " + person.gCity + ", " + person.gState + " " + person.gPostCode;
	var html = "<tr><td><input type='checkbox' onclick='APP_CONTROLLER.assignGuest(" + i + ", this);' id='guest_" + person.ccf_id + "' name='" + person.ccf_id + "' value='" + person.ccf_id + "' /></td><td width=230><div class='adminListItem'><a href='#' class='listItem' id='guestListItem" + i + "' onmouseover='tooltip(\"" + addrStr + "\");' onmouseout='exit();' onclick='APP_CONTROLLER.selectMarker(" + i + ");return false;' style='margin-bottom:5px;'>" + addrStr + "</a></div></td>";
	var dateStr = (person.sched != "" ? person.sched : "unconfirmed");
	html += "<td width=100><div class='dateListItem' onmouseover='tooltip(\"" + dateStr + "\");' onmouseout='exit();'>" + dateStr + "</div></td></tr>";
	return html;
}
AppController.prototype.buildHostGuestListHtml = function(person, i) {
	var name = "&nbsp;"+person.first+ " " +person.last;
	var addrStr = person.gAddr + " " + person.gUnit + ", " + person.gCity + ", " + person.gState + " " + person.gPostCode;
	
	 var checkboxDisabled = "";
        if(person.email.indexOf("@")>0){ 
                checkboxDisabled="";            
        }else{
                checkboxDisabled=" style='display:none' ";
        }
	
	
	var html = "<tr><td ><input type='checkbox' " + checkboxDisabled + " onclick='APP_CONTROLLER.assignGuestEmail(" + i + ", this);' id='guest_" + person.ccf_id + "' name='guest_id' value='" + person.email + "' /></td><td width=330><div ><a href='#' class='listItem' id='guestListItem" + i + "' onmouseover='tooltip(\"" + name + "\");' onmouseout='exit();' onclick='APP_CONTROLLER.selectMarker(" + i + ");return false;' >" + name + "</a></div></td>";
	html += "<td width=100><div class='phoneListItem' onmouseover='tooltip(\"" + person.phone + "\");' onmouseout='exit();'>" + person.phone + "</div></td></tr>";
	html += "<tr style=\"border-bottom: 1px solid black\"><td colspan=3 width=430><div style=\"margin-left:30px;\"><a href='#' class='listItem' onmouseover='tooltip(\"" + addrStr + "\");' onmouseout='exit();' onclick='APP_CONTROLLER.selectMarker(" + i + ");return false;' >" + addrStr + "</a></div></td></tr>";
	return html;
}
AppController.prototype.setMessage = function(message) {
	document.getElementById("foundContainer").innerHTML = '<div style="margin:2px 4px;font-weight:bold;">' + message + '</div>';
}

// I grabbed this from the tooltip code for use with the code window
AppController.prototype.setElemPosition = function(e, elementId)
{
	var ie5 = (document.getElementById && document.all); 
	var ns6 = (document.getElementById && !document.all); 
	var ua = navigator.userAgent.toLowerCase();
	var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
        var iebody=(document.compatMode && 
        	document.compatMode != 'BackCompat') ? 
        		document.documentElement : document.body;
        pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
        pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
        mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
        mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;

        var elem = document.getElementById(elementId);
        elem.style.left = (mousex+pagex+200) + 'px';
        elem.style.top = (mousey+pagey-70) + 'px';
}