// requires Prototype version 1.6 or greater (http://www.prototypejs.org)

function getCookies()
{
	var cookies = window.document.cookie.split("; ");
	var result = new Array();

	//window.alert("splitting cookies");

	var tempCookieName = null;
	var tempCookieValue = null;

	for (var index = 0; index < cookies.length; index++)
	{
		tempCookieName = cookies[index].split("=")[0];
		tempCookieValue = cookies[index].split("=")[1];

		result.push({ name: tempCookieName, value: tempCookieValue });
	}

	return result;
}

function parseQueryString()
{
	var queryString = window.location.search;
	var result = new Hash();

	if (queryString && queryString.length > 0)
	{
		queryString = queryString.substr(1);

		var params = queryString.split("&");

		for (var index = 0; index < params.length; index++)
		{
			result.set(params[index].split("=", 2)[0], params[index].split("=", 2)[1]);
		}
	}

	return result;
}

function reloadPageWithQueryParams(queryParams)
{
	if (queryParams && Object.isHash(queryParams))
	{
		queryParams.unset("msg");
				
		var queryStringStartIndex = window.location.href.indexOf("?");
		
		if (queryStringStartIndex > -1)
		{
			var queryString = queryParams.toQueryString();
			var newURL = window.location.href.substring(0, queryStringStartIndex);
			
			if (!queryString.blank())
			{
				newURL = newURL + "?" + queryString;
			}
			
			window.location = newURL;
		}
	}
}

function checkEmailStatus()
{
	var queryParams = parseQueryString();
	var emailLink = $('emailLink');
	var	origContents = null;
	
	if (!emailLink)
	{
		return;
	}
	
	switch (queryParams.get("msg"))
	{
		case "EMAILSENT":
		{
			origContents = emailLink.childElements();
			origContents.each(function(item) {
				item.remove();
			});
			
			Effect.Pulsate("emailLink", { duration: 4, pulses: 4, beforeStart: function(effect) {
				emailLink.update("Email Sent");
				emailLink.addClassName("successInfoText");
			},
			afterFinish: function(effect) {
				emailLink.update("");
				emailLink.removeClassName("successInfoText");
				origContents.each(function(item) {
					emailLink.insert(item);
				});
			},
			queue: 'front'});
			
			Effect.Appear("emailLink", { queue: 'end' , afterFinish: function(effect) {
				reloadPageWithQueryParams(queryParams);
			}});
			break;
		}
		
		case "EMAILNOTSENT":
		{
			origContents = emailLink.childElements();
			origContents.each(function(item) {
				item.remove();
			});

			Effect.Pulsate("emailLink", { duration: 4, pulses: 4, beforeStart: function(effect) {
				emailLink.update("Email Not Sent");
				emailLink.addClassName("errorInfoText");
			},
			afterFinish: function(effect) {
				emailLink.update("");
				emailLink.removeClassName("errorInfoText");
				origContents.each(function(item) {
					emailLink.insert(item);
				});
			},
			queue: 'front'});

			Effect.Appear("emailLink", { queue: 'end' , afterFinish: function(effect) {
				reloadPageWithQueryParams(queryParams);
			}});
			break;
		}
	}
}

function isUserLoggedIn()
{
	var cookies = getCookies();
	var bLoggedIn = false;
	var bPortalNameFound = false;
	var bPortalSessionFound = false;
	var	portalName = null;

	for (var index = 0; index < cookies.length; index++)
	{
		//window.alert("examining cookie: " + cookies[index]);
		if (cookies[index].name == "portalName")
		{
			//window.alert("cookie matches");

			bPortalNameFound = true;
			portalName = cookies[index].value;
		}
		else if (cookies[index].name == "TIBCOSessionID")
		{
			bPortalSessionFound = true;
		}

		bLoggedIn = bPortalSessionFound && bPortalNameFound;

		if (bLoggedIn)
		{
			break;
		}
	}
	
	return { loggedIn: bLoggedIn, name: portalName };
}

function updateStatusText()
{
	if (!$('logout') && !$('loginRegister'))
	{
		return;
	}

	var loginStatus = isUserLoggedIn();
	
	var bLoggedIn = loginStatus.loggedIn;
	var portalName = loginStatus.name;
	
	if (!bLoggedIn)
	{
		$('logout').hide();
		$('loginRegister').style.display = "inline";
	}
	else
	{
		var welcomeElem = window.document.getElementById("portalWelcome");
		
		if (welcomeElem)
		{
			welcomeElem.className = "successInfoText";
			welcomeElem.innerHTML = "Welcome " + portalName;
			$('loginRegister').hide();
			$('logout').style.display = "inline";
		}
	}

	var queryParamHash = parseQueryString();
	var	bErrText = false;
	var errText = null;

	switch (queryParamHash.get("msg"))
	{
		case "USERNOTFOUND":
		{
			bErrText = true;
			errText = "Invalid login";
			break;
		}

		case "OK":
		{
			bErrText = false;
			break;
		}

		case "OLDPASSWORDINVALID":
		{
			bErrText = true;
			errText = "Old password is invalid";
			break;
		}

		case "USERNOTACTIVATED":
		{
			bErrText = true;
			errText = "User not activated";
			break;
		}

		case "ACTIVATIONEMAILSENT":
		{
			bErrText = false;
			errText = "Activation email has been sent";
			break;
		}

		case "USERACTIVATED":
		{
			bErrText = false;
			errText = "User has been activated";
			break;
		}

		case "USERALREADYREGISTERED":
		{
			bErrText = true;
			errText = "User is already registered";
			break;
		}
	}

	$('portalWelcome').className = (bErrText) ? "errorInfoText" : "successInfoText";

	if (errText)
	{
		$('portalWelcome').innerHTML = errText;
	}
}

function resolveURLToServer(rootRelativeURL)
{
	if (!rootRelativeURL)
	{
		rootRelativeURL = "/";
	}

	if (rootRelativeURL.toLowerCase().startsWith("http:") || rootRelativeURL.toLowerCase().startsWith("https:"))
	{
		return rootRelativeURL;
	}

	var serverURL = window.location.href;
	var serverHostIndex = serverURL.indexOf(window.location.hostname);
	var serverURLBase = null;
	
	if (window.location.pathname && !window.location.pathname.strip().empty())
	{
		serverURLBase = serverURL.substring(0, serverURL.indexOf("/", serverHostIndex));
	}
	else
	{
		serverURLBase = serverURL;
	}
	
	return serverURLBase + rootRelativeURL;
}

Form.Element.Methods.resolveValueToServer = function(element) {
	element = $(element);
	
	var rootRelativeURL = element.value;
	
	if (!rootRelativeURL)
	{
		rootRelativeURL = "/";
	}
	
	if (rootRelativeURL.toLowerCase().startsWith("http:") || rootRelativeURL.toLowerCase().startsWith("https:"))
	{
		return element;
	}
	
	var serverURL = window.location.href;
	var serverHostIndex = serverURL.indexOf(window.location.hostname);
	var serverURLBase = null;

	if (window.location.pathname && !window.location.pathname.strip().empty())
	{
		serverURLBase = serverURL.substring(0, serverURL.indexOf("/", serverHostIndex));
	}
	else
	{
		serverURLBase = serverURL;
	}
		
	element.value = String(serverURLBase + rootRelativeURL);
	
	return element;
};

Element.addMethods();

// got this code from http://jehiah.cz/archive/firing-javascript-events-properly
// for manually firing native javascript events
function fireEvent(element,event)
{
    if (Prototype.Browser.IE)
    {
        // dispatch for IE
        var evt = document.createEventObject();
        return element.fireEvent('on'+event, evt)
    }
    else
    {
        // dispatch for firefox + others
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}