// JavaScript Document
/************************************************************************************************
 *			MAIN POPUP CODE 
 ************************************************************************************************/
var mainWindow, bgWindow;
var boxWidth, boxHeight;
var pageWidth, pageHeight;
var scrolledX, scrolledY;
var infoDisplayed = false;
var infoString = "We have a weekly drawing in which registered individuals can win a variety of prizes.";
var commentString = "<!-- more info -->";
var registrationStates = {registered: 3651, notRegistered: null, delay: 5, never: 3650};
var fName = null;
var lName = null;
var userEmail = null;
function openWindow(mainWindowId, bgWindowId, width)
{
	// set the ids, width and height to golbal vars
	mainWindow = mainWindowId;
	bgWindow = bgWindowId;
	boxWidth = width;
	
	// Sizes based on Firefox rendering, adding 15px to compensate for different IE rendering and 
	// keep similar look
//	if(navigator.appName == "Microsoft Internet Explorer")
//		boxHeight += 15;
	
	// Set height and width
	document.getElementById(mainWindow).style.width = boxWidth + "px";
	//document.getElementById(mainWindow).style.height = "auto";
	document.getElementById(bgWindow).style.width = 100 + "%";
	document.getElementById(bgWindow).style.height = 100 + "%";


	// Set opacity to zero to hide window
	setOpacity(mainWindow, 0);
	setOpacity(bgWindow, 0);
	// Make visible
	document.getElementById(mainWindow).style.display = "block";
	document.getElementById(bgWindow).style.display = "block";
	// Calculate height
	boxHeight = document.getElementById(mainWindow).offsetHeight;
	// Position
	centerPopup();
	// Fade in
	fadeIn(8); // change back to 8
	

	// Keep the popup in the center
	document.body.onscroll = centerPopup; 
	window.onscroll = centerPopup;	


}

function closeWindow(registrationState)
{
	// Fade window out
	fadeOut(8);
	// Hide window
	setTimeout("document.getElementById(mainWindow).style.display = \"none\"", 800);
	setTimeout("document.getElementById(bgWindow).style.display = \"none\"", 800);
	var text;
	// if the person registered, set the cookie text to be "Registered, firstName, lastName, email", and show text welcoming them to UL
	if(registrationState == registrationStates.registered)
	{
		text = "Registered," + fName + "," + lName + "," + userEmail;
		document.getElementById("welcome").innerHTML += "Welcome to University Living, " + fName + " " + lName;
	}
	// otherwise, we want to show the hidden text
	else
	{
		displayHiddenText();
		// record all the various states in the cookies
		if(registrationState == registrationStates.notRegistered)
			text = "Not registered";
		else if(registrationState == registrationStates.delay)
			text = "Delayed registration";
		else if(registrationState == registrationStates.never)
			text = "Never register";
		else
			text = "skipped all";
	}
	// set the cookie with the title "ULCookie", required text and expiration date
	setCookie("ULCookie", text, registrationState);
}

function centerPopup()
{
	// Determine how much the visitor had scrolled	
	if( self.pageYOffset ) 
	{
		scrolledX = self.pageXOffset;
		scrolledY = self.pageYOffset;
	} 
	else if( document.documentElement && document.documentElement.scrollTop ) {
		scrolledX = document.documentElement.scrollLeft;
		scrolledY = document.documentElement.scrollTop;
	} 
	else if( document.body ) 
	{
		scrolledX = document.body.scrollLeft;
		scrolledY = document.body.scrollTop;
	}

	// Determine the height and width of the page
	if( self.innerHeight ) 
	{
		pageWidth = self.innerWidth;
		pageHeight = self.innerHeight;
	} 
	else if( document.documentElement && document.documentElement.clientHeight ) 
	{
		pageWidth = document.documentElement.clientWidth;
		pageHeight = document.documentElement.clientHeight;
	} 
	else if( document.body ) 
	{
		pageWidth = document.body.clientWidth;
		pageHeight = document.body.clientHeight;
	}
	
	// Determine the coordinates required to center window on screen
	var leftOffset = scrolledX + ((pageWidth - boxWidth) / 2);
	var topOffset = scrolledY + ((pageHeight - boxHeight) / 2);
	
	// Place main window in center of screen
	document.getElementById(mainWindow).style.top = topOffset + "px";
	document.getElementById(mainWindow).style.left = leftOffset + "px";
	// Place background window at the top left visible corner
	document.getElementById(bgWindow).style.top = scrolledY + "px";
	document.getElementById(bgWindow).style.left = scrolledX + "px";
}

function setOpacity(element, value) 
{
	// Set opacity; two different elements depend on browser
	// Set on scale of 1-10; normalizes for different browser scales
	// 0-100 on IE, 0-1 on all others as per CSS standard
	document.getElementById(element).style.opacity = value / 10;
	document.getElementById(element).style.filter = "alpha(opacity=" + value * 10 + ")";
}

function fadeIn(speed) // high = slow; low = fast
{
	// loop that increases opacity by 0.1 every iteration
	for(var i = 0; i <= 100; i++)
	{
		// wait (speed * loop number) milliseconds before increasing opacity to next level
		setTimeout( "setOpacity(mainWindow, " + (i / 10) + ")" , speed * i)
		setTimeout( "setOpacity(bgWindow, " + (i / 20) + ")" , speed * i)
	}
}
function fadeOut(speed) // high = slow; low = fast
{
	// loop that decreases opacity by 0.1 every iteration
	for(var i = 0; i <= 100; i++)
	{
		// wait (speed * loop number) milliseconds before decreasing opacity to next level
		setTimeout( "setOpacity(mainWindow, " + ((100 - i) / 10) + ")" , speed * i);
		setTimeout( "setOpacity(bgWindow, " + ((100 - i) / 20) + ")" , speed * i);
	}
}

function openRegisterBox()
{
	// opens the popup window done this way because size is part of the paramaters (done in order to make the function reuseable);
	// this prevents too many different sizes floating around the code and provides just one place to change it
	openWindow('info_popup', 'popup_bg', 525);
}

function displayHiddenText()
{
	var targetRule;
	// Iterate through the various stylesheets and rules until we find the specific one we want, ".infodivs"
	for(l = 0; l < document.styleSheets.length; l++)
	{
		if(document.styleSheets[l].cssRules)
			var rules = document.styleSheets[l].cssRules;
		else if(document.styleSheets[l].rules)
			var rules = document.styleSheets[l].rules;
		for(i = 0; i < rules.length; i++)
		{
			if(rules[i].selectorText.toLowerCase() == ".infodivs")
			{
				targetRule = rules[i];
			}
		}
	}
	if(targetRule != null && targetRule != "")
	{
		// finally, set the display to block in order to show the text, if we found the rule
		targetRule.style.display = "block";
	}
}

/************************************************************************************************
 *			COOKIE CODE 
 ************************************************************************************************/

function checkCookie(displayWindow)
{
	// Get the text in the cookie
	var cookieText = getCookie("ULCookie");

	//Check if the cookie text is null or empty; if it is, there is no cookie and we want the user to register
	if((cookieText == null || cookieText == "") && displayWindow == true)
	{
		openRegisterBox();
	} 
	// If the cookie text contains the word "Registered", then we know the user has registered and we want to
	// welcome them back to University Living
	else if(cookieText.match("Registered"))
	{	
		var strings = cookieText.split(",");
		document.getElementById("welcome").innerHTML = "Welcome back to University Living, " + strings[1] + " " + strings[2];
	}
	// All other cases, the user has seen the registration box, but has opted out of registering, so we show him/her the 
	// hidden text asking to register or sign up for our Google Group
	else
	{
		displayHiddenText()		
	}
}

function getCookie(c_name)
{
	if (document.cookie.length > 0)
	{
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1)
		{
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) 
				c_end = document.cookie.length;
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function setCookie(c_name, content, expiredays)
{
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + " = " + escape(content) + ((expiredays == null) ? "" : "; expires= " + exdate.toGMTString());
}

/************************************************************************************************
 *			MORE INFO POPUP CODE 
 ************************************************************************************************/
 function moreInfo()
 {
	// if the more info has not yet been displayed
 	if(!infoDisplayed)
	{
		// Find comment string and replace with text
		document.getElementById(mainWindow).innerHTML = 
			document.getElementById(mainWindow).innerHTML.replace(commentString, infoString);
		// Increase padding to help separate it from all the surrounding info
		document.getElementById("moreInfo").style.padding = 15 + "px";
		// Recalculate height and recenter the window
		boxHeight = document.getElementById(mainWindow).offsetHeight;
		centerPopup();
		// Now we know it is being displayed
		infoDisplayed = true;		
	}
	else
	{
		// Find text string and replace with a comment
		document.getElementById(mainWindow).innerHTML = 
			document.getElementById(mainWindow).innerHTML.replace(infoString, commentString);
		// Decrease padding to bring the two items a bit closer instead of unusually far apart
		document.getElementById("moreInfo").style.padding = 7 + "px";
		// Recalculate height and recenter the window
		boxHeight = document.getElementById(mainWindow).offsetHeight;
		centerPopup();
		// Now we know it is not being displayed
		infoDisplayed = false;
	}
 }

/************************************************************************************************
 *			FORM VALIDATION 
 ************************************************************************************************/
function validateForm(form)
{
	var registerLaterBox = "registerLater";
	with(form)
	{
		// if the register later box has not been checked, verfiy that all the fields are filled out
		// if any field has not been filled out, ask the user to fill it out and and focus on the field
		if(!document.getElementById(registerLaterBox).checked)
		{
			if(!validateRequired(firstName, "Please fill in your first name."))
			{
				firstName.focus();
				return false;
			}
			else if(!validateRequired(lastName, "Please fill in your last name."))
			{
				lastName.focus();
				return false;
			}		// special validation for emails to also check if it is a valid emails
			else if(!validateEmail(emailForm, "Please enter a valid email."))
			{
				emailForm.focus();
				return false;
			}
			// if all the fields have been filled out, set the values to global variables to be easily accessed later
			fName = firstName.value;
			lName = lastName.value;
			userEmail = emailForm.value;
			// close the window with the state of registered
			closeWindow(registrationStates.registered);
		}
		// if the register later box has been checked
		else
		{
			// if they selected never, simply close the window with the state of never wanting to register
			if(document.getElementById("delayOptions").value == "never")
			{
				closeWindow(registrationStates.never);
			}
			// otherwise, parse the number that they chose, set delay to that value and close the window with the state of delay
			else
			{
				registrationStates.delay = parseInt(document.getElementById("delayOptions").value)
				closeWindow(registrationStates.delay);
			}
		}
	}	
}

function validateRequired(field, alertText)
{
	with(field)
	{
		// if value is empty or null, alert user and return false
		if(value == null || value == "")
		{
			alert(alertText);
			return false;
		}
		// if value has something in it, return true
		else
		{
			return true;
		}
	}
}

function validateEmail(field,alerttxt)
{
	with (field)
	{
		// get the position of "@" and "."
		apos = value.indexOf("@");
		dotpos = value.lastIndexOf(".");
		// if @ is the first char or non-existent ||
		// if . is right next to @ or non-existent; alert user and return false
		if( apos < 1 || dotpos - apos < 2)
		{
			alert(alerttxt);
			return false;
		}
		// if there is a value and it validates, return true
		else 
		{
			return true;
		}
	}
}


/*************************************
  Cookie/Registering Options:
  1. Give name, email, etc
  		Cookie text: "Registered, firstname, lastname, email"
		Expiration: 10 years
  2. Close button
  		Cookie text: "Not registered"
		Expiration: 1 day (or 0 days (deleted when browser closes)?)
  3. Remind me again in x day/weeks
  		Cookie text: "Delayed registration"
		Expiration: x days
  4. Never remind me again
  		Cookie text: "Never register"
		Expiration: 10 years
  5. 
		
  If "Never register" or "Registered" cookie found, set another with same text for another 10 years to keep cookie going
  If "Not registered", "Delayed registration" or "Never register" cookie found, display option on home page to register/take "survey"
  If "Registered", display "Welcome back, name"?

  Information requested from user:
  Name
  Email
  Contact options: Send me more information
  				   Do not send me any information
				   Enroll me in weekly prize drawing
  Remind me again in 1 day
  					 2 day
					 3 day
					 4 day
					 5 day
					 6 day
					 7 day
					 Never
  Log IP address? (Get IP address serverside in JS or PHP, create hidden input with IP address as value)

*************************************/

// CODE TO GET BOX HEIGHT AND WIDTH
//	var boxWidth = document.getElementById(mainWindow).style.getPropertyValue("width");
//	var boxHeight = document.getElementById(mainWindow).style.getPropertyValue("height");