// -----------------------------------------------------------------------------
// gisuser.js v1.2a
//
// Manages a G.I.S. Web User
// (requires /js/jquery/jquery.js, /js/jquery/jqalert/jqalert.js)
//
// Author: 	Jim Faulkner   jim.faulkner@bocc.citrus.fl.us
//
// Copyright (c) 2007-2008 Citrus County Board of County Commissioners
// -----------------------------------------------------------------------------
var webUser = new WebUser();

function WebUser() {
	var wu            = this;
	var emailAddress  = '';
	var password      = '';
	var accountID     = -1;
	var userInfoBarID = null;
	
	this.setEmailAddress = function(_emailAddress) {
		emailAddress = _emailAddress;	
	}
	
	this.getEmailAddress = function() {
		return(emailAddress);	
	}
	
	this.setPassword = function(_password) {
		password = _password;
	}
	
	this.getAccountID = function() {
		return(accountID);	
	}
	
	this.loginForm = function() {
		
		jqalert('<div style="width: 375px">' +
		        '<form name="loginUserForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td width="20%">Email:</td>' +
				'<td width="80%"><input id="emailAddress" type="text" size="35" name="emailAddress"></td>' +
				'</tr>' +
				'<tr>' +
				'<td width="20%">Password:</td>' +
				'<td width="80%"><input id="userPassword" type="password" size="35" name="userPassword"></td>' +
				'</tr>' +
				'<tr>' +
				'<td colspan="2" width="100%" align="center"><small><a style="color: #000000;" href="#" onclick="webUser.emailPasswordForm(); return false;">Forgot your password? Click to have it emailed to you!</a></small></td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Citrus County G.I.S. User Login', 
				{icon: '/js/jquery/jqalert/alert_icon_login.png', callbackFunction: wu.login, cancelBtn: true});
	}
	
	this.emailPasswordForm = function() {
		
		jqalert('<div style="width: 375px">' +
		        '<form name="emailPasswordForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td width="20%">Email:</td>' +
				'<td width="80%">' +
				'  <input id="emailAddress2" type="text" size="35" name="emailAddress2"><br />' +
				'  <small>Enter the email address you registered with</small>' +
				'</td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Citrus County G.I.S. Password Help', 
				{icon: '/js/jquery/jqalert/alert_icon_login.png', callbackFunction: wu.emailPassword, cancelBtn: true});		
	}
	
	this.changePasswordForm = function() {
		
		jqalert('<div style="width: 375px">' +
		        '<form name="changePasswordForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td width="30%">*Old Password:</td>' +
				'<td width="70%">' +
				'  <input id="oldPassword" type="password" size="20" name="oldPassword"><br />' +
				'  <small>Enter your old (current) password</small>' +
				'</td>' +
				'</tr>' +
				'<tr>' +
				'<td width="30%">*New Password:</td>' +
				'<td width="70%">' +
				'  <input id="newPassword" type="password" size="20" name="newPassword"><br />' +
				'  <small>Enter a new password</small>' +
				'</td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Citrus County G.I.S. - Change Password', 
				{icon: '/js/jquery/jqalert/alert_icon_login.png', callbackFunction: wu.changePassword, okBtnText: 'Change Password!', cancelBtn: true});		
	}
	
	this.changePassword = function() {
		var url = '/ims/geoUser?appAction=changePassword&oldPassword=' + $('#oldPassword').val() + '&newPassword=' + $('#newPassword').val();
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem changing your password!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				
				if ($(xml).find('response').find('password').attr('changed') == 'Y') {
					jqalert('Your password has been changed successfully. ', 'Password Changed', {icon: '/js/jquery/jqalert/alert_icon_info.png'});
				}
				else {
					accountID    = -1;
					emailAddress = '';
					password     = '';
					
					jqalert('There was a problem changing your password!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.deleteStoredMap = function(mapID) {
		var url = '/ims/geoUser?appAction=deleteStoredMap&mapID=' + mapID;
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem deleting the specified map!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				
				if ($(xml).find('response').find('map').attr('deleted') == 'Y') {
					//jqalert('Map was successfully deleted.', 'Delete Map', {icon: '/js/jquery/jqalert/alert_icon_info.png', callbackFunction: function() {window.location.reload(); }});
					window.location.reload();
				}
				else {
					accountID    = -1;
					emailAddress = '';
					password     = '';
					
					jqalert('There was a problem deleting the specified map!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.emailPassword = function() {
		var url = '/ims/geoUser?appAction=emailPassword&emailAddress=' + $('#emailAddress2').val();
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem locating your password!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				
				if ($(xml).find('response').find('email').attr('sent') == 'Y') {
					jqalert('Your password has been emailed to you. Please be<br />patient as it could take up to five minutes.', 'Password Located', {icon: '/js/jquery/jqalert/alert_icon_info.png'});
				}
				else {
					accountID    = -1;
					emailAddress = '';
					password     = '';
					
					jqalert('There was a problem locating your password!<br /> Please try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.registerNewUserForm = function() {
		jqalert('<div style="width: 375px">' +
		        '<form name="registerUserForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td colspan="2" align="center">** You do not need to register to use maps! **</td>' +
				'</tr>' +
				'<tr>' +
				'<td width="20%">Email:</td>' +
				'<td width="80%">' +
				'  <input id="emailAddress" type="text" size="35" name="emailAddress"><br />' +
				'  <small>Required to create an account</small>' +
				'</td>' +
				'</tr>' +
				'<tr>' +
				'<td width="20%">Password:</td>' +
				'<td width="80%">' +
				'  <input id="userPassword" type="password" size="35" name="userPassword"></td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Register as a New User', 
				{icon: '/js/jquery/jqalert/alert_icon_register.png', callbackFunction: wu.register, okBtnText: 'Register!', cancelBtn: true});	
	}
	
	this.deleteMapForm = function(mapID) {
		jqalert('<div style="width: 375px">' +
		        '<form name="deleteMapForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td width="100%">Are you sure you want to delete the stored map?</td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Delete Map', 
				{icon: '/js/jquery/jqalert/alert_icon_warning.png', callbackFunction: function() {wu.deleteStoredMap(mapID);}, okBtnText: 'Delete!', cancelBtn: true});	
	}
	
	this.register = function() {
		var url = '/ims/geoUser?appAction=register&emailAddress=' + $('#emailAddress').val() + '&password=' + $('#userPassword').val();
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem registering! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				var status = parseInt($(xml).find('response').find('account').attr('status')); 
				
				if (status == 0) {
					jqalert('You have successfully registered as a new user. You will<br>receive an email at the email address that you specified.<br>To finish the registration process, follow the directions <br>in the email.', 'Registered!', {icon: '/js/jquery/jqalert/alert_icon_info.png'});
				}
				else {
					accountID    = -1;
					emailAddress = '';
					password     = '';
					
					jqalert('There was a problem registering! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.login = function() {
		var url = '/ims/geoUser?appAction=login&email=' + $('#emailAddress').val() + '&password=' + $('#userPassword').val();
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem logging in! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				var userAccountID = parseInt($(xml).find('response').find('account').attr('id')); 
				
				if (userAccountID > -1) {
					accountID    = userAccountID;
					emailAddress = $('#emailAddress').val();
					password     = $('#userPassword').val();
					
					$('#loginout').html('LOGOUT');
					$('#loginout').attr('title', 'Click to Logout');
					$("#loginout").removeAttr('onclick').unbind('click');
					$("#loginout").bind('click', function() {
						webUser.logout();
					});
					
					//jqalert('You have successfully logged in.', 'Logged In', {icon: '/js/jquery/jqalert/alert_icon_info.png', callbackFunction: function() {window.location.href = '/my_account.htm';}});
					
					window.location.href = '/my_account.htm';
				}
				else {
					accountID    = -1;
					emailAddress = '';
					password     = '';
					
					jqalert('There was a problem logging in! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.checkUser = function(callback) {
		var url = '/ims/geoUser?appAction=checkUser';
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do nothing - user not logged in
				callback(false);
    		},
    		success: function(xml) {
				var userAccountID = parseInt($(xml).find('response').find('account').attr('id')); 
				var isLoggedIn    = (userAccountID == -1 ? false : true);
				
				if (isLoggedIn) {
					emailAddress = $(xml).find('response').find('account').attr('email');
					
					if ($('#emailAddressDisplay').length > 0) {
						$('#emailAddressDisplay').html(emailAddress);
					}
				}
				
				callback(isLoggedIn);
			}
				
		});	
	}
	
	this.getStoredMaps = function() {
		var url = '/ims/geoUser?appAction=getStoredMapList';
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
    		},
    		success: function(xml) {
				if ($(xml).find('response').find('account') == 'undefined' || $(xml).find('response').find('account') == null) {
					wu.resetUser();
					
					jqalert('Due to inactivity, you have been logged out.! Please<br>login again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
					return;	
				}
				
				$(xml).find('response').find('map').each(function() {
					if (!$('#storedmaplist').containsOption($(this).attr('id'))) {
						$('#storedmaplist').addOption($(this).attr('id'), $(this).attr('map_name'));
					}	
				});
				
				$('#storedmaplist').sortOptions();
				$('#storedmaplist').selectOptions('');
			}
				
		});	
	}
	
	this.getStoredMapsAsTable = function(divID, callback) {
		var url = '/ims/geoUser?appAction=getStoredMapList';
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
    		},
    		success: function(xml) {
				if ($(xml).find('response').find('account') == 'undefined' || $(xml).find('response').find('account') == null) {
					wu.resetUser();
					
					jqalert('Due to inactivity, you have been logged out.! Please<br>login again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
					return;	
				}
				
				var mapList  = '<table class="stripeClass" width="100%" cellpadding="1" cellspacing="0" border="0">' +
				               '  <tr>' +
							   '    <td align="left"><strong>Map Name</strong></td>' +
							   '    <td>&nbsp;</td>' +
							   '    <td align="center" nowrap="nowrap"><strong>Last Used</strong></td>' +
							   '    <td>&nbsp;</td>' +   
							   '    <td colspan="3" align="center" nowrap="nowrap"><strong>Actions</strong></td>' +
							   '  </tr>';
				var mapCount = 0;
				
				$(xml).find('response').find('map').each(function() {
					mapCount++;
					
					mapList += '  <tr>' +
							  //'    <td width="5%" align="center"><input type="checkbox" id="mapID" name="mapID" value="' + $(this).attr('id') + '" /></td>' +
							   '    <td align="left">' + $(this).attr('map_name') + '</td>' +
							   '    <td>&nbsp;</td>' +
							   '    <td align="center" nowrap="nowrap">' + $(this).attr('last_use_dttm') + '</td>' +
							   '    <td>&nbsp;</td>' +   
							   '    <td align="center" nowrap="nowrap"><a style="color: #000000;" href="#" onclick="webUser.deleteMapForm(' + $(this).attr('id') + '); return false;">Delete</a></td>' +
							   '    <td>&nbsp;</td>' +                    
							   '    <td align="center" nowrap="nowrap"><a style="color: #000000;" href="/ccimap.html?z=storedMap&zval=' + $(this).attr('id') + '" target="storedmap_' + $(this).attr('id') + '">Launch Map</a></td>' +
							   '  </tr>';
							   
				});
				
				if (mapCount == 0) {
					mapList += '  <tr>' +
					           '    <td colspan="7" align="center"><i>No Stored Maps Available</i></td>' +
							   '  </tr>';
				}
				
				mapList += '</table>' +
				           '<br />';
				
				$('#' + divID).html(mapList);
				$('.stripeClass tr:odd').addClass('alt');
			
				if (callback) {
					callback;
				}
			}
				
		});	
	}
	
	this.loadStoredMap = function(_mapID) {
		if (_mapID == '' || _mapID == '-1')
			return;
		
		var url = '/ims/geoUser?appAction=getStoredMap&mapID=' + _mapID;
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem loading stored map! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				
				if ($(xml).find('response').find('account') == 'undefined' || $(xml).find('response').find('account') == null) {
					wu.resetUser();
					
					jqalert('Due to inactivity, you have been logged out.! Please<br>login again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
					return;	
				}
				
				var minX = parseFloat($(xml).find('response').find('map').attr('minx')); 
				var minY = parseFloat($(xml).find('response').find('map').attr('miny')); 
				var maxX = parseFloat($(xml).find('response').find('map').attr('maxx')); 
				var maxY = parseFloat($(xml).find('response').find('map').attr('maxy')); 
				
				$(xml).find('response').find('layers').find('layer').each(function() {
					if ($(this).attr('enabled') == 'Y') {
						$('#layerID_' + $(this).attr('id')).attr('checked', 'checked');
					}
					else {
						$('#layerID_' + $(this).attr('id')).removeAttr('checked');	
					}	
				});
				
				map.setExtent(minX, maxX, minY);
				map.redraw();
			}
				
		});	
	}
	
	this.storeMapForm = function() {
		jqalert('<div style="width: 375px">' +
		        '<form name="storeNewMapForm" method="post" action="#">' +
		        '<table width="100%" align="center" border="0">' +
				'<tr>' +
				'<td width="20%">Map Name:</td>' +
				'<td width="80%"><input id="newMapName" type="text" size="35" maxlen="50" name="newMapName"></td>' +
				'</tr>' +
				'</table>' +
		        '</form>' +
				'</div>', 
				'Store Current Map View', 
				{icon: '/js/jquery/jqalert/alert_icon_info.png', callbackFunction: wu.storeMap, okBtnText: 'Save Map', cancelBtn: true});		
	}
	
	this.storeMap = function() {
		var newMapName = $('#newMapName').val();   
		var url  = '/ims/geoUser?appAction=storeMap&mapName=' + newMapName.replace(/&/, '-') + '&service=' + mapManager.getMapService() + 
		           '&x1=' + map.getXmin() + '&y1=' + map.getYmin() + '&x2=' + map.getXmax() + '&y2=' + map.getYmax();
		var list = '';
		
		$("input[@name=layerID]").each(function() { 
		
			if (this.checked) {
				url += '&l_' + this.value + '=' + this.value +
				       '&en_l_' + this.value + '=Y';
			}
			else {
				url += '&l_' + this.value + '=' + this.value +
				       '&en_l_' + this.value + '=N';	
			}
					
        }); 
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem storing map! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				
				if ($(xml).find('response').find('account') == 'undefined' || $(xml).find('response').find('account') == null) {
					wu.resetUser();
					
					jqalert('Due to inactivity, you have been logged out.! Please<br>login again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
					return;	
				}
				
				var newMapID = parseInt($(xml).find('response').find('map').attr('id')); 
				
				if (newMapID > -1) {
					$('#storedmaplist').addOption($(xml).find('response').find('map').attr('id'), newMapName);
					$('#storedmaplist').sortOptions();
					$('#storedmaplist').selectOptions('');
					
					jqalert('Map successfully stored.', 'Map Stored', {icon: '/js/jquery/jqalert/alert_icon_info.png'});
					
				}
				else {
					jqalert('There was a problem storing map! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});
  
	}
	
	this.logout = function() {
		var url = '/ims/geoUser?appAction=logout';
		
		$.ajax({
  			url: url + '&' + Math.random(),
    		type: 'GET',
    		dataType: 'xml',
    		timeout: 15000,
    		error: function() {
				// do some error control here
				jqalert('There was a problem logging out! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});
    		},
    		success: function(xml) {
				var userAccountID = parseInt($(xml).find('response').find('account').attr('id')); 
				
				if (userAccountID == -1) {
					wu.resetUser();
					
					//jqalert('You have successfully logged out.', 'Logged Out', {icon: '/js/jquery/jqalert/alert_icon_info.png', callbackFunction: function() {window.location.href = '/gis.htm';} });
					
					window.location.href = '/index.html';
				}
				else {
					jqalert('There was a problem logging out! Please<br>try again.', 'Error', {icon: '/js/jquery/jqalert/alert_icon_error.png'});	
				}
			}
				
		});	
	}
	
	this.resetUser = function() {
		accountID    = -1;
		emailAddress = '';
		password     = '';
					
		$('#loginout').html('LOGIN');
		$('#loginout').attr('title', 'Click to Login');
		$("#loginout").removeAttr('onclick').unbind('click');
		$("#loginout").bind('click', function() {
			webUser.loginForm();
		});
		
		$('#profileLinkDiv').removeAttr('onclick').unbind('click');
		$('#profileLinkDiv').empty();
					
		/*
		$('#savemap').html('');
		$('#savemap').attr('title', '');
		$('#savemap').removeAttr('onclick').unbind('click');
					
		$('#storedmaplist').removeOption(/./);
						
		$('#storedmaplist').addOption('', '-- Load Stored Map --');	
		*/
	}
	

};