/**
* Global variables
* ****************
*/
// Will be used for adding or removing time in done 
// and todo fields...
var gDayIncrement = 1;

// See PrivateConfig.inc.php!!
var gSelectUser = "00";

var gMaxRisk = 10;
var gMaxPriority = 10;
var gMaxWeight = 10;

var gAllIterations = {};
var gAllIterationsAndProjects = {};
var gIterationStories = {};
var gMembers = {};

var gForbiddenIds;

var gCalTaskIsOn = false;
var gCurrentCalTask;
var gToDeleteCalTask = "";

// Insert
var gCurrentInsertCount	= -1;
var gCurrentInsertType	= "";

var gIsOnModifyTask = false;

// I don't like to do this but...

var gDetectUserAgent = navigator.userAgent.toLowerCase();
var gBrowser;

if (checkIt('konqueror')) gBrowser = "Konqueror";
else if (checkIt('safari')) gBrowser = "Safari";
else if (checkIt('omniweb')) gBrowser = "OmniWeb";
else if (checkIt('opera')) gBrowser = "Opera";
else if (checkIt('webtv')) gBrowser = "WebTV";
else if (checkIt('icab')) gBrowser = "iCab";
else if (checkIt('msie')) gBrowser = "Internet Explorer";
else if (!checkIt('compatible')) gBrowser = "Netscape Navigator";
else gBrowser = "An unknown gBrowser";

function checkIt(string)
{
	var place = gDetectUserAgent.indexOf(string) + 1;
	var thestring = string;
	return place;
}

/**
* Functions
* ****************
*/

function submitInParent(form) {
	
	form.target = "xpwebMain";
	
	form.action = parent.document.location;
	form.submit();
	//window.setTimeout('closeAndReloadOpener()', 200);
	return true;
}

function closeAndReloadOpener() {
	window.opener.location.reload();
	window.close();
}

function openClose(currentClass, linkObject) {

	var openName = currentClass + " Open";
	var closedName = currentClass + " Closed";
	
	if (isOpen(currentClass, linkObject)) {
		linkObject.className = closedName;
	} else {
		linkObject.className = openName;
	}
	
}

function isOpen(currentClass, linkObject) {

	var openName = currentClass + " Open";
	
	return (linkObject.className.indexOf(openName) != -1);
	
}

function openIncluded(type, id, linkObject) {
	//alert(type  + " / " + id + " / " + link.id);
	openClose('cont', linkObject);
	chgVis('con_'+type+'_'+id);
}

function focStory(formName) {
	var priority = document.forms[formName].elements["priority"];
	populate(priority, gMaxPriority);
	var risk = document.forms[formName].elements["risk"];
	populate(risk, gMaxRisk);
	var weight = document.forms[formName].elements["weight"];
	populate(weight, gMaxWeight);
	
	var iterationId = document.forms[formName].elements["iterationId"];
	
	populateListSelect(gAllIterationsAndProjects, iterationId, true);
}

function focDelIte(formName) {
	var iterationId = document.forms[formName].elements["iterationId"];
	try {
		populateListSelect(gAllIterationsAndProjects, iterationId, false);
	} catch (e) {
	}
}


function focDelStory(formName) {
	var listStories = document.forms[formName].elements["iterationStoryId"];
	try {
		populateListSelect(gIterationStories, listStories, false);
	} catch (e) {
	}
}

function focTask(formName) {
	var iteStoryId = document.forms[formName].elements["iterationStoryId"];
	populateListSelect(gIterationStories, iteStoryId, true);
	
	var memberId = document.forms[formName].elements["memberId"];
	populateListSelect(gMembers, memberId, true);
		
	var pairId = document.forms[formName].elements["pairId"];
	populateListSelect(gMembers, pairId, true);
	
	// Validate pair id
	changeUserTasks(memberId, "pairId");
	
	document.forms[formName].elements["auto"].onclick();
	
	sigEDToUpd(formName);
	
	gIsOnModifyTask = true;
}

function populate(theInput, maxValue) {
	if (theInput.length == 1) {
		var currentOption = theInput.options[0];
		var inputValue = currentOption.value;
		theInput.options[0] = null;
		for (var i=0; i<=maxValue; i++) {
			var newOption = new Option(i, i);
			theInput.options[theInput.length] = newOption;
		}
		theInput.selectedIndex = inputValue;
	}
}

function clearListSelect(theInput) {

	
	if (theInput.className != "inv") {
	
		// last element
		var i = theInput.length - 1;
		
		// We leave ONE value
		while (theInput.length != 1) {
			if (theInput.options[i].defaultSelected != true) {
				theInput.options[i] = null;
			}
			i --;
		}
	}
}

function populateListSelect(theList, theInput, allowed) {
	
	if (theInput.length == 1) {
		
		var currentId = 0;
		var isolatedId = 0;
		
		var currentOption = theInput.options[0];
		var currentValue = currentOption.value;
		
		theInput.options[0] = null;
		
		for (var ite in theList) {
			
			var newOption = new Option(theList[ite], ite);
			
			try {
				if (eval("ite in gForbiddenIds")) {
					newOption.disabled = true;
				}
			} catch(nothing) {}
			
			if (ite == currentValue) {
				
				currentId = theInput.length;
				newOption.defaultSelected = true;
				
			} else if (ite == "0" || ite == "0_0") {
				
				// "isolated" index
				isolatedId = theInput.length;
				
			}
			
			theInput.options[theInput.length] = newOption;
			
		}
		
		if (allowed) {
			
			theInput.selectedIndex = currentId;
			
		} else {
			
			// To remove the "forbidden" option
			// (case of a "delete" menu)
			theInput.options[currentId] = null;
			
			if (currentId < isolatedId) {
				isolatedId --;
			}
			
			if (currentId != isolatedId) {
				theInput.selectedIndex = isolatedId;
			} else {
				theInput.selectedIndex = theInput.length-1;
			}
			
		}
		
	}
}

function showHidePassChange(boxObject, section) {
	
	var enabled = boxObject.checked;
	
	if (enabled) {
		
		visible(section);
		
	} else {
		
		boxObject.form.elements["password"].value = "";
		boxObject.form.elements["passwordAgain"].value = "";
		invisible(section);
		
	}
}

function alertTimeOut(timeoutTime) {
	var warningWindow = window.open('LoginTimeoutWarning.php','timeout','width=300, height=160,toolbar=false,scrollbars=no');
	window.setTimeout('alertTimeOutRiched()',timeoutTime);
}

function alertTimeOutRiched() {
	chgVis('login');
	chgVis('login1');
	window.open('LoginTimeoutRiched.php','timeout', 'width=300, height=160,toolbar=false,scrollbars=no');
}

function bl(inpT) {
	var formName = inpT.form.name;
	checkPositiveInput(formName,inpT.name,2,2);

	// If this is "done" input and "todo" is not zero, don't care...
	sigEDToUpd(formName);
	
	if (inpT.name == "todo") {
		// If todo => update real days value...
		loadFactor = getLoadFactor(document.forms[formName]);
		MM_findObj(formName+"_realTodo").innerHTML = Math.round(inpT.value * loadFactor*100)/100;
	}
}

function blLF(inpT) {
	//if (inpT.value != inpT.defaultValue) && confirmUpdateDate(inpT.form.name)) {
		checkPositiveInput(inpT.form.name,inpT.name,2,2);
	//} else {
	//	inpT.value = inpT.defaultValue;
	//}
}

function changeCombo(formName, inputName, initValue, newValue) {
	var myObject = document.forms[formName].elements[inputName][newValue];
	myObject.checked=true;
	var myDiv = MM_findObj(inputName+"_"+newValue);
	myDiv.className = 'newSetting';
	for (var i = 0; i < document.forms[formName].elements[inputName].length; i++){
		var currentObject = document.forms[formName].elements[inputName][i];
		myDiv = MM_findObj(inputName+"_"+i);
		if (currentObject.value == initValue){
			myDiv.className = 'currentSetting';
		} else {
			if (i != newValue){
				myDiv.className = 'notCurrentSetting';
			}
		}
		
	}
}

function checkPositiveInput(formName, inputName, integerMax, decimalMax) {
	var inputValue = document.forms[formName].elements[inputName].value.replace(",",".");
	var newValue = inputValue;
	var toReturn = true;
	if (inputValue == "") {
		newValue = 0;
	}
	if ((isNaN(inputValue)) || (Number(inputValue) < 0)) {
		newValue = 0;
		toReturn = false;
	} else {
		var decimalPart = "";
		var integerPart = inputValue;
		var commaIndex = inputValue.indexOf(".");
		if (commaIndex > -1) {
			integerPart = inputValue.substring(0, commaIndex);
			decimalPart = inputValue.substring(commaIndex + 1);
		}
		
		// Too big integer part
		if (integerPart.length > integerMax) {
			integerPart = Math.pow(10,integerMax) - 1;
			newValue = integerPart;
			if (decimalPart != "") {
				newValue = newValue+"."+decimalPart;
			}
			toReturn = false;
		}
		
		// Too big decimal part
		if (decimalPart.length > decimalMax) {
			if (decimalMax == 0) {
				// Integer
				newValue = integerPart;
				toReturn = false;
			} else {
				// round
				oldValue = newValue;
				newValue = Math.round(newValue*Math.pow(10,decimalMax))/Math.pow(10,decimalMax);
				toReturn = (oldValue != newValue);
			}
		}
	}
	document.forms[formName].elements[inputName].value = newValue;
	if (!toReturn) {
		document.forms[formName].elements[inputName].focus();
	}
	return toReturn;
}

function isWorkingDay(formName, day) {
	var workingPace = document.forms[formName].elements["wp"];
	return (workingPace.value.indexOf("|"+day+"|") != -1);
}

function checkUnCheckWorkingDay(formName, day, link) {
	
	var workingPace = document.forms[formName].elements["wp"];
	var value = workingPace.value + "|"+day+"|";
	var className = 'wd';
	var result = true;
	
	if (isWorkingDay(formName, day)) {
		// was a working day
		value = workingPace.value.replace("|"+day+"|", "");
		className = 'nWd';
		result = false;
	}
	
	workingPace.value = value;
	link.className = className;
	return result;
}

function clickCompletion(formName, tdPattern, newValue, yesClass) {
	var currentValue = document.forms[formName].elements['completion'].value;
	
	document.forms[formName].elements['completion'].value = newValue;
	mouseOverOutSelectCompletion(tdPattern+currentValue, '');
	
	mouseOverOutSelectCompletion(tdPattern+newValue, yesClass);
}

function isAutoEndDate(formName) {
	return document.forms[formName].elements['auto'].checked;
}

function dec(theButton, inputName) {
	var loadFactor = getLoadFactor(theButton.form);
	decPrecise(theButton, inputName, loadFactor, gDayIncrement);
}

function decPrecise(theButton, inputName, loadFactor, val) {
	theButton.form.elements[inputName].value -= val;
	bl(theButton.form.elements[inputName]);
}

function doNothing() {
	// This stupid function is necessary to fix a bug in IE6
	eval("void(0);");
}

function endDateDisabled(formName, disabled) {
	
	var minus = MM_findObj(formName + "_min");
	var plus = MM_findObj(formName + "_plus");
	var calcHtmlElement = MM_findObj(formName + "_calcEnd");
		
	var endDateInput = document.forms[formName].elements["endDate"];
	
	calcHtmlElement.disabled = disabled;
	
	if (disabled) {
		// Set "disabled" calendar image
		calcHtmlElement.className = "autoEndInv";
		minus.className = "lessMoreInv";
		plus.className = "lessMoreInv";
	} else {
		calcHtmlElement.className = "autoEnd";
		minus.className = "less";
		plus.className = "more";
	}
	
	endDateInput.disabled = disabled;
	endDateInput.className = disabled?"dis":"";
	
	minus.disabled = disabled;
	plus.disabled = disabled;
}

/*
function entsub(myform) {
	if (window.event && window.event.keyCode == 13) {
		var something = submitLoginForm();
		myform.submit();
		return false;
	} else {
		return true; 
	}
}
*/

function inc(theButton, inputName) {
	var loadFactor = getLoadFactor(theButton.form);
	incPrecise(theButton, inputName, loadFactor, gDayIncrement);
}

function incPrecise(theButton, inputName, loadFactor, val) {
	theButton.form.elements[inputName].value = 
		Number(theButton.form.elements[inputName].value) + Number(val);
	bl(theButton.form.elements[inputName]);
}

function invisible(nomObject) {
	var myObject;
	myObject = MM_findObj(nomObject);
	if (myObject == null) {
		alert("Unable to locate HTML element: " + nomObject);
		return false;
	}
	return invisibleObj(myObject);
}

function invisibleObj(myObject) {
	myObject.className	= 'inv';
	myObject.style.display	= 'none';
	return true;
}

function isType(formName, type) {
	return (formName.indexOf(type) != -1)
}

function isInsert(formName) {
	return (formName.indexOf("insert") != -1)
}

function modifyLoginUserSelectModern() {
	var loginForm = document.forms['loginForm'];
	var theValue = loginForm.elements['userSelect'].value;
	if (theValue == 'admin' || theValue == 'textUser') {
		visible('textLogin');
		loginForm.elements['textUsername'].focus();
	} else {
		invisible('textLogin');
		loginForm.elements['password'].focus();
	}
}

function MM_findObj(n, d) {
	var p,i,x;
	
	if (d == undefined) {
		d = document;
	}
	
	var directAccess = (x = d[n]);
	
	// Direct access
	if (directAccess) {
		return x;
	}
	
	
	// d.all
	if(d.all) {
		x = d.all[n];
		if (x != null) {
			return x;
		}
	}
	
	// By id
	if(d.getElementById) {
		x = d.getElementById(n);
		if (x != null) {
			return x;
		}
	}
	
	// Each form
	for (i=0; i<d.forms.length; i++) {
		x = d.forms[i][n];
		if (x != null) {
			return x;
		}
	}
	
	// Each div
	if (d.layers) {
		for(i=0; i<d.layers.length; i++) {
			x = MM_findObj(n, d.layers[i].document);
			if (x != null) {
				return x;
			}
		}
	}
	
	return null;
}

function popup(page) {
	//window.open(page,'popup');
	window.open(page, 'popup', 'toolbar=false, scrollbars=yes, resizable=yes');
}

function resetForm(formName) {
	// If task INSERT, we want to remember iteration and story Id (which is NOT
	// the HTML init value...)
	var taskInsert = isType(formName, "task") && isInsert(formName);
	
	if (taskInsert) {
		iteStory = document.forms[formName].elements["iterationStoryId"].value;
	}
		
	document.forms[formName].reset();
	
	if (taskInsert) {
		document.forms[formName].elements["iterationStoryId"].value = iteStory;
	}
}

function res(formName) {
	// Full reset
	resetForm(formName);
	
	var isTask = isType(formName, "task");
	
	// For iterations and tasks, reset working days
	if (isTask || isType(formName, "iteration")) {
		resetWorkingDays(formName);
	}
	
	
	// For tasks, execute code depending on auto or not...
	if (isTask) {
		// Re init menus
		
		var iteStoryId = document.forms[formName].elements["iterationStoryId"];
		clearListSelect(iteStoryId);
		
		var memberId = document.forms[formName].elements["memberId"];
		clearListSelect(memberId);
		focTask(formName);
	}
}

function getIteIdFromTask(formName) {
	// If insert, we affect working days from iteration...
	var iteStoryId = document.forms[formName].elements["iterationStoryId"].value;
	return iteStoryId.substring(0, iteStoryId.indexOf("_"));
}

function getIteFormFromTask(formName) {
	var iteId = getIteIdFromTask(formName);
	
	var parentType = "iteration";
	
	if (iteId == 0) {
	
		// Iteration id == 0 => this is the planning itself (isolated task)
		parentType = "planning";
		
	}
	
	var iteFormName = "mod_"+parentType+"_"+iteId+"_info";
	
	return document.forms[iteFormName];
}

function dbPrintUpdate(formName) {
	document.forms[formName].elements['switch'].value += 'print';
	return sub(formName);
}

function resetWorkingDays(formName) {
	var itemId = document.forms[formName].elements["id"].value;
	
	var bIsInsert = isInsert(formName);
	
	var type;
	
	if (isType(formName, "task")) {
		var type = "task";
		
		if (bIsInsert) {
			iteForm = getIteFormFromTask(formName);
			
			if (iteForm != undefined) {
				// Get wd from iteration...
				document.forms[formName].elements["wp"].value = iteForm.elements["wp"].value;
			}
		}
		
	} else {
		var type = "iteration";
	}
	
	for (var i in gAllDays){
		
		var dayToCheck = gAllDays[i];
		
		if (dayToCheck != '') {
			
			var link = MM_findObj(type+"_"+itemId+"_"+dayToCheck);
			
			checkUnCheckWorkingDay(formName, dayToCheck, link);
			checkUnCheckWorkingDay(formName, dayToCheck, link);
		}
	}
}

/**
 * Change from and to "mini display"
 */
function mini(type, id) {
	chgVis('usual_'+type+'_'+id, 'mini_'+type+'_'+id);
}

function itemIsChecked(type, id) {
	var myCheck;
    myCheck = MM_findObj("check_"+type+"_"+id);
    
    if (myCheck == undefined) {
		return false;
	}
	
    return myCheck.checked;
}

function checkAll(containerId, type, myInput) {
	var myContainer;
	myContainer = MM_findObj(containerId);
	
	var checkOrUnCheck = myInput.checked;
	    
    // Get all the included checkboxes
    var includedItems = myContainer.getElementsByTagName('input');
    		
	// Get child elements with that tagName
	
	for(var j=0; j<includedItems.length; j++) {
		var node = includedItems[j];
					
		if (node.className == "checkItem" && node.id != undefined) {
		
			var sepIndex = node.id.indexOf("_");
			
			var incRest = node.id.substring(sepIndex + 1);
						
			sepIndex = incRest.indexOf("_");
			
			var incType = incRest.substring(0, sepIndex);
			
			if (incType == type) {
							
				node.checked = checkOrUnCheck;
				
			}
		}
	}
}

function miniAll(containerId, type, miniOrMaxi, openOrClose) {
	var myContainer;
    myContainer = MM_findObj(containerId);
    
    // Get all the included links
    //includedItems = myContainer.getElementsByTagName('a');
    var includedItems = myContainer.getElementsByTagName('div');
    		
	// Get child elements with that tagName
	for(var j=0; j<includedItems.length; j++) {
		var node = includedItems[j];
					
		if (node.id != undefined) {
			var sepIndex = node.id.indexOf("_");
			if (sepIndex > -1) {
				var incMini = node.id.substring(0, sepIndex);
				
				var incRest = node.id.substring(sepIndex + 1);
				
				if (incMini == "mini") {
				
					sepIndex = incRest.indexOf("_");
					
					var incType = incRest.substring(0, sepIndex);
					
					if (incType == type) {
					
						var incId = incRest.substring(sepIndex + 1);
						
						var incIsMini = (node.className == "vis");
						
						if (itemIsChecked(incType, incId)) {
						
							if (openOrClose == undefined || openOrClose) {
						
								if ((incIsMini && !miniOrMaxi)
									|| (!incIsMini && miniOrMaxi)) {
								
									mini(incType, incId);
																
								}
								
							}
							
							if (openOrClose != undefined) {
								
								//alert(openOrClose);
							
								var linkObject = MM_findObj("lkopen"+incType+incId);
								
								if (linkObject != undefined) {
								
									incIsOpen = isOpen('cont', linkObject);
									
									if ((incIsOpen && !openOrClose)
										|| (!incIsOpen && openOrClose)) {
									
										openIncluded(incType, incId, linkObject);
										
									}
								}
							}
						}
					}
				}
			}
		}
	}
}

function getAbsolutePos(el) {
	var SL = 0, ST = 0;
	var is_div = /^div$/i.test(el.tagName);
	if (is_div && el.scrollLeft)
		SL = el.scrollLeft;
	if (is_div && el.scrollTop)
		ST = el.scrollTop;
	var r = { x: el.offsetLeft - SL, y: el.offsetTop - ST };
	if (el.offsetParent) {
		var tmp = getAbsolutePos(el.offsetParent);
		r.x += tmp.x;
		r.y += tmp.y;
	}
	return r;
}

function showCalTask(id, element, plusx, plusy) {

	if (!gIsOnModifyTask) {
		id = "calTask"+id;
		refreshCalTask(id);
		var myTask = MM_findObj(id);
		var s = myTask.style;
		s.position = "absolute";
		var elPos = getAbsolutePos(element);
		s.left = elPos.x - 2 + plusx + "px";
		s.top = elPos.y + 17 + plusy + "px";
		visible(id);
		gCurrentCalTask = id;
	}
}

function mouseoutCal(id) {
	if (!gIsOnModifyTask) {
		id = "calTask"+id;
		gToDeleteCalTask = id;
		gCurrentCalTask = "";
		window.setTimeout('checkCalTask()',1);
	}
}

function checkCalTask() {
	if (!gIsOnModifyTask) {
		if ((gToDeleteCalTask != "") && (gToDeleteCalTask != gCurrentCalTask)) {
			hideCalTask(gToDeleteCalTask);
		}
	}
}

function showPatt(element) {
	var myDiv = MM_findObj("patterns");

	var s = myDiv.style;
	s.position = "absolute";
	
	var elPos = getAbsolutePos(element);
	s.left = elPos.x - 0 + "px";
	s.top = elPos.y + element.offsetHeight - 1 + "px";

	visibleObj(myDiv);
}

function hidePatt() {
	var myDiv = MM_findObj("patterns");
	invisibleObj(myDiv);
}

function metaphor(element, url) {
	var elPos = getAbsolutePos(element);
	    
	openInIFrame(url,
		elPos.x + 5, elPos.y + 15,
		false);
}


/**
 * Open item in "modification" mode
 */
function deleteItem(thisPage, type, projectId, id) {
	
	// Open the iFrame
	openInIFrameAtElement("Delete.php?thisPage=" + thisPage + "&projectId=" + projectId + "&type=" + type + "&id=" + id,
		type, id, true);
	
}


function modItem(type, id) {
	
	openInIFrameAtElement(document.location.pathname + "?modifyItem&type=" + type + "&id=" + id,
		type, id, true);
}

function cancelMod() {
	closeIFrame();
}

function cancelDelete() {
	closeIFrame();
}

function openInIFrameAtElement(url, type, id, shadowBack) {
	
	var itemName = "tb_"+type+"_"+id;
	
	var element = MM_findObj(itemName);
	
	var elPos = getAbsolutePos(element);
	
	openInIFrame(url,
		elPos.x, elPos.y,
		shadowBack);
}

/**
 * Open an url in the iFrame
 */
function openInIFrame(url, leftVal, topVal, shadowBack) {
	
	setIFrameSize(1, 1);
	
	// Waiting message
	// @todo: gif

	// First remove current url
	var xpIFrameElem = MM_findObj("xpIFrame");
	affectUrlToIFrameElem(xpIFrameElem, "_blank.php");
	
	
	leftVal		= leftVal + "px";
	topVal		= topVal + "px";
	
	// Move DIV
	var xpIFrameParentDivElem = MM_findObj("xpIFrameParentDiv");
	
	var s		= xpIFrameParentDivElem.style;
	s.position	= "absolute";
	s.left		= leftVal;
	s.top		= topVal;
	
	// Affect new URL
	affectUrlToIFrameElem(xpIFrameElem, url);
	
	// Make div visible
	visibleObj(xpIFrameParentDivElem);
	
	// Grrrr....
	if (gBrowser != "Safari") {
		setShadowBackground(shadowBack);
	}
	
}

function affectUrlToIFrameElem(iFrameElem, url) {
	if (iFrameElem.document) {
		// Seems like it's necessary for IE
		iFrameElem.document.location = url;
	} else {
		// Usual way
		iFrameElem.src = url;
	}
}

/**
 * Close the iFrame
 */
function closeIFrame() {
	setShadowBackgroundObj(false, window.parent.document.body);
	var xpIFrameParentDivElem = MM_findObj("xpIFrameParentDiv", window.parent.document);
	//alert(xpIFrameParentDivElem.style.display);
	invisibleObj(xpIFrameParentDivElem);
}

function setItemSize(itemName) {
	
	var myItemElem = MM_findObj(itemName);
	
	var itemWidth = myItemElem.offsetWidth;
	var itemHeight = myItemElem.offsetHeight;
	
	// We need to add some pixels for the patterns layer to display properly...
	itemHeight += 70;
	
	//alert("setItemSize "+itemWidth+", "+itemHeight);
	
	setIFrameSize(itemWidth, itemHeight);
	
}


function setIFrameSize(width, height) {
	
	//alert("setIFrameSize("+width+", "+height+")");
	
	var xpIFrameParentDivElem = MM_findObj("xpIFrameParentDiv", parent.document);
	var xpIFrameElem;
	
	if (parent.document.getElementById) {
		// Required because of IE bug if using MM_findObj directly (uses parent.document[all])
		xpIFrameElem = parent.document.getElementById("xpIFrame");
	} else {
		xpIFrameElem = MM_findObj("xpIFrame", parent.document);
	}

	
	if (xpIFrameParentDivElem && xpIFrameElem) {
		xpIFrameElem.style.height = "0%";
		xpIFrameParentDivElem.style.width = width + "px";
		xpIFrameParentDivElem.style.height = height + "px";
		xpIFrameElem.style.height = "100%";
	}
	else {
		alert("cannot find xpIFrameParentDivElem or xpIFrameElem");
	}
	
	//alert("div: set width "+xpIFrameParentDivElem.style.width+" ("+width+")"+" / height "+xpIFrameParentDivElem.style.height+" ("+height+")");
	
	//alert("frame: set width "+xpIFrameElem.width+" ("+width+")"+" / height "+xpIFrameElem.height+" ("+height+")");
}

function onloadDelete(type, id) {
	var myItemElem = MM_findObj("tb_"+type+"_"+id, parent.document);
	
	var itemWidth = myItemElem.offsetWidth;
	var itemHeight = myItemElem.offsetHeight;
	
	setIFrameSize(itemWidth, itemHeight);
}

function showError(itemType, itemId, errorMsg) {
	if (itemId != "insert") {
		modItem(itemType, itemId);
	}
	alert(errorMsg);
}

function checkSelect(theInput) {
	var currentOption = theInput.options[theInput.selectedIndex];
	while (theInput.selectedIndex != 0 && currentOption.disabled) {               
		theInput.selectedIndex --;
		currentOption = theInput.options[theInput.selectedIndex];
	}
	var newOption = theInput.options[theInput.selectedIndex];
	if (currentOption == newOption) {
		// We stayed on the same option!!
		// Let's try to choose next options...
		while (theInput.selectedIndex != theInput.length-1 && currentOption.disabled) {
			theInput.selectedIndex ++;
			currentOption = theInput.options[theInput.selectedIndex];
		}
	}
}

function refreshCalTask(id) {
	if (!gIsOnModifyTask) {
		id = "calTask"+id;
		gCurrentCalTask = id;
		checkCalTask();
	}
}

function hideCalTask(id) {
	invisible(id);
}

function sub(formName) {
	
	var theForm = document.forms[formName];
	
	if (isType(formName, "task")) {
		endDateDisabled(formName, false);
	}
	
	if (theForm.onsubmit) {
	
		var something = theForm.onsubmit();
		
	}
	
	theForm.submit();
	
	//return false;
}

function formKeyPress(formName) {
	
	if (window.event && window.event.keyCode == 13) {
		// "enter" was hit
		
		sub(formName);
		return false;
		
	} else {
		
		return true; 
		
	}
}

function submitLoginForm() {
	var loginForm = document.forms['loginForm'];
	if (loginForm.elements['userSelect'].value == 'admin'
		|| loginForm.elements['userSelect'].value == 'textUser') {
		loginForm.elements['username'].value = loginForm.elements['textUsername'].value;
	} else {
		loginForm.elements['username'].value = loginForm.elements['userSelect'].value;
	}
	return false;
}

function taskCheckWD(formName) {
	document.forms[formName].elements['wkType'][1].checked = true;
}

function chgVis(objects) {
	for (var i=0; i<arguments.length; i++) {
		var nomObject = arguments[i];
		
		var myObject = MM_findObj(nomObject);
		if (myObject.className == 'inv') {
			visibleObj(myObject);
		} else {
			invisibleObj(myObject);
		}
	}
}

function visible(nomObject) {
	var myObject;
	myObject = MM_findObj(nomObject);
	if (myObject == null) {
		alert("Unable to locate HTML element: " + nomObject);
		return false;
	}
	return visibleObj(myObject);
}

function visibleObj(myObject) {
	myObject.className = 'vis';
	myObject.style.display = 'block';
	return true;
}

function oneDayExceptThisOneIsWorking(formName, day) {
	for (var i in gAllDays){
		var dayToCheck = gAllDays[i];
		if (dayToCheck != '' && dayToCheck != day) {
			if (isWorkingDay(formName, dayToCheck)) {
				// One working day different from <day> has been found:
				// return TRUE
				return true;
			}
		}
	}
	// No working day different from <day> has been found:
	// return FALSE
	return false;
}

function wd(link, formName, day) {
	// Verify all the others are not unchecked!!
	if (oneDayExceptThisOneIsWorking(formName, day)) {
		
		checkUnCheckWorkingDay(formName, day, link);

		updateStartDate(formName);
		return true;
	} else {
		return false;
	}
}

function getLoadFactor(theForm) {
	return theForm.elements["loadFactor"].value;
}

function tskwd(link, formName, day) {
	var loadFactor = getLoadFactor(document.forms[formName]);
	taskCheckWD(formName);
	if (wd(link, formName, day)) {
		sigEDToUpd(formName);
		updateWorkingEndDate(formName);
		return true;
	}
}

function checkVersion(psLg, psVersion, pbClose) {

	var lsUrl = "http://xpweb.sourceforge.net/checkVersion.php?lg="+psLg+"&current="+psVersion;
	
	if (pbClose) {
		lsUrl += "&doClose=true";
	}
	
	/*
	
	newWindow = window.open(lsUrl,"XPWeb - Version check", "width=106, height=86,toolbar=false,scrollbars=no");
	newWindow.location.href = lsUrl;
	// Move the window to the background
	newWindow.blur();
	// Just in case, it'll be closed after 1 minute
	timeoutTime = 1 * 60 * 1000;
	newWindow.setTimeout("newWindow.close()",timeoutTime);
	*/
	xpIFrame.document.location.href = lsUrl;
}

function url(url) {
	window.parent.document.location.href = url;
	return false;
}

function reloadPage() {
	window.location.href=window.location.href;
	return false;
}

// *******************
// **** Insert scripts
// *******************

function setShadowBackground(setOrRemove) {
	setShadowBackgroundObj(setOrRemove, document.body);
}

function setShadowBackgroundObj(setOrRemove, bodyElement) {
	if (setOrRemove) {
		bodyElement.className = "opacityZoub";
	} else {
		bodyElement.className = "";
	}
}

function insertItem(itemType, count, formName) {

	setShadowBackground(true);

	if (gCurrentInsertCount != -1) {
		//alert("cancel insert "+gCurrentInsertType);
		cancelInsert(gCurrentInsertType);
	}

	gCurrentInsertCount	= count;
	gCurrentInsertType	= itemType;
	
	var strInsertDivName = itemType + "_insert_layer";
	
	var currentLinkName = "insert_" + itemType + "_" + count;

	var insertForm	= MM_findObj(strInsertDivName);
	var currentLink	= MM_findObj(currentLinkName);
	
	// Display insert form here
	
	var s = insertForm.style;
	
	visible(strInsertDivName);
	
	var insertTable = insertForm.getElementsByTagName("table")[0];
	
	var newPos = (currentLink.offsetWidth - insertTable.offsetWidth) / 2;
	
	s.position = "absolute";
	var elPos = getAbsolutePos(currentLink);
	
	s.left	= elPos.x + newPos + 0 + "px";
	s.top	= elPos.y - 8 + "px";//currentLink.offsetHeight) + "px";
	
	s.zIndex = "4";
	
	res(formName);
	
}

function forbidden() {
	url("Help/Login_help.php#forbidden");
}

function forceReplaceFormValue(theForm, strValName, strValue) {
	
	theForm.elements[strValName].value = strValue;
	
	// Force even the default value...
	theForm.elements[strValName].defaultValue = 
		theForm.elements[strValName].value;
		
}

function cancelInsert(itemType) {
	
	// Make the previous invisible, if necessary
	invisible(itemType + "_insert_layer");
	
	gCurrentInsertCount = -1;
	
	setShadowBackground(false);
}

function getInsertForm(formName) {
	
	var theForm = document.forms[formName];
	
	return theForm;

}

// ** Custom insert scripts

function insertTask(itemType, count, formName, iteId, storyId) {

	// Generic
	var theForm = getInsertForm(formName);
	
	// ** Specific **
	forceReplaceFormValue(theForm, "iterationStoryId", iteId + "_" + storyId);
	
	// Generic
	insertItem(itemType, count, formName);
	
	// ** Specific **
	// Reaffect the right loadfactor

	// @todo PB here no more iteration form...
	var iteForm = getIteFormFromTask(formName);
	theForm.elements["loadFactor"].value =
		iteForm.elements["loadFactor"].value;
	
}

function insertStory(itemType, count, formName, iteId) {

	// Generic
	var theForm = getInsertForm(formName);
	
	// ** Specific **
	forceReplaceFormValue(theForm, "iterationId", iteId);
	
	// Generic
	insertItem(itemType, count, formName);
	
	focStory(formName);
}

function insertIteration(itemType, count, formName) {
	// Generic
	insertItem(itemType, count, formName);
}

function insertMetaphorWord(itemType, count, formName) {
	// Generic
	insertItem(itemType, count, formName);
}

function insertWebCategory(itemType, count, formName) {
	// Generic
	insertItem(itemType, count, formName);
}

function insertWebLink(itemType, count, formName, categoryId, title) {
	// Generic
	var theForm = getInsertForm(formName);
	
	// ** Specific **
	forceReplaceFormValue(theForm, "name", title);
	forceReplaceFormValue(theForm, "categoryId", categoryId);
	
	insertItem(itemType, count, formName);
}

function insertProject(itemType, count, formName) {
	// Generic
	insertItem(itemType, count, formName);
}

function insertProjectLink(itemType, count, formName, projectId,
	linkType, linkTypeName, linkTitle) {
	
	// Generic
	var theForm = getInsertForm(formName);
	
	// ** Specific **
	forceReplaceFormValue(theForm, "projectId", projectId);
	forceReplaceFormValue(theForm, "type", linkType);
	forceReplaceFormValue(theForm, "comment", linkTitle);
	
	insertItem(itemType, count, formName);
}

function insertMember(itemType, count, formName, projectId,	projectTitle) {
	
	// Generic
	var theForm = getInsertForm(formName);
	
	// ** Specific **
	forceReplaceFormValue(theForm, "memberProjectId", projectId);
	
	insertItem(itemType, count, formName);
}

function insertProfile(itemType, count, formName) {
	
	// Generic
	insertItem(itemType, count, formName);
}

function changeUserTasks(theInput, pairInputName) {
	// Currently selected user
	
	/*
	test = theInput.selectedIndex;
	for (i = 0; i < theInput.options.length; i ++) {
		test += "/" + theInput.options[i].value + "=" + theInput.options[i].text;
	}
	alert(test);
	*/
	
	var currentOption = theInput.options[theInput.selectedIndex];
	var currentUserId = currentOption.value;
	
	var pairInput = theInput.form.elements[pairInputName];
	
	var wrongId = false;
	
	var currentPairOption;
	var currentPairId;

	for (i = 0; i < pairInput.length; i ++) {
		// For each pair
		
		currentPairOption = pairInput.options[i];
		currentPairId = currentPairOption.value; 
		
		if (currentPairId == currentUserId
			// Always allowed to choose "all"
			&& currentPairId != -1
			// Always allowed to choose "nobody"
			&& currentPairId != 0) {
			
			if (currentPairOption.selected) {
				wrongId = true;
			}
			
			currentPairOption.disabled = true;
			
		} else if (!eval("currentPairId in gForbiddenIds")) {
			// If not forbidden => is allowed
			currentPairOption.disabled = false;
		}
		
	}
	
	if (wrongId) {
		// the pair id was wrong => set it to "nobody"
		pairInput.selectedIndex = 0;
	}
	
	checkSelect(pairInput);

}
