//Global Variables
var http_request = false;
var SID = false;
var service_login = true;
var taskDiv;
var contentDiv;
var statusDiv;
var accessDiv;
var session_timer;
var expanded_cats = new Array();
var expanded_users = new Array();
var expanded_stats = new Array();
var display_disabled_users = false;
var display_disabled_files = false;
var display_disabled_stats = false;
var doneMsg 	= "Done.";
var loadingMsg 	= 'Loading...<img src="images/indicator.gif" title="indicator.gif" class="ind"/>';

//GENERAL FUNCTIONS
function welcomeMsg(fname,lname){
	$str = "Welcome, " + fname;
	if(lname != undefined)
		$str = $str + " " + lname + ".";
	return $str;
}

function initialize() {
	taskDiv		= document.getElementById('taskDiv');
	contentDiv	= document.getElementById('contentDiv');
	statusDiv	= document.getElementById('status');
	accessDiv	= document.getElementById('access');
	document.getElementById('username').focus;
	//externalLinks();
}

function content_updated(){
	buildCats();
	buildUsers();
	buildStats();
}


function logout() {
	location.reload(true);
}

function externalLinks() {//not needed for download.php push file (unused)
	if (!document.getElementsByTagName) return;
	var anchors = contentDiv.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
			anchor.target = "_blank";
	}
}

function setHidden(show) {
	var display = 'none';
	if(show) display = '';
	var items = getElementsByClassName(document.getElementById("contentDiv"), "tbody", "disabledItem");
	for(var i=0; i<items.length; i++) {
		items[i].style.display = display;
	}
}

//Expanding categories functions
function buildCats() {//not needed for download.php push file (unused)
	if (document.getElementById("manageFilesDiv") == undefined) return;
	
	var cats = getElementsByClassName(document.getElementById("contentDiv"), "div", "filesDiv");
	var msg = "";
	for(var i=0; i<cats.length; i++) {
		if( expanded_cats[ cats[i].id ] == undefined ) {
			expanded_cats[ cats[i].id ] = false;
		}
	}
	expandCats();
	displayDisabledFiles();
	document.getElementById("manageFilesDiv").style.visibility = 'visible';
}
function expandCats(){
	for(keyVar in expanded_cats) {
		if( expanded_cats[ keyVar ] == true ) {
			document.getElementById( keyVar ).style.display = '';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '-';
		} else {
			document.getElementById( keyVar ).style.display = 'none';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '+';
		}
	}
}
function expandAllCats(){
	for(keyVar in expanded_cats) {
		expanded_cats[ keyVar ] = true;
	}
	expandCats();
}
function collapseAllCats(){
	for(keyVar in expanded_cats) {
		expanded_cats[ keyVar ] = false;
	}
	expandCats();
}
//End expanding categories functions

//Expanding users functions
function buildUsers() {//not needed for download.php push file (unused)
	if (document.getElementById("manageUsersDiv") == undefined) return;
	
	var users = getElementsByClassName(document.getElementById("contentDiv"), "div", "usersDiv");
	var msg = "";
	for(var i=0; i<users.length; i++) {
		if( expanded_users[ users[i].id ] == undefined ) {
			expanded_users[ users[i].id ] = false;
		}
	}
	expandUsers();
	displayDisabledUsers();
	document.getElementById("manageUsersDiv").style.visibility = 'visible';
}
function expandUsers(){
	for(keyVar in expanded_users) {
		if( expanded_users[ keyVar ] == true ) {
			document.getElementById( keyVar ).style.display = '';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '-';
		} else {
			document.getElementById( keyVar ).style.display = 'none';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '+';
		}
	}
}
function expandAllUsers(){
	for(keyVar in expanded_users) {
		expanded_users[ keyVar ] = true;
	}
	expandUsers();
}
function collapseAllUsers(){
	for(keyVar in expanded_users) {
		expanded_users[ keyVar ] = false;
	}
	expandUsers();
}
//End expanding users functions

//Expanding files functions
function buildStats() {//not needed for download.php push file (unused)
	if (document.getElementById("manageStatsDiv") == undefined) return;
	
	var Stats = getElementsByClassName(document.getElementById("contentDiv"), "div", "statsDiv");
	var msg = "";
	for(var i=0; i<Stats.length; i++) {
		if( expanded_stats[ Stats[i].id ] == undefined ) {
			expanded_stats[ Stats[i].id ] = false;
		}
	}
	expandStats();
	displayDisabledStats();
	document.getElementById("manageStatsDiv").style.visibility = 'visible';
}
function expandStats(){
	for(keyVar in expanded_stats) {
		if( expanded_stats[ keyVar ] == true ) {
			document.getElementById( keyVar ).style.display = '';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '-';
		} else {
			document.getElementById( keyVar ).style.display = 'none';
			document.getElementById( keyVar + "ExpandLink" ).innerHTML = '+';
		}
	}
}
function expandAllStats(){
	for(keyVar in expanded_stats) {
		expanded_stats[ keyVar ] = true;
	}
	expandStats();
}
function collapseAllStats(){
	for(keyVar in expanded_stats) {
		expanded_stats[ keyVar ] = false;
	}
	expandStats();
}
//End expanding stats functions

//EXPAND/COLLAPSE Function
function toggleVisible( obj ) {
	if(	expanded_cats[ obj ] != undefined ){
		expanded_cats[ obj ] = !expanded_cats[ obj ];
		expandCats();
	} else if (	expanded_users[ obj ] != undefined ){
		expanded_users[ obj ] = !expanded_users[ obj ];
		expandUsers();
	} else if (	expanded_stats[ obj ] != undefined ){
		expanded_stats[ obj ] = !expanded_stats[ obj ];
		expandStats();
	} 
}
//HIDE/SHOW DISABLED FUNCTIONS
function toggleDisplayDisabled( obj ) {
	switch (obj.id) {
		case 'toggleDDUsers':
			display_disabled_users = !display_disabled_users;
			displayDisabledUsers();
			break;
		case 'toggleDDFiles':
			display_disabled_files = !display_disabled_files;
			displayDisabledFiles();
			break;
		case 'toggleDDStats':
			display_disabled_stats = !display_disabled_stats;
			displayDisabledStats();
			break;
	}
}
function displayDisabledUsers(){
	setHidden(display_disabled_users);
	
	if (display_disabled_users)
		document.getElementById("toggleDDUsers").innerHTML = "Hide Disabled";
	else
		document.getElementById("toggleDDUsers").innerHTML = "Show Disabled";
}

function displayDisabledFiles(){
	setHidden(display_disabled_files);

	if (display_disabled_files)
		document.getElementById("toggleDDFiles").innerHTML = "Hide Disabled";
	else
		document.getElementById("toggleDDFiles").innerHTML = "Show Disabled";
}
function displayDisabledStats(){
	setHidden(display_disabled_stats);

	if (display_disabled_stats)
		document.getElementById("toggleDDStats").innerHTML = "Hide Disabled";
	else
		document.getElementById("toggleDDStats").innerHTML = "Show Disabled";
}
//END HIDE/SHOW DISABLED FUNCTION


function handleEnterKey(e,form) {
	var key;
	if(window.event)
		key = window.event.keyCode; //IE
	else
		key = e.which; //firefox     
	
	if(key == 13) { //if enter, submit to url of input box
		if(form.name == 'loginForm')
			loginRequest();
		else if(form.name == 'newuserForm')
			formValidate(form);
		else if(form.name == 'optionsForm')
			formValidate(form);
		else if(form.name == 'resetForm')
			formValidate(form);
		else if(form.name == 'forgotU')
			forgotUsername();
		else if(form.name == 'forgotP')
			forgotPassword();
		else if(form.name == 'editfileForm')
			formValidate(form);
		else if(form.name == 'editcatForm')
			formValidate(form);
		else
			alert("NO ENTER YET: "+form.name);
	}

	return (key != 13);
}

function parse(document){
	//alert(document);
	var msg 	= "Data:\n";
	var open	= 0;
	var close	= document.indexOf(">");
	var end		= document.lastIndexOf("</root>");
	var arr		= [];
	var tagid	= "";
	var tagvalue= "";
	
	open	= document.indexOf("<", close+1) ;
	
	while (open < end && open >= 0) {
		close	= document.indexOf(">", open) ;
		tagid	= document.substring(open+1,close) ;
		//if duplicate root entries exists, ignore
		if(tagid=="root" || tagid=="/root"){
			open	= document.indexOf("<", close+1) ;
			continue ; //restart loop
		}
		
		open		= close;
		close		= document.indexOf("</"+tagid+">", open) ;
		tagvalue	= document.substring(open+1,close);

	//	alert(tagid+'\n'+tagvalue);

		arr[tagid] = tagvalue;
		open	= document.indexOf("<", close+1) ;
		msg = msg + tagid + " = " + tagvalue + "\n";
	}
	//alert(msg);
	return arr;
}

function expired(xmldata){
	if(!(xmldata['invalid'] == undefined)){
		$SID=false;
		taskDiv.innerHTML = '<div class="taskLink" onclick="loadContent(\'loginform.php\')">Login</div>';
		contentDiv.innerHTML = xmldata['loginform'];
		accessDiv.innerHTML = xmldata['msg'];
		return true;
	} else {
		return false;
	}
}


function loadService() {
	//set that we're attempting a login (prevent failed login loop)
	service_login = true;
	
	document.getElementById('status').innerHTML = 'Loading...<img src="images/indicator.gif" title="indicator.gif" class="ind"/>';

	var height = size();
	
	loadContent("serviceformI.php",height);
	
}

function resizeService(){
	var height = size();
	var serviceFrame = document.getElementById('serviceFrame');
	if(serviceFrame)
		serviceFrame.height = height;
}

function size() {
	var offset = 134;//keep this consistent with style.css
	//-X, X= bannerDiv.height + bannerDiv.border-width + contentDiv.border-width
	
	var height = window.innerHeight; //standards compliant.
	if(!height) {//ie >= 6
		height = document.documentElement.clientHeight;
	}
	if(!height) {//ie (older, and newer if newer returns 0)
		height = document.body.clientHeight;
	}
	return height - offset;	
}

function slogin(serviceForm) {
	if(service_login){
		service_login = false;
		
		document.getElementById('status').innerHTML = doneMsg;
	
		var username	= document.getElementById('serviceUser').innerHTML;
		var password	= document.getElementById('servicePass').innerHTML;
		serviceForm.username.value = username;
		serviceForm.password.value = password;
		
		serviceForm.submit();
	} else {
		document.getElementById('status').innerHTML = 'Service Login Failed.  Try setting your password.';
	}
}

//Outside Developed Functions
/*
	Written by Jonathan Snook, http://www.snook.ca/jonathan
	Add-ons by Robert Nyman, http://www.robertnyman.com
*/
function getElementsByClassName(oElm, strTagName, strClassName){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	strClassName = strClassName.replace(/\-/g, "\\-");
	var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	var oElement;
	for(var i=0; i<arrElements.length; i++){
		oElement = arrElements[i];
		if(oRegExp.test(oElement.className)){
			arrReturnElements.push(oElement);
		}
	}
	return (arrReturnElements)
}

function test(){
	var supervisor = document.getElementById("supervisor");

	supervisor.options[supervisor.length] = new Option('test','value');
	
}

//*************************************************************************
//VALIDATION FUNCTIONS
//*************************************************************************
function formValidate(form) {
	switch (form.name) {
		case ("optionsForm"):
		
			var password 	= document.getElementById("password");
			var newpass 	= document.getElementById("password1");
			var verify 		= document.getElementById("password2");
			var fname 		= document.getElementById("fname");
			var lname		= document.getElementById("lname");
			var email	 	= document.getElementById("email");
			var email2	 	= document.getElementById("email2");
		
			if(!(newpass.value==verify.value)) {
				alert("Passwords do not match!");
				verify.select();
				return;
			} else if (newpass.value.length > 0){
				if(!(Vpassword(newpass.value))) {
					alert("Password too simple!\nMust be 6 characters long.");
					newpass.select();
					return;
				}
			} else if (!(fname.value.length >= 1)) {
				alert("Please enter first name.");
				fname.select();
				return;
			} else if (false/*!(lname.value.length >= 1)*/) {
				alert("Please enter last name.");
				lname.select();
				return;
			} else if (!(Vemail(email.value))) {
				alert("Please enter a valid email address.");
				email.select();
				return;
			} else if (!(email.value == email2.value)) {
				alert("Emails do not match!");
				email2.select();
				return;
			}
			optionsRequest();
			break;
		
		case 'newuserForm':
			var username	= document.getElementById("username");
			var password 	= document.getElementById("password");
			var newpass 	= document.getElementById("password1");
			var verify 		= document.getElementById("password2");
			
			if (!(Vusername(username.value))) {
				alert("Username Invalid!\nMay only contain alphanumeric characters,'_',and'-'.");
				username.select();
				return;
			} else if(!(newpass.value==verify.value)) {
				alert("Passwords do not match!");
				verify.select();
				return;
			} else if (!(Vpassword(newpass.value))) {
				alert("Password too simple!\nMust be 7 characters long and contain two of:\nlowercase,uppercase,numbers,or symbols");
				newpass.select();
				return;
			}
			newuserRequest();
			break;

		case 'newcatForm':
			var title	 	= document.getElementById("title");
			var comment		= document.getElementById("comment");
		
			if(!(title.value.length >= 1)) {
				alert("Please enter a title!");
				title.select();
				return;
			} else if (!(title.value.length <= 80)) {
				alert("Title too long, must be no more than 80 long.\nCurrent is "+ title.value.length +" long.");
				title.select();
				return;
			} else if (!(comment.value.length <= 800)) {
				alert("Comment too long, must be no more than 800 long.\nCurrent is "+ comment.value.length +" long.");
				comment.select();
				return;
			}
			newcatRequest();
			break;
		
		case 'resetForm':
			var newpass 	= document.getElementById("password1");
			var verify 		= document.getElementById("password2");
			
			if(!(newpass.value==verify.value)) {
				alert("Passwords do not match!");
				verify.select();
				return;
			} else if (!(Vpassword(newpass.value))) {
				alert("Password too simple!\nMust be 7 characters long and contain two of:\nlowercase,uppercase,numbers,or symbols");
				newpass.select();
				return;
			}
			resetRequest();
			break;
		
		case 'editfileForm':
			document.getElementById("editfileLink").click();
			break;
		
		case 'editcatForm':
			document.getElementById("editcatLink").click();
			break;
			
		default:
			alert("No validation- " + form.name)
			
	}

}/**/

function typeChanged() {
	var supervisor = document.getElementById("supervisor");
	if (document.getElementById("type").value != 3){
		supervisor.disabled = true;
	} else {
		supervisor.disabled = false;
	}


	var service_admin = document.getElementById("service_admin");
	var sales_admin = document.getElementById("sales_admin");
	var files_admin = document.getElementById("files_admin");
	var stats_admin = document.getElementById("stats_admin");
	if (document.getElementById("type").value != 1){
		service_admin.disabled = true;
		sales_admin.disabled = true;
		files_admin.disabled = true;
		stats_admin.disabled = true;
	} else {
		service_admin.disabled = false;
		sales_admin.disabled = false;
		files_admin.disabled = false;
		stats_admin.disabled = false;
	}


}

function passwordChanged() {
	var strength = document.getElementById('strength');
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{3,}).*", "g");
	var pwd = document.getElementById("password1").value;
	if (pwd.length==0) {
		strength.innerHTML = 'Type Password';
	} else if (false == enoughRegex.test(pwd)) {
		strength.innerHTML = 'More Characters';
		return false;
	} else if (strongRegex.test(pwd)) {
		strength.innerHTML = '<span style="color:green">Strong</span>';
		return true;
	} else if (mediumRegex.test(pwd)) {
		strength.innerHTML = '<span style="color:orange">Good</span>';
		return true;
	} else {
		strength.innerHTML = '<span style="color:red">Acceptable</span>';
		return true;
	}
}
function passwordMatch() {
	var match = document.getElementById('match');
	var pwd = document.getElementById("password1").value;
	var pwd2 = document.getElementById("password2").value;

	if (pwd!=pwd2) {
		match.innerHTML = '<span style="color:red">Passwords do not match.</span>';
		return false;
	} else {
		match.innerHTML = '<span style="color:green">Passwords match.</span>';
		return true;
	}
}

function Vusername(str){
	var regex = /^([-_a-zA-Z0-9]+)$/i;
	return regex.test(str);
}

function Vpassword(pwd){
	var strongRegex = new RegExp("^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*\\W).*$", "g");
	var mediumRegex = new RegExp("^(?=.{7,})(((?=.*[A-Z])(?=.*[a-z]))|((?=.*[A-Z])(?=.*[0-9]))|((?=.*[a-z])(?=.*[0-9]))).*$", "g");
	var enoughRegex = new RegExp("(?=.{3,}).*", "g");
	
	return (enoughRegex.test(pwd));
}

/*
Strip whitespace from the beginning and end of a string
Input : a string
*/
function trim(str)
{
	return str.replace(/^\s+|\s+$/g,'');
}

/*
Check if a string is in valid email format. 
Returns true if valid, false otherwise.
*/
function Vemail(str)
{
	var regex = /^[-_.a-z0-9]+@(([-_a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i;
	return regex.test(str);
}

//*************************************************************************
//XMLHttpRequest (AJAX) FUNCTIONS
//*************************************************************************
//Initialize AJAX request - used by all AJAX functions
function getTicket() {
	http_request = false; //reset ajax request
	
	//Pre-made ajax connect code for various browsers
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!http_request) {
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	return true;
}

//Universal AJAX request function - takes target url, post variables string, and event handler function
function makeRequest(url,poststr,onchange) {
	//alert the user that a request is being made
	statusDiv.innerHTML = loadingMsg;

	getTicket();
	
	if(http_request) { //if successful, continue
		http_request.onreadystatechange = onchange;
		http_request.open('POST', url, true);
		http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http_request.setRequestHeader("Content-length", poststr.length);
		http_request.setRequestHeader("Connection", "close");
		http_request.send(poststr);
	}

}

//RESTORE LINK FUNCTIONS
var linkObj;
var linkTimer;

//This is necessary to prevent starting to IP connections simultaneously
//(href from download click and onclick action to make a new link)
function waitLink(obj){
	linkObj = obj;
	setTimeout("linkObj.href = 'javascript:;'",1);
	clearTimeout(linkTimer);
	linkTimer = setTimeout("restoreLink()",500);
	
}

function restoreLink() {
	var obj = linkObj;
	//wait for download request
	var url = 'newlink.php';
	var poststr =	"SID=" + encodeURI( SID ) +
					"&file_id=" + encodeURI( obj.getAttribute("file_id") );
	
	var onchange = updateLink;
	
	makeRequest(url,poststr,onchange);
}

function updateLink() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if (xmldata["success"] == "true") {
				obj = document.getElementById('file_' + xmldata["file_id"] );
				//window.location = obj.getAttribute("link");
				obj.setAttribute("link",xmldata["newlink"]);
				obj.href = xmldata["newlink"];
			} else {
				alert( xmldata["msg"] );
			}
			
		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END RESTORE LINK FUNCTIONS

//CHECK SESSION FUNCTIONS
function checkStatus() {
	//set url
	var url = 'status.php';
	var poststr = "SID=" + encodeURI( SID );
	var onchange = updateStatus;
	
	makeRequest(url,poststr,onchange);
	
}

//Return from AJAX status request
function updateStatus() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			//reset timer for time left plus 15 seconds
			clearTimeout(session_timer);
			session_timer = setTimeout('checkStatus()', xmldata['timeleft'] + 15000);
			
		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}


//LOGIN REQUEST FUNCTIONS
function loginRequest() {
	//set url
	var url = 'login.php';
	var poststr =	"height=" + encodeURI( size() ) +
					"&user=" + encodeURI( document.getElementById("username").value ) +
					"&pass=" + encodeURI( document.getElementById("password").value );
	
	var onchange = updateLogin;
	
	makeRequest(url,poststr,onchange);
}

//Return from AJAX login request (success-> update shnum,welcome message / failure)
function updateLogin() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;

			if(xmldata['auth'] == 'true'){
				if(xmldata['disabled'] == 'false'){
					
					SID = xmldata['SID'];
					
					//if(xmldata['setup']=='true')
					//	accessDiv.innerHTML = "Please complete user setup.";
					//else
						accessDiv.innerHTML = welcomeMsg(xmldata['fname'],xmldata['lname']);
					
					session_timer = setTimeout('checkStatus()', 915000);//msec - 15min, 15sec
					
					taskDiv.innerHTML		= xmldata['task'];
					
					contentDiv.innerHTML	= xmldata['content'];
					
					//loadContent('options.php',xmldata['username']);
					
				} else {
					//USER DISABLED
					alert("User Disabled. Contact your supervisor.");
				}
			} else {
				//AUTHORIZATION FAILED
				alert("Incorrect username or password.");
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}


//RELOAD PAGE AND TASKS
function loadPage() {
	//set url
	var url = 'content.php';
	var poststr =	"SID=" + encodeURI( SID );
	
	var onchange = updatePage;

	makeRequest(url,poststr,onchange);

}

function updatePage() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			taskDiv.innerHTML		= xmldata['task'];
			contentDiv.innerHTML	= xmldata['content'];
			
			
		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
		http_request = false;
	}
}
//END RELOAD PAGE + TASKS


//CONENT FRAME UPDATE
function loadContent(url,selection) {
	
	var poststr =	"SID=" + encodeURI( SID ) +
					"&selection=" + encodeURI( selection );
	
	var onchange = updateContent;

	makeRequest(url,poststr,onchange);

}

function updateContent() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc 				= http_request.responseText;
			
			contentDiv.innerHTML	= xmldoc;
			
			content_updated();
			
		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
		http_request = false;
	}
}
//END CONTENT FRAM UPDATE

function newReport(type) {
	//set url
	var url = 'reports.php?report='+type;
	var poststr =	"SID=" + encodeURI( SID )+
					"&start_date=" + encodeURI( document.getElementById("start_date").value )+
					"&end_date=" + encodeURI( document.getElementById("end_date").value ) +
					"&selected_category=" + encodeURI( document.getElementById("selected_category").value ) +
					"&inverse=" + encodeURI( document.getElementById("inverse").checked );
	
	var onchange = updateContent;

	makeRequest(url,poststr,onchange);

}

//PASSWORD RESET
function resetRequest() {
	//set url
	var url = 'setpassword.php';
	var poststr =	"hash=" + encodeURI( document.getElementById("hash").value )+
					"&newpass=" + encodeURI( document.getElementById("password1").value )+
					"&verify=" + encodeURI( document.getElementById("password2").value );
		
	var onchange = resetConfirm;

	makeRequest(url,poststr,onchange);

}

function resetConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = "Password set.";
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				alert("Password set. You can now login with your new password.");
				contentDiv.innerHTML = xmldata["content"];
				
			} else {
				
				alert(xmldata['errormsg']);
				
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END PASSWORD RESET


//OPTIONS CHANGE and CONFIRM
function optionsRequest() {
	//set url
	var url = 'updateuser.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&user=" + encodeURI( document.getElementById("username").value )+
					"&pass=" + encodeURI( document.getElementById("password").value )+
					"&newpass=" + encodeURI( document.getElementById("password1").value )+
					"&verify=" + encodeURI( document.getElementById("password2").value )+
					"&fname=" + encodeURI( document.getElementById("fname").value )+
					"&lname=" + encodeURI( document.getElementById("lname").value )+
					"&email=" + encodeURI( document.getElementById("email").value )+
					"&email2=" + encodeURI( document.getElementById("email2").value ) +
					"&type=" + encodeURI( document.getElementById("type").value ) +
					"&service_admin=" + encodeURI( document.getElementById("service_admin").checked )+
					"&sales_admin=" + encodeURI( document.getElementById("sales_admin").checked )+
					"&files_admin=" + encodeURI( document.getElementById("files_admin").checked )+
					"&stats_admin=" + encodeURI( document.getElementById("stats_admin").checked );
		
	var onchange = optionsConfirm;

	makeRequest(url,poststr,onchange);

}

function optionsConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				msg = "User options updated:";
				if (xmldata["pwdset"]!=undefined)
					msg += "\nPassword Changed.";
				if (xmldata["servicepass"]=="true")
					msg += "\nService Reports Password Changed.";
				if (xmldata["fname"]!=undefined)
					msg += "\nFirst Name: " + xmldata["fname"];
				if (xmldata["lname"]!=undefined)
					msg += "\nLast Name: " + xmldata["lname"];
				if (xmldata["email"]!=undefined){
					msg += "\nEmail: " + xmldata["email"];
				}
				
				alert(msg);
				
				if(xmldata['admin'] == 'true')	loadContent('manageusers.php');
				else {
					accessDiv.innerHTML = welcomeMsg(xmldata['fname'],xmldata['lname']);
					if(xmldata['pwdset'] != undefined) {
						document.getElementById('serviceUser').innerHTML = xmldata['username'];
						document.getElementById('servicePass').innerHTML = xmldata['password'];
					}
					if (xmldata['type'] <= 3)//Sales users
						loadContent('view.php'); //re-load the page
					else//Service users
						loadService();
				}
				
			} else {
				alert(xmldata['errormsg']);
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END OPTIONS CHANGE AND CONFIRM

//CREATE NEW USER REQUEST
function newuserRequest() {
	//set url
	var url = 'newuser.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&type=" + encodeURI( document.getElementById("type").value )+
					"&supervisor=" + encodeURI( document.getElementById("supervisor").value )+
					"&user=" + encodeURI( document.getElementById("username").value )+
					"&pass=" + encodeURI( document.getElementById("password").value )+
					"&newpass=" + encodeURI( document.getElementById("password1").value )+
					"&verify=" + encodeURI( document.getElementById("password2").value ) +
					"&fname=" + encodeURI( document.getElementById("fname").value )+
					"&lname=" + encodeURI( document.getElementById("lname").value )+
					"&service_admin=" + encodeURI( document.getElementById("service_admin").checked )+
					"&sales_admin=" + encodeURI( document.getElementById("sales_admin").checked )+
					"&files_admin=" + encodeURI( document.getElementById("files_admin").checked )+
					"&stats_admin=" + encodeURI( document.getElementById("stats_admin").checked )+
					"&email=" + encodeURI( document.getElementById("email").value );
		
	var onchange = newuserConfirm;

	makeRequest(url,poststr,onchange);

}

function newuserConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				alert("User [" + xmldata['username'] + "] created!\n Give this username and the password you chose\n to the appropriate representative and they can finish account setup.");
				
				var another = document.getElementById("another").checked;
				if (!another) {
					loadContent('manageusers.php'); //re-load the page
				} else {
					//update options if a supervisor was added
					if(xmldata["type"] == 2) {
						var supervisor = document.getElementById("supervisor");
						supervisor.options[supervisor.length] = new Option(xmldata["fname"]+' '+
							xmldata["lname"]+' ('+xmldata["username"]+')',xmldata['username']);
					}
					
					document.getElementById("password").value = "";
					//document.getElementById("password1").value = "";
					//document.getElementById("password2").value = "";
					document.getElementById("username").select();
					document.getElementById("fname").value = "";
					document.getElementById("lname").value = "";
				}
				
			} else {
				alert(xmldata['error'] + "\n" + xmldata['errormsg']);
				document.getElementById("password").value = "";
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}

//EDIT FILE REQUEST
function editfileRequest(file_id) {
	//set url
	var url = 'updatefile.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&file_id=" + encodeURI( file_id )+
					"&title=" + encodeURI( document.getElementById("title").value )+
					"&comment=" + encodeURI( document.getElementById("comment").value )+
					"&category=" + encodeURI( document.getElementById("category").value );
	
	var onchange = editfileConfirm;

	makeRequest(url,poststr,onchange);

}

function editfileConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				alert("File information updated.");
				
				loadContent('managefiles.php'); //re-load the page
				
			} else {
				alert(xmldata['errormsg']);
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//ENN EDIT FILE REQUEST

//NEW CATEGORY REQUEST
function newcatRequest() {
	//set url
	var url = 'newcategory.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&title=" + encodeURI( document.getElementById("title").value )+
					"&comment=" + encodeURI( document.getElementById("comment").value )+
					"&order_id=" + encodeURI( document.getElementById("order_id").value ) +
					"&v_rep=" + encodeURI( document.getElementById("v_rep").checked ) +
					"&v_assoc=" + encodeURI( document.getElementById("v_assoc").checked ) +
					"&v_agent=" + encodeURI( document.getElementById("v_agent").checked );
	
	var onchange = newcatConfirm;

	makeRequest(url,poststr,onchange);

}

function newcatConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				alert("Category created.");
				
				loadContent('managefiles.php'); //re-load the page
				
			} else {
				alert(xmldata['errormsg']);
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END NEW CATEGORY REQUEST

//EDIT CATEGORY REQUEST
function editcatRequest(category_id) {
	//set url
	var url = 'updatecat.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&category_id=" + encodeURI( category_id )+
					"&title=" + encodeURI( document.getElementById("title").value )+
					"&comment=" + encodeURI( document.getElementById("comment").value )+
					"&order_id=" + encodeURI( document.getElementById("order_id").value )+
					"&v_rep=" + encodeURI( document.getElementById("v_rep").checked ) +
					"&v_assoc=" + encodeURI( document.getElementById("v_assoc").checked ) +
					"&v_agent=" + encodeURI( document.getElementById("v_agent").checked );
	
	var onchange = editcatConfirm;

	makeRequest(url,poststr,onchange);

}

function editcatConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				
				alert("Category information updated.");
				
				loadContent('managefiles.php'); //re-load the page
				
			} else {
				alert(xmldata['errormsg']);
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END EDIT CATEGORY REQUEST

//DISABLE OBJECT REQUEST
function disable(obj,id) {
	//set url
	var url = 'disable.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&obj=" + encodeURI( obj )+
					"&id=" + encodeURI( id );
	
	var onchange = disableConfirm;

	makeRequest(url,poststr,onchange);

}

function disableConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				switch (xmldata["obj"]){
					case "file":
						alert("File updated.");
						loadContent('managefiles.php'); //re-load the page
						break;
					case "category":
						alert("Category updated.");
						loadContent('managefiles.php'); //re-load the page
						break;
					case "user":
						alert("User updated.");
						loadContent('manageusers.php'); //re-load the page
						break;
					case "rep":
						alert("Rep updated.");
						loadContent('manageusers.php'); //re-load the page
						break;
				}
				
				
			} else {
				alert(xmldata['errormsg']);
				
				if(xmldata['error'] == "auth") loadPage();//if session invalid, reset
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END DISABLE REQUEST

//DELETE OBJECT REQUEST (Admin File Share Files Only)
function deleteobj(obj,id) {
	//set url
	var url = 'delete.php';
	var poststr =	"SID=" + encodeURI( SID )+
					"&obj=" + encodeURI( obj )+
					"&id=" + encodeURI( id );
	
	var onchange = deleteConfirm;

	makeRequest(url,poststr,onchange);

}

function deleteConfirm() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			if(xmldata['success'] == 'true'){
				switch (xmldata["obj"]){
					case "file":
						alert("File Deleted.");
						loadContent('managefiles.php'); //re-load the page
						break;
				}
			} else {
				alert(xmldata['errormsg']);
			}

		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END DELETE REQUEST


//FORGOT REQUEST FUNCTIONS
function forgotUsername() {
	//set url
	var url = 'forgot.php';
	var poststr =	"email=" + encodeURI( document.getElementById("email").value );
	
	var onchange = updateForgot;

	makeRequest(url,poststr,onchange);

}

function forgotPassword() {
	//set url
	var url = 'forgot.php';
	var poststr =	"username=" + encodeURI( document.getElementById("username").value );
	
	var onchange = updateForgot;

	makeRequest(url,poststr,onchange);

}

//Return from AJAX FORGOT request
function updateForgot() {
	if (http_request.readyState == 4) {		//if http done, continue. else, end
		if (http_request.status == 200) {	//if http successful, continue
			statusDiv.innerHTML = doneMsg;
			//XML Response
			var xmldoc = http_request.responseText;
			var xmldata = parse(xmldoc); if (expired(xmldata)) return;
			
			var msg = "";
			
			switch (xmldata["request"]) {
				case "username":
					if (xmldata["found"]=="true"){
						if(xmldata["email"]=="true") msg = "Username sent to email address on file.";
						else						msg = "There was an error sending your username.";
					} else msg = "E-mail address not found in database.";
					break;
				case "password":
					if (xmldata["found"]=="true"){
						if(xmldata["email"]=="true") msg = "Password reset link sent to email address on file.";
						else						msg = "There was an error resetting your password.";
					} else msg = "Username not found in databse.";
					break;
				default:
					msg = "No request made.";
			}
			
			alert(msg + "\n\nYou will now be returned to the HT Products Web Page.");
			
			window.location="http://"+xmldata['url'];
			
		} else {	//if http failed, alert user
			//error with AJAX request
			alert('There was a problem with the request.','AJAX Error');
		}
	}
}
//END FORGOT REQUEST
/**/

