// default messages
var defaultStatus = "Welcome to Retail Project Managers";
var userGreeting = "Hello, Guest!";
var userStatus = "You are not logged in";
var newProject = "";
var newNews = "";
var newEvent = "";
var adminLink = "";

/******************************************************************************/
/**                                                                          **/
/** lookupUser() - Used by 2K5.html to check the value of qdb_data[0][0]     **/
/**                and display the proper messages for the user.  If the     **/
/**                user is logged in, the user's name and a logout option    **/
/**                appear.  If not, a message informing the user that he/she **/
/**                is not logged in appears and the user is redirected to    **/
/**                index.html.                                               **/
/**                                                                          **/
/******************************************************************************/
function lookupUser()
{
	if (getCookie('2K5ticket') && (qdb_data[0][0] != "Anonymous"))
	{
		userGreeting = "Hello, " + qdb_data[0][0] + "!";
		userStatus = "<a class='options' href='javascript: logout()'>Logout</a>";
	}
	else
	{
		alert("You are not logged in.  One of the cookies needed to use this site "
			+ "either has expired or was not properly set. \n\nPlease make sure that " 
			+ "your Internet Options are set to Medium Security and Medium Privacy. "
			+ "\n\nIf you continue to receive this message afterwards, please contact "
			+ "Technical Support for assistance.");
		top.location.href = "http://www.rpm-direct.net/2K5/";
	}
}

function getCookie(cookieName)
{
	var allCookies = document.cookie;
	var pos = allCookies.indexOf(cookieName + "=");
	if (pos != -1)
	{
		var start = pos + cookieName.length + 1;
		var end = allCookies.indexOf(";", start);
		var value = unescape(allCookies.substring(start, end));
	}
	else
	{
		var value = false;
	}
	return value;
 }

/******************************************************************************/
/**                                                                          **/
/** loginRedirect() - Used by index.html to check the value of               **/
/**                qdb_data[0][0] and display the proper messages for the    **/
/**                user.  If the user is logged in, the user's name and a    **/
/**                logout option appear and the user is redirected to        **/
/**                2K5.html.  If not, a message informing the user that      **/
/**                user that he/she is not logged in appears.                **/
/**                                                                          **/
/******************************************************************************/
function loginRedirect()
{
	if (getCookie('2K5ticket') && (qdb_data[0][0] != "Anonymous"))
	{
		userGreeting = "Hello, " + qdb_data[0][0] + "!";
		userStatus = "<a class='options' href='javascript: logout()'>Logout</a>";
		top.location.href = "http://www.rpm-direct.net/2K5/2K5.html";
	}
}

/******************************************************************************/
/**                                                                          **/
/** getLinks() - Used by 2K5.html to check whether qdb_data[0][1] exists,    **/
/**              and display the "Add New..." buttons, or not.  If the user  **/
/**              belongs to the "RPM Staff" or "Administrator" roles on      **/
/**              Quickbase, the buttons are displayed, and he/she can add    **/
/**              a new project or news or events.  If the user is not        **/
/**              logged in, or is a member of limited viewing roles, the     **/
/**              buttons do not appear. In Mozilla, the user just sees a     **/
/**              blank grey bar; in IE, not even the grey bar appears.       **/
/**                                                                          **/
/******************************************************************************/
function getLinks()
{
	if (!qdb_data[0][1])
	{
		newProject = "";
		newNews = "";
		newEvent = "";
	}
	else
	{
		newProject = qdb_data[0][1];
		newNews = qdb_data[0][2];
		newEvent = qdb_data[0][3];
	}
	if (!qdb_data[0][4])
	{
		adminLink = "";
	}
	else
	{
		adminLink = qdb_data[0][4];
	}
}

/******************************************************************************/
/**                                                                          **/
/** screenSize() - Used by index.html and 2K5.html to determine the          **/
/**                resolution of the user's screen.  If the resolution is    **/ 
/**                1024x768 or greater, the scrollbar is hidden.  If not,    **/
/**                the scrollbar is allowed to appear as necessary.          **/
/**                                                                          **/
/******************************************************************************/
function screenSize()
{
	var correctwidth = 1024;
	var correctheight = 768;
	
	if (screen.width >= correctwidth || screen.height >= correctheight)
	{
		document.body.style.overflow = "hidden";
	}
	else if (screen.width < correctwidth || screen.height < correctheight)
	{
		document.body.style.overflow = "auto";
	}
}

/******************************************************************************/
/**                                                                          **/
/** help() - Used by index.html and 2K5.html to open a small pop-up          **/
/**          window containing help/index.html.                              **/
/**                                                                          **/
/******************************************************************************/
function help() 
{
	var w = screen.availWidth;
	var h = screen.availHeight;
	var popW = 750;
	var popH = 525;
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	var hFeatures = 'width=' + popW + ',height=' + popH + ',top=' + topPos; 
	hFeatures += ',left=' + leftPos + ',scrollbars=yes,menubar=no,resizable=yes,';
	hFeatures += 'toolbar=no,location=no,status=no';
	var load = window.open('help/index.html','',hFeatures);
}

/******************************************************************************/
/**                                                                          **/
/** support() - Used by index.html and 2K5.html to open a small pop-up       **/
/**             window containing support.html.                              **/
/**                                                                          **/
/******************************************************************************/
function support() 
{
	var w = screen.availWidth;
	var h = screen.availHeight;
	var popW = 500;
	var popH = 400;
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	var sFeatures = 'width=' + popW + ',height=' + popH + ',top=' + topPos;
	sFeatures += ',left=' + leftPos + ',scrollbars=no,menubar=no,resizable=no,';
	sFeatures += 'toolbar=no,location=no,status=no';
	var load = window.open('support.html','',sFeatures);
}

/******************************************************************************/
/**                                                                          **/
/** weather() - Used by 2K5.html to open a small pop-up                      **/
/**             window containing weather.html.                              **/
/**                                                                          **/
/******************************************************************************/
function weather() 
{
	var w = screen.availWidth;
	var h = screen.availHeight;
	var popW = 320;
	var popH = 340;
	var leftPos = (w-popW)/2;
	var topPos = (h-popH)/2;
	var sFeatures = 'width=' + popW + ',height=' + popH + ',top=' + topPos;
	sFeatures += ',left=' + leftPos + ',scrollbars=no,menubar=no,resizable=no,';
	sFeatures += 'toolbar=no,location=no,status=no';
	var load = window.open('http://www.rpm-direct.net/2K5/weather.html','',sFeatures);
}

/******************************************************************************/
/**                                                                          **/
/** logout() - Used in index.html and 2K5.html to activate a logout form.    **/
/**                                                                          **/
/******************************************************************************/
function logout() 
{
	API_SignOut();
	document.qdlogout.action = "https://www.quickbase.com/db/main?act=API_SignOut";
	document.qdlogout.submit(); 
} 

/******************************************************************************/
/**                                                                          **/
/** errorMsg() - called by login to receive an error code obtained from      **/
/**              the Quickbase API response XML.  For each possible error    **/
/**              code there is a message which is displayed as an alert.     **/
/**                                                                          **/
/******************************************************************************/
function errorMsg (e)
{
	var msg = "";
	switch(e)
	{
		case '1':			// Unknown error
			msg =  "Unknown error";
			break;
		case '2':			// Invalid input
			msg =  "Invalid input";
			break;
		case '3':			// Insufficient Permissions
			msg =  "You do not have permission to perform this operation.\n";  
			msg += "Please contact technical support.";
			break;
		case '4':			// Bad ticket
			msg =  "You are not logged in.  Please log in and try again.";
			break;
		case '5':			// Unimplemented operation
			msg =  "Unimplemented operation";
			break;
		case '6':			// Syntax error
			msg =  "Syntax error";
			break;
		case '9':			// Invalid choice
			msg =  "Invalid Choice";
			break;
		case '10':		// Invalid field type
			msg =  "Invalid Field Type";
			break;
		case '11':		// Could not parse XML input
			msg =  "The form could not process your input correctly.  There is\n";
			msg += "probably a programming error in the form.  Please report this\n";
			msg += "incident to technical support.";
		case '20':		// Unknown username/password
			msg =  "We could not log you in because your login information was\n";
			msg += "incorrect.  Please make sure your username and password\n"; 
			msg += "are correct and try again.";
			break;
		case '21':		// Unknown user
			msg =  "The username or group name you supplied cannot be found.";
			break;
		case '22':		// Sign-in Required
			msg =  "You are not logged in.  Please return to the login page \n";
			msg += "and enter your username and password.";
			break;
		case '30':		// No such record
			msg =  "The record you are trying to access does not exist.";
			break;
		case '31':		// No such field
			msg =  "The field you have specified does not exist in this table.";
			break;
		case '32':		// No such database
			msg =  "The database you specified does not exist.";
			break;
		case '33':		// No such query
			msg =  "The query you specified cannot be found.";
			break;
		case '34':		// You cannot change the value of this field
			msg =  "You cannot change the value of this field.";
			break;
		case '36':		// Cloning error
			msg =  "You do not have permission to copy this project.";
			break;
		case '50':		// Missing required field
			msg =  "You have left a required field blank.  Please supply a\n";
			msg += "value for all required fields, then try again.";
			break;
		case '60':		// Update conflict detected
			msg =  "Update Conflict Detected";
			break;
		case '70':		// Account size limit exceeded
			msg =  "Account size limit has been exceeded";
			break;
		case '71':		// Database size limit exceeded
			msg =  "Datbase size limit has been exceeded";
			break;
		case '101':		// No such database
			msg =  "You do not have permission to access the specified table.";
			break;
		default:		// If any error codes exist which are not listed in the API 
						// reference, this message appears.
			msg =  "This process resulted in an error code of " + e + ".\n";
			msg += "Please report this to technical support.";
			break;
	}
	alert (msg);
}

/******************************************************************************/
/**                                                                          **/  
/** populateDropDown() - Used by 2K5.html to write the list of <option> tags **/
/**                      in the "My Projects" dropdown menu.  A call is made **/
/**                      API_GrantedDBs() to obtain the names and IDs of all **/
/**                      the 2K5 projects the user has access to.            **/
/**                                                                          **/
/******************************************************************************/
function populateDropDown()
{
	var xmlDoc = API_GrantedDBs(0);
	var errCode = xmlDoc.getElementsByTagName('errcode').item(0).childNodes.item(0).nodeValue;
	if (errCode == 0)
	{
		var databases = xmlDoc.getElementsByTagName("dbinfo");
		for (var i = 0; i < databases.length; i++)
		{
			var db = databases.item(i);
			var dbName = db.getElementsByTagName("dbname").item(0).childNodes.item(0).nodeValue;
			if (dbName.length > 65)
			{
				dbName = dbName.substring(0, 65) + "...";
			}
			// This makes certain applications not show up on the drop-down. 
			// bakfexks2 = RPM Portal Source 
			// beutzzttq = Project Management Protocol Template
			// bcj52mskr = Project Management Protocol with ATBs Template
			// bfjnrkciv = Blank Project Template
			// ba6hzpqfx = Sales Protocol Template (deprecated)
			var dbID = db.getElementsByTagName("dbid").item(0).childNodes.item(0).nodeValue;
			if ((dbID != "bakfexks2") && (dbID != "beutzzttq") && (dbID != "bcj52mskr") && (dbID != "bfjnrkciv") && (dbID != "ba6hzpqfx"))
			{
				document.write("<option value='" + dbID + "'>" + dbName + "</option>");
			}
		}
		document.close();
	}
	else
	{
		errorMsg(errCode);
	}
}

/******************************************************************************/
/**                                                                          **/
/** deleteProject() - used by my_projects.php to call API_DeleteDatabase()   **/
/**                   and process the response.  The user is presented with  **/
/**                   a prompt to either delete the project or cancel.  If   **/
/**                   the project is successfully deleted, it is removed     **/
/**                   from the "My Projects" menu                            **/
/**                                                                          **/
/******************************************************************************/  
function deleteProject(id, name)
{
	var msg = "You are about to delete the project:\n\n" + name; 
		+ "\n\nOnce it is deleted you will not be able to recover any of the\n" 
		+ "data in this project.  Are you sure you want to delete?"; 
	
	if (confirm(msg))
	{
		var xmlResponse = API_DeleteDatabase(id);
		var errCode = xmlResponse.getElementsByTagName('errcode').item(0).childNodes.item(0).nodeValue;
		
		if (errCode == "0")
		{
			alert(name + " has been deleted.");
			var opts = parent.document.getElementById("dropDown").options;
			for (var i = 0; i < opts.length; i++)
			{
				if (opts[i].value == id)
				{
					opts[i] = null;
					break;
				}
			}
			location.href="my_projects.php";
		}
		else if (errCode == "3")
		{
			alert("You do not have permission to delete " + name + ".\n\n"  
				+ "To delete this project you must first request permission from "
				+ "the owner of the project.");
			
			alert(name + " has not been deleted.");
		}
		else
		{
			errorMsg(errCode);
			alert(name + " has not been deleted.");
		}
	}
	else
	{
		alert(name + " has not been deleted.");
	}
}

/******************************************************************************/
/**                                                                          **/
/** verify() - used by addnews.htm and editnews.php to check that there      **/
/**            actually is a news item to post.                              **/
/**                                                                          **/
/******************************************************************************/
function verify(f) 
{
	if (f.news_item.value=="") 
	{
		var themessage = "Please write some news before trying to save.";
		alert(themessage);
		return false;
	}
	else  
	{
		return true;
	}
}

/******************************************************************************/
/**                                                                          **/
/** addNews() - Used in addnews.html to add news records to the News table   **/
/**             on 2K5 Portal Files.                                         **/
/**                                                                          **/
/******************************************************************************/
function addNews(f)
{
	var newsURL = "news.php"
	var newsTable = "baktavx7y";
	var fields = new Array();
	
	fields['16']  = f.category.value;
	fields['6']   = f.news_item.value;
	
	if (f.fso.checked)
	{
		fields['19'] = 1;
	}
	
	if (f.customer.checked)
	{
		fields['20'] = 1;
	}
	
	var xmlDoc = API_AddRecord(newsTable, fields);
	errcode = xmlDoc.getElementsByTagName("errcode").item(0).childNodes.item(0).nodeValue;
	
	if (errcode == 0)
	{
		location.href = newsURL;
	}
	else
	{
		errorMsg(errcode);
	}
}

/*******************************************************************************/
/**                                                                           **/
/** editNews() - used by editnews.php                                         **/
/**                                                                           **/
/*******************************************************************************/
function editNews(f, rid)
{
	var newsTable = "baktavx7y";
	var fields = new Array();
	fields['16'] = f.category.value;
	fields['6'] = f.news_item.value;
	fields['19'] = new Number(f.fsos.checked);
	fields['20'] = new Number(f.customers.checked);
	var xmlDoc = API_EditRecord(newsTable, rid, fields);
	var errcode = xmlDoc.getElementsByTagName("errcode").item(0).childNodes.item(0).nodeValue;
	if (errcode == 0)
	{
		location = "news.php";
	}
	else
	{
		errorMsg(errcode);
	}
}

/*******************************************************************************/
/**                                                                           **/
/** deleteNews() - used by editnews.php                                       **/
/**                                                                           **/
/*******************************************************************************/
function deleteNews(rid)
{
	if (confirm("Are you sure you want to delete this news item?"))
	{
		var newsTable = "baktavx7y";
		xmlDoc = API_DeleteRecord(newsTable, rid);
		errcode = xmlDoc.getElementsByTagName("errcode").item(0).childNodes.item(0).nodeValue;
		if (errcode == 0)
		{
			alert("The news item has been deleted.");
			location = "news.php";
		}
		else
		{
			errorMsg(errcode);
			alert("The news item was not deleted.");
		}
	}
}

