var BASEURL = 'http://' + window.location.hostname + '/';

function returnDocument() {
	var file_name = document.location.href;
	var end = (file_name.indexOf("?") == -1) ? file_name.length : file_name.indexOf("?");
	return file_name.substring(file_name.lastIndexOf("/")+1, end);
}

function submitFieldForm(id, field, value) {
	//alert(id + " " + field + " " + value);
	jQuery.ajax({
		type: "POST",
		url: "userUpdates.php",
		dataType: "html",
		data: "UID=" + id + "&field=" + field + "&value=" + value,
		success: function(response){
			$('.currentUser').removeClass('currentUser');
			$('tr:odd').addClass('everyOther');
			var fullResponse = response;
			//alert(fullResponse);
			var strArr = fullResponse.split(":");
			var enabled = strArr[0];
			var answer = strArr[1];
			
			if(enabled == 1) {
				var enabledClass = 'yes';
				var disabledClass = 'no';
			} else {
				var enabledClass = 'no';
				var disabledClass = 'yes';
			}
			if(field == 'Enabled') {
				field = 'enabled';
			}
			$('tr.' + id + ' > td.' + field)
				.empty()
				.html("<span class='clickable " + enabledClass + "'>" + answer + "</span>")
				.parents('tr')
					.children('td')
						.children('span')
							.removeClass(disabledClass)
							.addClass(enabledClass);
			editInfoClickable();
		},
		error: function(){
			alert("Error occured while sending your information");
		}
	});
	return true;
}

function editInfoClickable() {
	var changed = false;
	$('.clickable').click(function() {
		//alert('click');
		var numExp = new RegExp(/\d*/);
		var classes = $(this).parents('tr').attr('class');
		var UID = numExp.exec(classes);
		$('.cancel').trigger('click');
		$('.currentUser').removeClass('currentUser');
		$('tr:odd').addClass('everyOther');
		$(this).parents('tr').addClass('currentUser').removeClass('everyOther');
				
		if($(this).parents('td').hasClass('userType')) {
			if($(this).parents('td').siblings('.Username').children('span').text() != 'Admin') {
				var value = $(this).text();
				//var length = $(this).parents('td').width() + 20;
				var field = 'userType';
				
				$(this).parents('td')
					.empty()								
					.html('<div class="editBox"><form name="editFieldForm" method="POST" action="admin.php"></form></div>');
				$('<select id="' + field + UID + '" name="userType"></select')
					.prependTo('form[name="editFieldForm"]');
				
				var types = new Array("Customer", "Rep", "Dealer", "Owner", "Admin");
				for(type in types) {
					if(types[type] == value) {
						var selected = 'selected="selected"';
					} else {
						var selected = '';
					}
					var html = '<option value="' + types[type].toLowerCase() + '" ' + selected + '>' + types[type] + '</option>';
					$('#' + field + UID).append(html);
				}
				
				$('#' + field + UID + ' > option').click(function() {
					var str = $('form[name="editFieldForm"] > select[name="' + field + '"]').val();
					return submitFieldForm(UID, field, str);
				});
			} else {
				$('.currentUser').removeClass('currentUser');
				$('tr:odd').addClass('everyOther');
			}
		} else if($(this).parents('td').hasClass('enabled')) {
			if($(this).parents('td').siblings('.Username').children('span').text() != 'Admin') {
				var value = $(this).text();
				//var length = $(this).parents('td').width() + 20;
				var field = 'Enabled';
				
				$(this).parents('td')
					.empty()								
					.html('<div class="editBox"><form name="editFieldForm" method="POST" action="admin.php"></form></div>');
				$('<select id="' + field + UID + '" name="' + field + '"></select')
					.prependTo('form[name="editFieldForm"]');
				
				var types = new Array("Yes", "No");
				for(type in types) {
					if(types[type] == value) {
						var selected = 'selected="selected"';
					} else {
						var selected = '';
					}
					var html = '<option value="' + types[type].toLowerCase() + '" ' + selected + '>' + types[type] + '</option>';
					$('#' + field + UID).append(html);
				}
				
				$('#' + field + UID + ' > option').click(function() {
					var str = $('form[name="editFieldForm"] > select[name="' + field + '"]').val();
					return submitFieldForm(UID, field, str);
				});
			} else {
				$('.currentUser').removeClass('currentUser'); 
				$('tr:odd').addClass('everyOther');
			}
		} else if($(this).parents('td').hasClass('UID')) {
		
		} else if($(this).parents('td').hasClass('lastAccess')) {
		
		} else if($(this).parents('td').hasClass('delete')) {
			var field = 'delete';
			$(this).parents('td')
					.empty()								
					.html('<div class="editBox"><form name="editFieldForm" method="POST" action="admin.php"></form></div>');
			$('<select id="' + field + UID + '" name="' + field + '"></select')
				.prependTo('form[name="editFieldForm"]');
			
			var types = new Array("User", "Info", "Both");
			for(type in types) {
				var html = '<option value="' + types[type].toLowerCase() + '">' + types[type] + '</option>';
				$('#' + field + UID).append(html);
			}
			
			$('#' + field + UID + ' > option').click(function() {
				var val = $('form[name="editFieldForm"] > select[name="' + field + '"]').val();
				$.post("deleteUser.php", {"UID":UID,"delete":val}, function(json) {
					var ok = json.status;
					if(ok) {
						$('#' + field + UID).parents('tr:first').remove();
						var curPg = parseInt($('.current').not('.prev,.next').html()) - 1;
						pageSelectCallback(curPg, $('#Pagination'));
					} else {
						alert(data.message);
					}
				}, "json");
			});
			
		} else {
			var value = $(this).text();
			if(value != 'Admin') {
				var length = $(this).parents('td').width() + 20;
				if(length < 106) {
					length = 110;
				}
				var field = $(this).parents('td').attr('class');
				
				$(this).parents('td')
					.empty()
					.html('<div class="editBox"><form name="editFieldForm" method="POST" action="admin.php"><br><span class="save"><img src="' + BASEURL + 'images/save.png" border="0">&nbsp;Save</span>&nbsp;<span class="cancel"><img src="' + BASEURL + 'images/cancel.png" border="0">&nbsp;Cancel</span></form></div>');
				$('<input name="' + field +'" id="' + field + UID + '" value="' + value + '">')
					.width(length)
					.height(15)
					.prependTo('form[name="editFieldForm"]');
				
				$('.cancel').click(function() {
					if($(this).parents('tr').children('td:last').children('span').text() == 'No') {
						
						var enabledClass = 'no';
					} else {
						var enabledClass = 'yes';
					}
					$('.currentUser').removeClass('currentUser');
					$('tr:odd').addClass('everyOther');
					$('tr.' + UID + ' > td.' + field)
						.empty()
						.html("<span class='clickable " + enabledClass + "'>" + value + "</span>");
					editInfoClickable();
				});
				
				$('.save').click(function() {
					$('.currentUser').removeClass('currentUser');
					$('tr:odd').addClass('everyOther');
					var str = $('form[name="editFieldForm"] > input[name="' + field + '"]').val();
					return submitFieldForm(UID, field, str);
				});	
			}
		}
	});
}

function getReps(ID, AID, CID, personType) {
	jQuery.ajax({
		type: "POST",
		url: "getDealer.php",
		dataType: "html",
		data: "ID=" + ID + "&areaID=" + AID + "&companyID=" + CID + "&personType=" + personType,
		success: function(response){
			$("#rightSide").append(response);
			resize();
			setupButtonEvent();
			var repSpan = $('span.rep');
			var rmSpan = $('span.rm');
			var dealerSpan = $('span.dealerSpan');
			$('.addRep').click(function() {
				var AID = $(this).siblings('.areaID').text();
				var CID = $(this).siblings('.companyID').text();
				$('.contactForm').remove();
				$('#repList').remove();
				$('#editDealer').remove();
				$('#rmDiv').remove();
				$('#dealerDiv').remove();
				addDealer(AID, CID, 'add', 'Rep');
			});
			repSpan.click(function() {
				var AID = $(this).children('.areaID').text();
				var CID = $(this).children('.companyID').text();
				var DID = $(this).children('.repID').text();
				$('.contactForm').remove();
				$('#repList').remove();
				$('#editDealer').remove();
				$('#rmDiv').remove();
				$('#dealerDiv').remove();
				getDealer(DID, AID, CID, "view", "Rep");
			});
			rmSpan.click(function() {
				var AID = $(this).children('.areaID').text();
				var CID = $(this).children('.companyID').text();
				var RMID = $(this).children('.RMID').text();
				$('.contactForm').remove();
				$('#repList').remove();
				$('#editDealer').remove();
				$('#rmDiv').remove();
				$('#dealerDiv').remove();
				getDealer(RMID, AID, CID, "view", "Regional Manager");
			});
			dealerSpan.click(function() {
				var AID = $(this).children('.areaID').text();
				var CID = $(this).children('.companyID').text();
				var BID = $(this).children('.dealerID').text();
				$('.contactForm').remove();
				$('#repList').remove();
				$('#editDealer').remove();
				$('#rmDiv').remove();
				$('#dealerDiv').remove();
				getDealer(BID, AID, CID, "view", "Dealer");
			});
			if(personType == 'Regional Manager'){
				////get dealer list for the current state and put on the right side of page
			}
		},
		error: function(){
			alert("Error occured during while retrieving Rep information from the server...");
		}
	});
}

function removeDealer(BID, AID, CID, personType) {
	$('#buttonKey').hide('fast');
	$('.contactForm').remove();
	$('#areaMng').hide('fast');
	$('#content').height(700);
	$('#dealerForm').remove();
	$('#statesDealerList').remove();
	$('#rightSide').append('<div id="dealerForm"></div>');
	if(personType == 'Rep') {
		var msg = 'By removing this Rep, you are not removing their complete record only their link as a Rep.';
	} else if(personType == 'Dealer') {
		var msg = 'By removing this Dealer, you are simply reassiging this Dealerage and any Reps linked to it to Renew a permanent replacement Dealer is put in place.';
	}
	$.getJSON("getAreaAndLogo.php", { areaID: AID, companyID: CID }, function(json){
  		$.each(json.data, function(i,items){
			var area = items.area;
			var logo = items.logo;
			$('#dealerForm').append("<div class='contactForm copy'><img class='logo' src='" + BASEURL + "images/" + logo + "'><br><br><span class='infoTitle'>Remove " + area + " " + personType + "</span><br><br><p class='infoTitle'>Would you like to Remove or Replace this " + personType + "<br><span class='rep'><b>Note: </b>" + msg + "</p><br><br><form name='removeOrReplace' class='copy' action='' method='post'><input name='new' class='removeDealer remove' type='radio' value='Remove'><span>Remove</span></input><br><input name='new' class='removeDealer replace' type='radio' value='Replace'><span>Replace</span></input></form></div>");
		});
		$('.removeDealer').click(function() {
			if($(this).hasClass('remove')) {
				$('form[name=removeOrReplace]').remove();
				$('p.infoTitle').remove();
				$('span.infoTitle').remove();
				$('img.logo').remove();
				jQuery.ajax({
					type: "POST",
					url: "removeDealer.php",
					dataType: "html",
					data: "dealerID=" + BID + "&areaID=" + AID + "&companyID=" + CID + "&personType=" + personType,
					success: function(response){
						$("#dealerForm").append(response);
						var serverCodes = $('.serverCode');
						var succeeded = true;
						serverCodes.each(function() {
							if($(this).text() == 'false') {
								succeeded = false;
								return false;
							} else {
								succeeded = true;
							}
						});
						if(succeeded) {
							$('.contactForm').remove();
						}
					},
					error: function(){
						alert("Error occured while removing" + firstName + " " + lastName);
					}
				});
			} else if($(this).hasClass('replace')) {
				$('form[name=removeOrReplace]').children().remove();
				addDealer(AID, CID, 'replace', 'Dealer');
			}
		});
	});
}

function submitAdminForm(BID, AID, CID, action, type, input, personType) {
	//$('#dealerForm').remove();
	$('#repList').remove();
	$('#rmDiv').remove();
	$('#editDealer').remove();
	$('#dealerDiv').remove();
	$('#statesDealerList').remove();
	jQuery.ajax({
		type: "POST",
		url: "adminCon.php",
		dataType: "html",
		data: input + "&action=" + action + "&dealerID=" + BID + "&areaID=" + AID + "&companyID=" + CID + "&personType=" + personType,
		success: function(response){
			$("#dealerForm").append(response);
			var serverCodes = $('.serverCode');
			var succeeded = true;
			serverCodes.each(function() {
				if($(this).text() == 'false') {
					succeeded = false;
					return false;
				} else {
					succeeded = true;
				}
			});
			if(succeeded) {
				$('.contactForm').remove();
				$('#editDealer').remove();
				$('.addMore').click(function() {
					if($(this).hasClass('yes')) {
						jQuery.ajax({
							type: 'POST',
							url: 'addAnother.php',
							dataType: 'html',
							success: function(response){
								$('span.addAnother').remove();
								$('span.serverMessage').remove();
								$('form[name=editInfo]').remove();
								$('form[name=addAnother]').empty().append(response);
								$('#company option').click(function() {
									var area = $('#area').val();
									var type = $('#type').val();
									var company = $('#company').val();
									$('form[name=addAnother]').remove();
									addDealer(area, company, 'add', type);
								});
							},
							error: function(){
								alert('Error occured during Ajax request...');
							}
						});
					} else if($(this).hasClass('no')) {
						window.location = SECURE + "dealers.php";
					}
				});
				
				
			}
		},
		error: function(){
			alert("Your request could not be submitted to the server...");
		}
	});
}

function addDealer(AID, CID, addReplace, personType) {
	$('#buttonKey').hide('fast');
	$('#areaMng').hide('fast');
	$('#content').height(700);
	$('#dealerForm').remove();
	$('#statesDealerList').remove();
	$('#rightSide').append('<div id="dealerForm"></div>');
	$.getJSON("getAreaAndLogo.php", { areaID: AID, companyID: CID }, function(json){
		if(addReplace == 'replace') {
			var replaceStr = 'Replace ';
			var instructions = 'assign';
			$('form[name=newOrExist]').remove();
			$('p.infoTitle').remove();
			$('span.infoTitle').remove();
			$('img.logo').remove();
			$('div.contactForm').remove();
		} else {
			var replaceStr = '';
			var instructions = 'add';
		}
	$.each(json.data, function(i,items){
		var area = items.area;
		var logo = items.logo;
		$('#dealerForm').append("<div class='contactForm copy'><img class='logo' src='" + BASEURL + "images/" + logo + "'><br><br><span class='infoTitle'>" + replaceStr + area + " " + personType + "</span><br><br><p class='infoTitle'>Please choose <span class='remove'>which type of " + personType + "</span> you would like to " + instructions + " <span class='asThe hidden'>as the " + personType + " </span>for " + area + "</p><br><form name='newOrExist' class='copy' action='' method='post'><input name='new' class='addDealer new' type='radio' value='New'><span>New</span></input><br><input name='new' class='addDealer existing' type='radio' value='Existing'><span>Existing</span></input></form></div>");
	});
		$('.addDealer').click(function() {
			if($(this).hasClass('new')) {
				$('form[name=newOrExist]').remove();
				$('p.infoTitle').remove();
				$('span.infoTitle').remove();
				$('img.logo').remove();
				$('div.contactForm').remove();
				getDealer('', AID, CID, "add", personType);
			} else if($(this).hasClass('existing')) {
				$('form[name=newOrExist]').children('').remove();
				$('span.remove')
					.empty()
					.append("who");
				$('span.asThe').removeClass('hidden');
				jQuery.ajax({
					type: 'POST',
					url: 'addDealer.php',
					dataType: 'html',
					success: function(response){
						$('form[name=newOrExist]').append(response);
						$('#dealers option').click(function() {
							var BID = $(this).val();
							$('.contactForm').remove();
							getDealer(BID, AID, CID, "addExist", "Dealer");
						});
						$('#reps option').click(function() {
							var DID = $(this).val();
							$('.contactForm').remove();


							getDealer(DID, AID, CID, "addExist", "Rep");
						});
					},
					error: function(){
						alert('Error occured during Ajax request...');
					}
				});
			}
		});
	});
}

function getDealer(ID, AID, CID, task, personType) {
	$('#buttonKey').hide('fast');
	$('#areaMng').hide('fast');
	$('#content').height(700);
	$('#dealerForm').remove();
	$('#statesDealerList').remove();
	$('#rightSide').append('<div id="dealerForm"></div>');
	jQuery.ajax({
		type: "POST",
		url: "getDealer.php",
		dataType: "html",
		data: "ID=" + ID + "&areaID=" + AID + "&companyID=" + CID + "&task=" + task + "&personType=" + personType,
		success: function(response){
			$("#dealerForm").append(response);
				$('.ui-datepicker-trigger').hide();
				if(task == 'view') {
					$('label').css({cursor: 'default'});
					getReps(ID, AID, CID, personType);
				}
				if(task == 'edit' || task == 'add') {
					$('div.row.hidden').removeClass('hidden');
					$('.ui-datepicker-trigger').show();
					checkFormInput();
					if(task == 'edit') {
						getReps(ID, AID, CID, personType);
					}
				}
				

			//date picker call
			$("#startDate").datepicker({
				showOn: 'both', 
				buttonImage: '../images/calendar.gif', 
				buttonImageOnly: true,
				changeMonth: true,
				changeYear: true,
				showButtonPanel: true
			});
			$('form[name=editInfo]').submit(function(event) {
				event.preventDefault();
				var submitType = $('#submit').val();
				var str = $("form[name=editInfo]").serialize();
				if(task == 'add' || task == 'addExist') {
					var addType = $('#hiddenValue').val();
					submitAdminForm(ID, AID, CID, submitType, addType, str, personType);
				} else {
					submitAdminForm('', '', '', submitType, '', str, personType);
				}
			});
			$('div#editDealer img').click(function(){
				
				if($(this).hasClass('editInfo')) {
						$('.disabled').removeAttr("disabled").removeClass("disabled");
						$('input.hidden').removeClass('hidden');
						$('div.row.hidden').removeClass('hidden');
						checkFormInput();
				} else if($(this).hasClass('remove')) {
					$('#repList').remove();
					$('#rmDiv').remove();
					removeDealer(ID, AID, CID, personType);
				}
			});
		},
		error: function(){
			alert("Error occured during while retrieving information from the server...");
		}
	});
}

function setupButtonEvent() {
	var buttons = $('.button');
	buttons.click(function() {
		var AID = $(this).siblings('.dealerSpan').children('.areaID').text();
		var CID = $(this).siblings('.dealerSpan').children('.companyID').text();
		if(!($(this).hasClass('add'))) {
			var BID = $(this).siblings('.dealerSpan').children('.dealerID').text();
			var fullName = $(this).siblings('.dealerSpan').children('.dealerName').text();
			var firstName = fullName.split(" ")[0];
			var lastName = fullName.split(" ")[1];
		}
		if($(this).hasClass('add')) {
			addDealer(AID, CID, 'add', 'Dealer');
		} else if($(this).hasClass('edit')) {
			getDealer(BID, AID, CID, "edit", "Dealer");
		} else if($(this).hasClass('remove')) {
			removeDealer(BID, AID, CID, "Dealer");
		}
	});
}

function pageSelectCallback(page_index, jq){
	$.ajax({
		type: "POST",
		url: "getUsers.php",
		dataType: "html",
		data: "page=" + page_index + "&filter=0",
		success: function(data){
        	$('#userMng tbody').empty().append(data);
			$('tr:odd').addClass('everyOther');
			$('.current').corners("5px transparent");
			editInfoClickable();
			var prevPos = $('.prev').position();
			var nextPos = $('.next').position();
			var paginationLeft = parseInt($('#subNavBar').width()) / 2 - (Math.round((nextPos.left + $('.next').width()) - prevPos.left) / 2);
			$('#Pagination').css({'left': paginationLeft + 'px'});
      	}
	  });
	/*alert(page_index + 1);
	if(page_index == 0) {
		var start = (page_index);
	} else {
		var start = (page_index + 1) * 10;
	}
	var end = start + 10;
	alert('start: ' + start + ' end: ' + end);
	var new_content = $('#hiddenresult div.result:gt(' + start + ')').clone();
	$('#Searchresult').empty().append(new_content);
	return false;*/
}

function chgPasswordActions() {
	$('#changePasswordForm :input').not('#changePassword, .UID').blur(function() {
		var id = $(this).attr("id");
        clearErrors();
		errList[id] = 0;
		validate($(this));
	});
	$('#changePasswordForm').submit(function(event) {
		event.preventDefault();
		//alert('submit');
		var valid = validate($('#changePasswordForm :input').not('#changePassword, .UID'));
		//alert(valid);
		var str = $('#changePasswordForm').serialize();
		//alert(str);
		$.post("updatePersonalInfo.php", str + '&clicked="account"', function(json) {
			var ok = json.status;
			if(ok) {
				$('#passMsg').html(json.message).fadeOut(5000);
				hide_overlay()
				$('#wait').html('Redirecting...').fadeIn('fast', function(){
						if(json.user != 1) {
							if(SITE == 'www.greenlawnandhome.com') {
								$('#sessId').attr({'action': 'http://' + SITE});
								$('#sessId').submit();
							} else {
								$('#sessId').submit();
							}
						} else {
							if(SITE == 'www.biologicalservices.com') {
								window.location=CORP + 'userSiteSelect.php';
							} else {
								window.location=json.url;
							}
						}
				});
			} else {
				$('#passMsg').addClass('error').html(json.message).fadeOut(5000);
			}
		}, "json");	
		
	});
}

$(function() {
	$('#fieldResults').css({'width': '110px'});
	if(page != 'index.php') {
		$('#secretNav').append('<div id="subNavBar"></div>');
	}
	var selected = page.slice(0,-4);
	$('.secretNavTab').each(function() {
		if($(this).is('#' + selected)) {
			var title = $(this).attr('id');
			title = title[0].toUpperCase() + title.slice(1);
			if(title == 'FieldResults') {
				title = 'Field Results';
			}
			$(this).corners("top 10px transparent").css({'background-color':'#94B553', 'height': '38px'});
			$('#subNavBar').append('<span class="subNavTitle">' + title + '</span>')
		} else {
			$(this).corners("10px transparent");
		}
		
	});
	
	if(page == 'register.php') {
		$('fieldset.prosRep').hide(); 
		if($('div.row.hide').is(':visible')) {
			$(this).hide();
		}
		
		$('input[name="haveRep"]').click(function() {
			var clicked = $(this).val();
			if(clicked == 'yes') {
				$('#DIDN').parents('div.row.hide:first').show();
			} else if(clicked == 'no') {
				$('#DIDN').parents('div.row.hide:first').hide();
			}
			resize();
		});
		
		$('input[name="interested"]').click(function() {
			var clicked = $(this).val();
			if(clicked == 'yes') {
				$('input:checkbox').parents('div.row.hide:first').show();
			} else if(clicked == 'no') {
				$('input:checkbox').parents('div.row.hide:first').hide();
			}
			resize();
		});
	}
	if(page == 'dashboard.php') {
		$('tr.hide, :input.hide').hide();
		$(':input').each(function() {
			$(this).css({'background-color': '#FFFFFF'});
		});
		var emailLength = $('#email').val().length;
		var emailWidthMultipier = 7;
		var newEmailWidth = emailLength * emailWidthMultipier;
		$('#email').width(newEmailWidth);
		$('.seeAll').live('click', function() {
			var seeWhat = $(this).attr('id').slice(6);
			if(seeWhat == 'Info') {
				$(this).text('See Less').addClass('seeLess').removeClass('seeAll');
				if($('#address2').val() != '') {
					$('#personalInfo tr.hide').show();
				} else {
					$('#personalInfo :input').not('.UID,#address2').parents('tr.hide').show();
				}
				resize();
			} else if(seeWhat == 'Orders') {
				$(this).text('See Less').addClass('seeLess').removeClass('seeAll');
				$('#recentOrders tr.hide').show();
				resize();
			}
		});
		$('.seeLess').live('click', function() {
			var seeWhat = $(this).attr('id').slice(6);
			if(seeWhat == 'Info') {
				$(this).text('See All').addClass('seeAll').removeClass('seeLess');
				$('#personalInfo tr.hide').hide();
				resize();
			} else if(seeWhat == 'Orders') {
				$(this).text('See All').addClass('seeAll').removeClass('seeLess');
				$('#recentOrders tr.hide').hide();
				resize();
			}
		});
		$('.editInfoButton img.edit').live('click', function() {
			$('img.edit').hide();
			var edit = $(this).parents('div').attr('id').slice(4,-4);
			if(edit == 'Personal') {
				
				if($('#seeAllInfo').hasClass('seeAll')) {
					$('#seeAllInfo').trigger('click').parents('span').hide();
				}
				$('#personalInfo span[class^="temp"]').hide();
				$('#personalInfo :input.hide').show();
				$('#address2').parents('tr.hide').show();
				$('#personalInfo .disabled').removeAttr("disabled").removeClass("disabled").addClass('enabled');
				$('#editPersonalInfo').append('<br /><span id="perControlsContainer"><span id="savePersonal" class="editAction clickable link"><img title="Save" src="' + GLBLIMAGES + 'save.png" border="0"></span> <span id="cancelPersonal" class="editAction clickable link"><img title="Cancel" src="' + GLBLIMAGES + 'cancel.png" border="0"></span></span>');
				resize();
			} else if(edit == 'Account') {
				$('#accountInfo :input.hide').show();
				$('#accountInfo .disabled').removeAttr("disabled").removeClass("disabled").addClass('enabled');
				$('#editAccountInfo').append('<br /><span class="accControlsContainer"><span id="saveAccount" class="editAction clickable link"><img title="Save" src="' + GLBLIMAGES + 'save.png" border="0"></span> <span id="cancelAccount" class="editAction clickable link"><img title="Cancel" src="' + GLBLIMAGES + 'cancel.png" border="0"></span></span>');
				$('.passwordContainer').hide();
				$('.passwordTd').empty().attr('valign', 'top').width(125).html('Current Password<br /><br />New Password<br /><br />Confirm Password').css({'padding-top':'8px', 'padding-bottom':'5px'});
				resize();
			}
		});
		$('.editAction').live('click', function() {
			var action = $(this).attr('id');
			$(this).parents('span').hide();
			$('img.edit').show();
			if(action == 'savePersonal') {
				var str = $('#editPersonalInfoForm').serialize();
				$('#cancelPersonal').trigger('click');
				//alert(str);
				$.post("updatePersonalInfo.php", str + '&clicked=personal', function(json) {
					//alert(json);
					$('#editPersonalInfoForm :input, #editAccountInfoForm :input').not('.UID').each(function() {
						$(this).val(json.user[$(this).attr("id")]);
					});
					var ok = json.status;
					if(ok) {
						$('#personalMessage').html(json.message).fadeOut(5000);
					} else {
						$('#personalMessage').addClass('error').html(json.message);
					}
				}, "json");
			} else if(action == 'cancelPersonal') {
				$('#personalInfo span[class^="temp"]').show();
				$('#personalInfo :input.hide').hide();
				$('#personalInfo .enabled').attr("disabled", true).addClass("disabled").removeClass('enabled');
				$('#seeAllInfo').trigger('click').parents('span').show();
				$('.controlsContainer').remove();
				resize();
			} else if(action == 'saveAccount') {
				var str = $('#editAccountInfoForm').serialize();
				$('#cancelAccount').trigger('click');
				$.post("updatePersonalInfo.php", str + '&clicked=account', function(json) {
					$('#editPersonalInfoForm :input, #editAccountInfoForm :input').not('.UID').each(function() {
						$(this).val(json.user[$(this).attr("id")]);
					});
					var ok = json.status;
					if(ok) {
						$('#accountMessage').html(json.message).fadeOut(5000);
					} else {
						$('#accountMessage').addClass('error').html(json.message).fadeOut(5000);
					}
				}, "json");	
			} else if(action == 'cancelAccount') {
				$('#accountInfo :input.hide').hide();
				$('#accountInfo .enabled').attr("disabled", true).addClass("disabled").removeClass('enabled');
				$('.passwordContainer').show().attr('valign', 'middle');
				$('.passwordTd').empty().attr('valign', 'middle').width(75).html('Password:').css({'padding-top':'0px', 'padding-bottom':'0px'});
				$('.accControlsContainer').remove();
			}
			
		});
	}
	
	if(page == 'users.php') {
		$('#subNavBar').append('<div id="usersSubNav"><div id="usersManage" class="floatL secretSubNavTab usersSubLinks"><a href="javascript:;" class="secretSubNavLink">Manage</a></div><div id="usersCreate" class="floatL secretSubNavTab usersSubLinks"><a href="javascript:;" class="secretSubNavLink">Create</a></div></div>');
		
		//var usersSubNavLeft = usersPos.left - ($('#users').width() / 2);
		//$('#usersSubNav').css({'left': usersSubNavLeft, 'top': '40px', 'position': 'absolute'});
		
		$('#userMng, #alphaFilter').hide();
		$('.usersSubLinks').click(function() {
			var subLinkId = $(this).attr('id');
			if(subLinkId == 'usersManage') {
				if(!$('#userMng').is(':visible')) {
					var num_entries = '' 
					$.ajax({
						type: "POST",
						url: "getUserCount.php",
						dataType: "html",
						success: function(data){
							
							num_entries = data;
							//alert(num_entries);
							$("#Pagination").pagination(num_entries, {
								num_edge_entries: 2,
								num_display_entries: 8,
								callback: pageSelectCallback,
								items_per_page:10
							});
					  	}
					  });
					
					//$('.create').hide();
					$('span:contains("Admin")')
						.parents('td')
							.not('.userType')
						.parents('tr')
							.children('td')
								.filter('.userType, .enabled, .Username')
								.children('span')
									.removeClass('clickable')
									.addClass('unchangeable');
					editInfoClickable();
					$('#userMng, #alphaFilter').show('slow');
					$('.filterLink').live('click', function() {
						var letter = $(this).attr('id');
						$.ajax({
							type: "POST",
							url: "getUsers.php",
							dataType: "html",
							data: "filter=1" + "&letter=" + letter,
							success: function(data){
								$('#userMng tbody').empty().append(data);
								$('tr:odd').addClass('everyOther');
								editInfoClickable();
							}
						  });
					});
					//pageSelectCallback(0, '');
					$('tr:odd').addClass('everyOther');
				}
			} else if(subLinkId == 'usersCreate') {
				if(!$('#textcentered').is(':visible')) {
					$('.manage').hide();
					$('#textcentered').show('slow');
				}
			}
		});	
	}
	
	
	if(page == 'dealers.php') {
		/*$('#tableContainer').hide();
		$('#secretNav').append('<div id="dealersSubNav"><div id="dealersMap" class="floatL secretSubNavTab dealersSubLinks"><a href="javascript:;" class="linkNav">Map</a></div><div id="dealersTable" class="floatL secretSubNavTab dealersSubLinks"><a href="javascript:;" class="linkNav">Table</a></div></div>');
		var dealerPos = $('#dealers').position();
		var dealersSubNavLeft = dealerPos.left - ($('#dealers').width() / 2);
		$('#dealersSubNav').css({'left': dealersSubNavLeft, 'top': '40px', 'position': 'absolute'});
		
		$('.dealersSubLinks').click(function() {
			var subLinkId = $(this).attr('id');
			if(subLinkId == 'dealersMap') {
				if($('#mapContainer').is(':not(:visible)')) {
					$('#tableContainer').hide('slow');
					$('#mapContainer').show('slow', function() {
						resize();
					});
				}
			} else if(subLinkId == 'dealersTable') {
				if($('#tableContainer').is(':not(:visible)')) {
					$('#mapContainer').hide('slow');
					$('#tableContainer').show('slow', function() {
						resize();
					});
				}
			}
		});*/
		
		var dealerSpan = $('span.dealerSpan');
		dealerSpan.hover(function(){ 
			$(this).css({textDecoration: 'underline'});
		}, function(){
			$(this).css({textDecoration: 'none'});
		});
	
		setupButtonEvent();
		dealerSpan.click(function() {
			var AID = $(this).children('.areaID').text();
			var CID = $(this).children('.companyID').text();
			var fullName = $(this).children('.dealerName').text();
			var firstName = fullName.split(" ")[0];
			var lastName = fullName.split(" ")[1];
			//alert("aid:" + AID + "cid:" + CID + "fullname:" + fullName + "firstName:" + firstName + "lastName:" + lastName);
			if($(this).children('span').hasClass('dealerID')) {
				var ID = $(this).children('.dealerID').text();
				getDealer(ID, AID, CID, "view", "Dealer");
			} else if($(this).children('span').hasClass('rmID')) {
				var ID = $(this).children('.rmID').text();
				getDealer(ID, AID, CID, "view", "Regional Manager");
			}
		});
	}
});