/* JS by Ola Imerslund */
/* September 24, 2009*/
/* Ola tester svn-commit! */

/*
 * 
 * Toggles visibility. Has a link that toggles visibility.
 * Checks whether div id="message" is present, if so: panel is visible anyway.
 */

/*
 ********************************************
 * Variables ********************************
 ******************************************** 
 */
var get_parameter = 'logoff';
var getKey_message = 'message';
var getKey_hash = '#';
var folderName = 'folder';
var debug;
//debug = true;
/* CSS relevant names */
var text_username = 'Brukernavn';
var text_password = '#';
var id_username = 'username-field';
var id_password = 'password-field';
var id_extra_password = 'password-extra-field';
var id_fieldset_password = 'password-fields';
var id_logonPanel = 'logonPanel';
var id_showPWbox = 'showPW';
var id_inputFields = 'inputFields';
var id_cancelCross = 'cancelCross';
var id_logonLink = 'logonLink';
var id_logonButton = 'logonButton';
var id_logoffLink = 'logoffLink';
var class_invisible = 'invisible';
var class_visible = 'visible';
var class_block = 'block';
var get_parameterSuffix = '=';
var paramName = get_parameter+get_parameterSuffix;

/*
 ********************************************
 * Functions ********************************
 ******************************************** 
 */

window.addEvent('domready', function() {
	init_logonbox();//må utkommenteres i utv. Hva med test?
})//addEvent

/*
 * Initiates the page, depending on whether user is logged in.
 */
function init_logonbox() {
	//Check whether this script can be run:
	if($(id_username) !== null) {
		switch(true) {
			case $(id_logonPanel) !== null:
			case $(id_cancelCross) !== null:
			//if user is not logged in: show Logon button.
			case $(id_logonLink) !== null:
				showLogOnLink();
			break;
			//if user is logged in: insert user name in Logout link.
			case $(id_logoffLink) !== null:
				alterLogoffLink();
			break;
		} //switch
	} //if 
} //initiate

/*
 * Initiates $('toggleLogonPanel') link
 * Makes $('logonPanel') invisible.
 */
function showLogOnLink() {
	var is_message = get_value(getKey_message);
	insertPWCheckbox();
	setUsernameAndPasswordValue();
	//if there is no error message: hide logon panel
	//enable the logon link
	//must be enabled even if logon panel is hidden. Otherwise it will fail when an error message is shown.
	$(id_logonLink).href= 'javascript: showLogOnPanel();';
	if(is_message.length < 1) {
		//hides logon panel
		hideLogOnPanel();
	} else {
		showLogOnPanel();
	} //if
} //showLogOnLink

/*
 * Makes $('logonPanel') visible and enables $('cancelCross').
 * Inserts value in $('username') field, if any. 
 */
function showLogOnPanel() {
	var user = get_value(get_parameter);
	//makes $('logonPanel') visible
	$(id_logonPanel).className = class_block;
	//enables click outside $('logonPanel') to hide it
	addOutsideClickEvent();
	//enables $('cancelCross')
	$(id_cancelCross).onmouseup = function () {
		hideLogOnPanel();
	}
//	$(id_cancelCross).href = 'javascript: hideLogOnPanel();';

	setVisibleClassName(id_cancelCross);
	//inserts value in $('username') field, if any.
	//TODO: obsolete in new mml version
	if(user !== '') {
		$(id_username).value = user;
	}//if
}//showLogonPanel


/*
 * Enables click outside $('logonPanel') to hide it
 * 
 */
function addOutsideClickEvent() {
	//document.html.addEvent('click', function(){//does not work in any IE
	document.addEvent('click', function(){//works as expected from above in IE6/7, correctly otherwise.
			hideLogOnPanel();
	});
	$(id_logonPanel).addEvent('click', function(event){
		event.stopPropagation();
	});
} //addOutsideClickEvent

/*
 * Sets correct element classname for visibility.
 */
function setVisibleClassName(elementId) {
	$(elementId).className = class_visible;
} //setClassName

/*
 * While initiating: 
 * Make $('logonPanel') invisible. If there is no 
 * 	checkbox for altering password visibility:
 * 	make one.
 */
function hideLogOnPanel() {
	$(id_logonPanel).className = class_invisible;
}//hideLogOnPanel


/*
 * Makes a checkbox with label, for altering password visiblity.
 */
function insertPWCheckbox() {
	var fields;
	var showPWbox;
	var showPWboxLabel;
	var type_showPWbox = 'checkbox';
	//make the box
	var advisoryText_PWbox = 'Vis passordet som tekst';
	showPWbox = document.createElement('input');
	showPWbox.setAttribute('type',type_showPWbox);
	showPWbox.setAttribute('name',id_showPWbox);
	showPWbox.setAttribute('id',id_showPWbox);
	showPWbox.alt = advisoryText_PWbox;
	showPWbox.title = advisoryText_PWbox;
	//IE hack: this way we can listen for changes
	showPWbox.onclick = function () {
		alterPasswordVisibility();
	}

	//make the box label
	showPWboxLabel = document.createElement('label');
	showPWboxLabel.setAttribute('id',id_showPWbox+'Label');
	showPWboxLabel.htmlFor = id_showPWbox;
	showPWboxLabel.appendChild(document.createTextNode('Vis passordet'));
	showPWboxLabel.title = advisoryText_PWbox;
	
	fields = $(id_fieldset_password);
	fields.appendChild(showPWbox);
	fields.appendChild(showPWboxLabel);
} //insertPWCheckbox

function initiateExtraPasswordField() {
	var currentText = $(id_password).value;
	if(currentText == text_password) {
		$(id_extra_password).value = $(id_password).value;
	} //if
	$(id_extra_password).addEvents({
		'focus': function(){ if (this.value == text_password) this.value = ''; },
		'blur': function(){  if (!this.value) this.value = text_password;  }
	});
}//initiateExtraPasswordField


/*
 * Shows a visible password,
 * and hides the original password field.
 */
function makeExtraPW() {
	var fields = $(id_fieldset_password);
	var extraPW = document.createElement('input');
	var name_extraPW = 'password_visible';
	var id_extraPW = id_extra_password;
	var text_extraPW = $(id_password).value;
	var timeStamp = new Date().getTime();
	
	$(id_password).className = class_invisible;
	//make the box
	extraPW.setAttribute('autocomplete','off');
	extraPW.setAttribute('name',name_extraPW+'_'+timeStamp);
	extraPW.setAttribute('id',id_extraPW);
	fields.appendChild(extraPW);
	//IKKE la noen se noe som er skrevet inn fra før!!!
//	$(id_extra_password).value = $(id_password).value;
	initiateExtraPasswordField();
	
	//IE hack: this way we can listen for changes
	$(id_extra_password).onkeyup = function () {
		updatePW();
	}
	//	$(id_extra_password).setAttribute('onkeyup','javascript: updatePW();');
} //makeExtraPW

/*
 * Updates the original password field value with that of the visible password input. 
 */
function updatePW() {
	$(id_password).value = $(id_extra_password).value;
} //updatePW

/*
 * Destroys the visible password field,
 * and shows the original password field.
 */
function removeExtraPW() {
	var fields = $(id_fieldset_password);
	var id_extraPW = id_extra_password;
	fields.removeChild($(id_extraPW));
	$(id_password).className = class_visible;
	//fjern form.onsubmit
} //removeExtraPW

/*
 * Sets default username and password in input fields.
 */
function setUsernameAndPasswordValue() {
	$(id_username).setAttribute('value',text_username);
	$(id_password).setAttribute('value',text_password);
}//setUsernameAndPasswordValue

/*
 * Alters password visiblity.
 */
function alterPasswordVisibility() {
	if($(id_showPWbox).checked !== false) {
		makeExtraPW();
	} else {
		removeExtraPW();
	} //if
}//alterPasswordVisibility

/*
 * Replaces default value '1' from logoff link parameter 'logoff' with current user's username.
 * TODO: obsolete in new mml version
 */
function alterLogoffLink() {
	var link = $(id_logoffLink).href;
	var paramValue = getParamValue(link);
	var user = $(id_username).innerHTML;
	var paramNew = paramName+user;
	if(user !== '') {
		link = link.replace(paramValue,paramNew);
		$(id_logoffLink).href = link;
	}//if
}//alterLogoffLink


/*
 ********************************************
 * Auxiliary functions **********************
 ******************************************** 
 */

/*
 * Finds value for a parameter in a specified link.
 * 
 * @param link	The specified link
 * @return 		Value of the wanted parameter 
 */
function getParamValue(link) {
	var paramPos;
	var folderPos;
	var paramLength;
	var paramValueLength;
	var paramValuePos;
	var paramValue;
	paramPos = link.search(paramName);
	paramLength = paramName.length;
	//'folder' has a '?' or a '&' preceding it.
	folderPos = link.search(folderName)-1;
	paramValueLength = folderPos - (paramPos+paramLength);
	paramValuePos = paramPos+paramLength;
	paramValue = paramName + link.substr(paramValuePos,paramValueLength);
	return paramValue;
} //paramData

/*
 * Fetches value of a specified parameter in the current URL (GET parameter).
 * Returns "" if no value is found.
 * 
 * @param name	Name of the parametere whose value we look for
 * @return 		The parameter's value 
 */
function get_value(param_name) {
	name = param_name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	switch(true) {
		case results == null:
		case results[1] == '':
		case results[1] == '1':
		case results[1] == 1:
		case results[1] == 'null':
			return "";
			break;
		default:
			return results[1];
			break;
	} //switch
}//get_value

function is_key(param_name) {
	var results = window.location.href.search(param_name);
	return results;
}