// JavaScript For Setting a Cookie

// Days and Hours for the cookie duration must be passes when the you call the setCookie function.

// Set the default code used for this enterence. The function will set this code if none is passed to the function.
var defaultCode = '1';

// Set the default number of days and hours for the cookie to exist
var defDay = 365;
var defHour = 0;

// Set the unchangable part of the application link. The code will be added to the end of this based on the cookie value.
// Use '<code>' where you want the entrance code to be placed.
var baseAddr_ApplyOnline = 'https://salukinet.siu.edu/cgi-bin/admit/sisadmi.cgi?sys_template=mtaplgsni&sys_logon=1&market=<code>';
var baseAddr_DownloadApplication = 'http://www.siuc.edu/~ips/INTL<code>/ForAP<code>.html';

// If the cookie is unsuccessful, what link should be used instead?
var defaultAddr_ApplyOnline = 'https://salukinet.siu.edu/cgi-bin/admit/sisadmi.cgi?sys_template=mtaplgsni&sys_logon=1&market=1';
var defaultAddr_DownloadApplication = 'http://www.siuc.edu/~ips/INTL1/ForAP1.html';

// When calling this function, pass three parameters: Entrance Code as a string, Days as a number, Hours as a number
// e.g. "javascript:setCookie( 'H', 30, 0 );" for setting a cookie with the entrance code "H" that will be active for 30 days.

function setCookie(entranceCode, durationDays, durationHours) {	
	if (entranceCode == '') {entranceCode = defaultCode;}
	var date = new Date();
	var dateTime  = date.getTime() + (durationDays * 24 * 60 * 60 * 1000) + (durationHours * 60 * 60 * 1000);	
	var expDate = new Date(dateTime);
	expireString = "expires=" + expDate.toGMTString();	
	document.cookie = 'entranceCode=' + entranceCode + '; ' + expireString;
}

function clearCookie() { // Sets the expiration of the cookie to the past, so it is cleared.
	if (document.cookie.length > 0) {
		var d = new Date();
		d = d.getTime() - 1000000;
		var neg = new Date(d);
		document.cookie = 'entranceCode=0; expires=' + neg.toGMTString();
	}
}

function checkCookie() {
	var entranceCode = '';
	if (document.cookie.length > 0) {	// There is a cookie
		var offset = document.cookie.indexOf('entranceCode=');
		if (offset != -1) {		// The entrance variable is set
			offset += 13;
			end = offset + 1	// Code can be only 1 character long!
			entranceCode = unescape( document.cookie.substring(offset, end));
		} 
	}
	return (entranceCode);	// Returns nothing if no valid cookie value exists
}

function makeLink(linkType) {
	var newAddr = '';
	var searchname = "entranceCode=";
	var entrance = checkCookie();
	
	if (entrance.length = 0) { entrance = defaultCode; }
		
	
	// return the results
	if (entrance) {
		if (linkType == 'ApplyOnline') {
			newAddr = baseAddr_ApplyOnline.replace(/<code>/g, entrance);
		} else {
			newAddr = baseAddr_DownloadApplication.replace(/<code>/g, entrance);
		}
		return( newAddr );
	} else {
		return;	
	}
}
