function delayedPleasePatient()
{
	window.setTimeout('showPleasePatient()',2000);
}

function showPleasePatient()
{
	document.getElementById('loadingPleaseWait').style.visibility = 'visible';
}

// ****** Notice form modifcations to avoid data loss ****** 
var unModifiedFlag = true;

function checkFormModifyFlag(confirmMsg)
{
	if (unModifiedFlag == false)
	{
		var aConfirm = confirm(unescape(confirmMsg));
		if (aConfirm == true)
		{
			submitModifiedForm();
			return false;
		}
	}
}

function setModified()
{
	unModifiedFlag = false;
}

inputFieldBlockedFlag = true;
function notifyBlockedInputField(notifyMessage)
{
	if (inputFieldBlockedFlag == true)
	{
		alert(unescape(notifyMessage));
	}
}

function unblockInputField()
{
	inputFieldBlockedFlag = false;
	document.getElementById('legendTextBox').readOnly = false;
}

function submitModifiedForm()
{
	// Make sure that the unmodified flag is correctly set.
	unModifiedFlag = true;
	
	// Lookup the form to submit.		
	var aForm = document.getElementById("itemUpdateForm");
	
	// Extract and perform the onSubmit-actions;
	var onSubmit;
	onSubmit = aForm.onsubmit;
	if (onSubmit != undefined)
	{
		onSubmit = onSubmit.toString();
		onSubmit = onSubmit.substring(onSubmit.indexOf("{")+1);
		onSubmit = onSubmit.substring(0,onSubmit.indexOf("}"));
		eval(onSubmit)
	}
	
	// Submit the form.
	aForm.submit();
}
// ****** Notice form modifcations upto here ****** 


function preloadSizedPic(aID)
{
	document.getElementById('picPreview').src = sizedPics[aID];
	setModified();
}

divSet     = Array();
slideIndex = Array();
timeOuts   = Array();

function prepareSlideShow(aDivSet,aSetId)
{
	divSet[aSetId]     = aDivSet;
	slideIndex[aSetId] = 0;
	setNextSlide(true,aSetId);
}

function setNextSlide(firstTime,aSetId)
{	
	if (firstTime == false)
	{
		oldIndex = slideIndex[aSetId];
		slideIndex[aSetId]++;
		if (slideIndex[aSetId] >= divSet[aSetId].length)
		{
			slideIndex[aSetId] = 0;
		}
		document.getElementById(divSet[aSetId][oldIndex]).style.visibility = 'hidden';
	}
	document.getElementById(divSet[aSetId][slideIndex[aSetId]]).style.visibility = 'visible';
	timeOuts[aSetId] = window.setTimeout("setNextSlide(false,'" + aSetId + "')",5000);
}

function changeRatingPicture()
{
	var aElement;
	for (var i=0;i<=5;i++)
	{
		aElement = document.getElementById("rating_" + i);
		if (aElement.checked == true)
		{
			document.getElementById("ratingPicture").src = "icons/rating_big_" + i + ".gif";
			break;
		}
	}
}

var suggestionContainer = "";
var inputBox = "";
function searchSuggestions(aBox,aContainer)
{
	var aPattern;
	
	suggestionContainer = document.getElementById(aContainer);
	inputBox            = document.getElementById(aBox);
	aPattern            = escape(inputBox.value);
	
	if (aPattern.length > 2)
	{
		createXmlHttp('suggestions');
		getXmlHttp('suggestions').open('GET','searchSuggestions.php?type=' + aBox + '&pattern=' + aPattern,true);
		getXmlHttp('suggestions').onreadystatechange=receiveSearchSuggestions;
		getXmlHttp('suggestions').send(null);
	}
	else
	{
		hideSuggestions(aContainer);
	}
}

function hideSuggestionsTimed(aID)
{
	window.setTimeout("hideSuggestions('" + aID + "')",300);
}

function hideSuggestions(aID)
{
	document.getElementById(aID).style.display = "none";
}

function setSuggestion(aSuggestion,aID,bID)
{
	document.getElementById(aID).value = unescape(aSuggestion);
	hideSuggestions(bID);
}

function receiveSearchSuggestions()
{
	if (getXmlHttp('suggestions').readyState==4)
	{
		var aHtml = "", aItem, aXml, aList;
		
		aXml  = getXmlHttp('suggestions').responseXML;
		aList = aXml.getElementsByTagName("item");
		
		if (aList.length > 0)
		{
			aHtml += "<ul>";
			
			for (i=0;i<aList.length;i++)
			{
				aItem = unescape(aList.item(i).firstChild.nodeValue);
				aHtml += "<li onclick='setSuggestion(\"" + escape(aItem) + "\",\"" + inputBox.id + "\",\"" + suggestionContainer.id + "\");'>";
				aHtml += aItem;
				aHtml += "</li>";
			}
			
			aHtml += "</ul>";
			suggestionContainer.innerHTML = aHtml;
			suggestionContainer.style.display = "inline";
		}
		removeXmlHttp('suggestions');
	}
}

// check/uncheck a checkbox
function virtualCheckboxClick(aId)
{
	var aBox = document.getElementById(aId); 
	switch(aBox.checked)
	{
		case true: aBox.checked = false; break;
		case false: aBox.checked = true; break;
	}
}

function setFlagContainer(aValue)
{
	var aPath = "../../pics/flags/" + aValue + ".gif";
	document.getElementById("flagContainer").src = aPath;
}

var commentsHidden = true;
function hideShowComments()
{
	switch (commentsHidden)
	{
		case true:
			commentsHidden = false;
			document.getElementById("commentPanel").style.display = "block";
			document.getElementById("showComments").style.display = "none";
			document.getElementById("hideComments").style.display = "inline";
		break;
		case false:
			commentsHidden = true;
			document.getElementById("commentPanel").style.display = "none";
			document.getElementById("showComments").style.display = "inline";
			document.getElementById("hideComments").style.display = "none";
		break;
	}
}

var testimonialsHidden = true;
function hideShowTestimonials()
{
	switch (testimonialsHidden)
	{
		case true:
			testimonialsHidden = false;
			document.getElementById("testimonialPanel").style.display = "block";
			document.getElementById("showTestimonials").style.display = "none";
			document.getElementById("hideTestimonials").style.display = "inline";
		break;
		case false:
			testimonialsHidden = true;
			document.getElementById("testimonialPanel").style.display = "none";
			document.getElementById("showTestimonials").style.display = "inline";
			document.getElementById("hideTestimonials").style.display = "none";
		break;
	}
}

function setOrder(aOrder)
{
	document.getElementById('order').value = aOrder;
	submitForm("searchForm");
}

function askListItemDeletion(aID,aHref,aMessage)
{
	document.getElementById(aID).className = 'deleteItemBox';
	window.setTimeout("renormalListItem('" + aID + "')",50);
	askBeforeAction(aHref,aMessage);
}

function renormalListItem(aID)
{
	document.getElementById(aID).className = 'modifyItemBox';	
}

function askBeforeAction(aHref,aMessage)
{
   if (confirm(unescape(aMessage)))
   {
      window.location.href = aHref;
   }
}

function submitForm(formId)
{
	document.getElementById(formId).submit();
}

// functions related to the material/tools library.

// ****** Load and receive a batch of pictures to preview the sizes ******
function replacePreviewImageBatch(aType,aMethod,itemID)
{
	var aDate = new Date();
	var aTime = aDate.getMilliseconds();
	var aHref = 'loadCatItems.php?method=' + aMethod + '&type=' + aType + '&item=' + itemID + '&version=' + aTime;
	
	createXmlHttp('replacePreviewBatch');
	getXmlHttp('replacePreviewBatch').open('GET',aHref,true);
	getXmlHttp('replacePreviewBatch').onreadystatechange=receivePreviewBatch;
	getXmlHttp('replacePreviewBatch').send(null);	
}

function setPicPreviewVisibility(aStatus)
{
	switch (aStatus)
	{
		case true:
			document.getElementById('picPreview').style.display    = "block";
			document.getElementById('noPreviewText').style.display = "none";
		break;
		default:
			document.getElementById('picPreview').style.display    = "none";
			document.getElementById('noPreviewText').style.display = "block";
		break;
	}
}

function receivePreviewBatch()
{
	if (getXmlHttp('replacePreviewBatch').readyState==4)
	{		
		var aResponse = getXmlHttp('replacePreviewBatch').responseXML;
		var aList = aResponse.getElementsByTagName("item");

		var aItem;
		if (aList.length > 0)
		{	
			for (var i=0; i<aList.length; i++)
			{
				aItem = unescape(aList.item(i).firstChild.nodeValue);
				sizedPics[i] = aItem;
			}
			
			aSize = document.getElementById('sizeSelector').value;
			document.getElementById('picPreview').src = sizedPics[aSize];
			setPicPreviewVisibility(true);
		}
		else
		{
			setPicPreviewVisibility(false);
		}

		aSize = document.getElementById('sizeSelector').value;
		document.getElementById('picPreview').src = sizedPics[aSize];				
		removeXmlHttp('replacePreviewBatch');
	}	
}
// ****** Load and receive upto here ******

// ****** Load and receive category items from the library ****** 
function loadCatItems(aType,catID,aTitle,itemID,lookupLegendProposalFlag,titleMsg,buttonMsg)
{
	inputFieldBlockedFlag = true;
	
	document.getElementById('itemCategorySelector').value = catID;
	
	if (itemID > 0)
	{
		unblockInputField();
		document.getElementById(aType + 'BaseSelection').value=itemID;
		document.getElementById('shapeContainer').value=1;
		replacePreviewImageBatch(aType,'preview',itemID);
	}
	else
	{
		if (itemID != null)
		{
			unblockInputField();			
		}
		setPicPreviewVisibility(false);
		document.getElementById('shapeContainer').value=0;
	}

	setOneVisible(0,'showrow');
		
	var aDate = new Date();
	var aTime = aDate.getMilliseconds(); 
	var aHref = 'loadCatItems.php?type=' + aType + '&cat=' + catID + '&item=' + itemID + '&version=' + aTime;
	
	createXmlHttp('loadCatItems');
	getXmlHttp('loadCatItems').open('GET',aHref,true);
	//getXmlHttp('loadCatItems').onreadystatechange=receiveCatItems;
	getXmlHttp('loadCatItems').onreadystatechange =
	new Function("fx",'receiveCatItems("'+itemID+'","'+titleMsg+'","'+buttonMsg+'")');
	getXmlHttp('loadCatItems').send(null);

	if (lookupLegendProposalFlag == true)
	{
		setModified();
		
		var aHref = 'loadCatItems.php?method=keyword&type=' + aType + '&cat=' + catID + '&item=' + itemID + '&version=' + aTime;	
		createXmlHttp('legendProposal');
		getXmlHttp('legendProposal').open('GET',aHref,true);
		getXmlHttp('legendProposal').onreadystatechange=receiveLegendProposal;
		getXmlHttp('legendProposal').send(null);
	}
}

function receiveLegendProposal()
{
	if (getXmlHttp('legendProposal').readyState==4)
	{
		var aProposal = getXmlHttp('legendProposal').responseText;
		var aField    = document.getElementById('legendTextBox');
		if (aProposal.length > 0)
		{
			aField.value = aProposal;
		}		
	}
}

function receiveCatItems(itemID,titleMsg,buttonMsg)
{
	if (getXmlHttp('loadCatItems').readyState==4)
	{
		var aHtml,aXml,container,newDiv;
		
		aHtml = getXmlHttp('loadCatItems').responseText;
		container = document.getElementById('catItemsContainer');
		
		container.innerHTML = aHtml;
		//newDiv = document.createElement("div");
		//newDiv.innerHTML = aHtml;
		//container.appendChild(newDiv);
		
		// Add an upload button, if button container is existing.
		// Necessary because it ain't work directly with innerHTML on IE.
		try
		{
			//container = document.getElementById('uploadButtonContainer');
			if (itemID == 0)
			{
				aList = container.getElementsByTagName("ul");
				aList = aList[0];
				
				aItem = document.createElement("li");
				
				aBox  = document.createElement("div");
				aBox.className = 'horizontalListBoxSelected';
			
				bBox = document.createElement("div");
				bBox.style.position = 'relative';
				bBox.style.width    = '90px';
				bBox.style.height   = '18px';
				bBox.style.overflow = 'hidden';
				bBox.className = 'usualbutton';
				bBox.style.margin = '6px';
				
				aLabel = document.createElement("span");
				aLabel.innerHTML = "<img src='pics/folder.gif' style='float:left;padding-right:5px;padding-top:1px;'>";
				aLabel.innerHTML += unescape(buttonMsg) + " ...";
				aLabel.style.position = 'absolute';
				aLabel.style.left = '8px';
				aLabel.style.top  = '2px';
				
				bLabel = document.createElement("span");
				//bLabel.innerHTML = "<br><strong>Illustrer l'objet</strong> (facultatif) <br><br>";
				bLabel.innerHTML = "<br><strong>" + unescape(titleMsg) + "<br><br>";
				
				/*
				bBox.style.borderLeft = '1px solid white'
				bBox.style.borderTop = '1px solid white'
				bBox.style.borderRight = '1px solid black'
				bBox.style.borderBottom = '1px solid white'
				*/
				
				inputElement = document.createElement("input");
				inputElement.style.position = 'relative';
				inputElement.style.left     = '-40px';
				inputElement.style.top     = '-3px';
				inputElement.type = 'file';
				inputElement.name = 'image';
				inputElement.border = '1px solid black';
				inputElement.size = 1;
				inputElement.style.filter = 'alpha(opacity=0)';
				inputElement.style.opacity = '0.0';
			
				bBox.appendChild(aLabel);
				bBox.appendChild(inputElement);
				
				aBox.appendChild(bLabel);
				aBox.appendChild(bBox);
				aItem.appendChild(aBox);
			
				aList.appendChild(aItem);
			}
		}
		catch (e) {}

		removeXmlHttp('loadCatItems');
	}
}
// ****** Load and receive upto here ******

// ****** Manipulate element order ******
// Save the order of the elements using a back-office
function ajaxSaveOrder(aElement)
{
	var aID    = aElement.id;
	var aParam = Sortable.serialize(aID);
	createXmlHttp('saveOrder');
	getXmlHttp('saveOrder').open('GET','saveOrder.php?action=' + aID + '&' + aParam,true);
	getXmlHttp('saveOrder').onreadystatechange=ajaxCleanUp;
	getXmlHttp('saveOrder').send(null);
}

// Clean up the ajax request object after saving the order.
function ajaxCleanUp()
{
	if (getXmlHttp('saveOrder').readyState==4)
	{
		removeXmlHttp('saveOrder');
	}
}
// ****** Manipulate element order upto here ******

// ****** Manipulate an exclusive set of table rows ******
function setOneVisible(aID,aGroupName)
{
	hideTableRows(aGroupName)
	// Show the selected row ie safely.
	aElement = document.getElementById(aGroupName + "_" + aID);
	/*
	try
	{
		aElement.style.display = 'table-row';
	}
	catch (e)
	{
		aElement.style.display = 'inline';
	}
	*/
	aElement.style.display = 'block';
}

function hideTableRows(aGroupName)
{
	// Hide all rows ie safely.
	aList = document.getElementsByName(aGroupName);
	if (aList.length > 0)
	{
		for (var i=0; i<aList.length; i++)
		{
			aList[i].style.display = 'none';
		}
	}
	else
	{
		try
		{
			aList = document.all;
			for (var i=0; i<aList.length; i++)
			{
				if (aList[i].name == aGroupName)
				{
					aList[i].style.display = 'none';
				}
			}
		}
		catch (e) {}
	}
}
// *******************************************************

// ****** Opens generator and load iframe ****************
function setGeneratorFrame(aShape,aPic,bricoID,uniqueKey)
{
	unblockInputField();
	
	replacePreviewImageBatch('material','generator',bricoID + "_" + uniqueKey);	
			
	document.getElementById('shapeContainer').value=2;
	setOneVisible(1,'showrow');
			
	var aFrame = document.getElementById('generatorFrame');
	aFrame.src = 'materialGenerator/generatorInterface.php?shape=' + aShape + "&pic=" + aPic;
}
// *******************************************************

// ****** Opens new item dialog and set category *********
function setNewItemCategory(aID,aGroupName,aItem)
{
	document.getElementById('shapeContainer').value=0;
	selectItem(aItem,aGroupName,'horizontalListBoxSelected');
	//setOneVisible(0,'detailrow');
	
	aDropDown = document.getElementById('itemCategorySelector');
	for (var i=0;i<aDropDown.options.length;i++)
	{
		if (aDropDown.options[i].value == aID)
		{
			aDropDown.options[i].selected = true;
			break;
		}
	}
}
// *******************************************************

// ****** Select an item from a list *********************
function selectItem(aItem,aGroupName,aClass)
{
	// Reset all elements of the group ie-safely.
	aList = document.getElementsByName(aGroupName);
	if (aList.length > 0)
	{
		for (var i=0; i<aList.length; i++)
		{
			aList[i].className = 'horizontalListBox';
		}
	}
	else
	{
		try
		{
			aList = document.all;
			for (var i=0; i<aList.length; i++)
			{
				if (aList[i].name == aGroupName)
				{
					aList[i].className = 'horizontalListBox';
				}
			}
		}
		catch (e) {}
	}
	// Select the transmitted element.
	aItem.className = aClass;
}
// *******************************************************

// ****** Select an material/tool from library ***********
/*
function selectMaterial(aID,aGroupName)
{
	var aField,aElement;
	
	setOneVisible(1,'detailrow');
	
	aField = document.getElementById('materialBaseSelection');
	aField.value = aID;
	aElement = document.getElementById('materialBaseItem_' + aID);
	
	selectItem(aElement,aGroupName,'horizontalListBoxEmphasized');
	loadItemDetails(aID,aElement,"material");
}

function selectTool(aID,aGroupName)
{
	var aField,aElement;
	
	setOneVisible(1,'detailrow');
	
	aField = document.getElementById('toolBaseSelection');
	aField.value = aID;
	aElement = document.getElementById('toolBaseItem_' + aID);
	
	selectItem(aElement,aGroupName,'horizontalListBoxEmphasized');
	loadItemDetails(aID,aElement,"tools");	
}
// *******************************************************
/*
function selectMaterial(aID)
{
   var aField,aHidden;
   
   aField = document.getElementById('materialBaseSelection');
   bID = aField.value;
   
   try
   {
      aHidden = document.getElementById('materialBaseItem_' + bID);
      selectItem(aHidden,false);
   }
   catch (e) {}

   selectItem(document.getElementById('materialBaseItem_' + aID),true);
   aField.value = aID;
   
   loadItemDetails(aID,"material");
}

function selectTool(aID)
{
   var aField,aHidden;
   aField = document.getElementById('toolBaseSelection');
   bID = aField.value;
   
   try
   {
      aHidden = document.getElementById('toolBaseItem_' + bID);
      selectItem(aHidden,false);
   }
   catch (e) {}
   
   selectItem(document.getElementById('toolBaseItem_' + aID),true);
   aField.value = aID;
   
   loadItemDetails(aID,"tools");
}
/*
// *******************************************************
/*
function selectCategory(aID)
{
   var aField,aHidden;
   
   aField = document.getElementById('categoryBaseSelection');
   bID = aField.value;
   
   try
   {
      aHidden = document.getElementById('categoryBaseItem_' + bID);
      selectItem(aHidden,false);
   }
   catch (e) {}

   selectItem(document.getElementById('materialBaseItem_' + aID),true);
   aField.value = aID;
}

var currentElement = null;
var oldElement     = null;

function loadItemDetails(aID,aElement,aType)
{
	if (currentElement != null)
	{
		oldElement = currentElement;
		currentElement.innerHTML = "";
		createXmlHttp('restoreOldItem');
		getXmlHttp('restoreOldItem').open('GET','loadCatItems.php?type=' + aType + '&item=' + aID + '&method=individual&selected=false&version=' + aTime,true);
		getXmlHttp('restoreOldItem').onreadystatechange=receiveOldItem;
		getXmlHttp('restoreOldItem').send(null);
	}
	currentElement = aElement;
	
	var aDate = new Date();
	var aTime = aDate.getMilliseconds(); 

	createXmlHttp('loadSelectedItem');
	getXmlHttp('loadSelectedItem').open('GET','loadCatItems.php?type=' + aType + '&item=' + aID + '&method=individual&selected=true&version=' + aTime,true);
	getXmlHttp('loadSelectedItem').onreadystatechange=receiveItemDetails;
	getXmlHttp('loadSelectedItem').send(null);
}

function receiveOldItem()
{
	if (getXmlHttp('restoreOldItem').readyState==4)
	{
		var aHtml;
		aHtml = getXmlHttp('restoreOldItem').responseText;
		oldElement.innerHTML = aHtml;
		removeXmlHttp('restoreOldItem');
	}
}

function receiveItemDetails()
{
	if (getXmlHttp('loadSelectedItem').readyState==4)
	{
		var aHtml = getXmlHttp('loadSelectedItem').responseText;
		alert(aHtml);
		currentElement.innerHTML = aHtml;
		removeXmlHttp('loadSelectedItem');
	}
}

*/

function copyPasteItemLegend(aElement)
{
	var aString, bString;
	// Prepare the copy string.
	aString = aElement.innerHTML;
	aString = aString.substring(0,aString.indexOf('<a'));
	aString = aString.replace(/^\s+|\s+$/g, '');
	// Verify if the field contains already something.
	bString = document.getElementById('legendTextBox').value;
	if (bString.length > 0)
	{
		bString += "\n" + aString;
	}
	else
	{
		bString = aString;
	}
	document.getElementById('legendTextBox').value = bString;
}

function calculatePopupCentering(xSize,ySize)
{
	var w = screen.availWidth;
	var h = screen.availHeight;
	var x = (w-xSize)/2;
	var y  = (h-ySize)/2;
	if (x < 0) {x = 0};
	if (y < 0) {y = 0};
	
	return Array(x,y,w,h);	
}

// open a popup window
function openPopupWindow(aHref,xSize,ySize)
{
	aBuffer = calculatePopupCentering(xSize,ySize);
	x = aBuffer[0];
	y = aBuffer[1];
	w = aBuffer[2];
	h = aBuffer[3];
	
	fenster = window.open(aHref,'webenergie','width=' + xSize + ',height=' + ySize + ',left=' + x + ',top=' + y + ',scrollbars=yes,status=no,location=no,dependent=yes,toolbar=no');
	fenster.focus();
}

function changeDisplayStatus(aID)
{
	var aElement = document.getElementById(aID);
	if (aElement.style.display == 'none')
	{
		aElement.style.display = 'block';
	}
	else
	{
		aElement.style.display = 'none';
	}
}

function savePageAsPDF(aURL)
{
	var authorId = '1A71736E-FAC0-4EC9-A211-A17F849DDDCA';
	var pageOrientation = '0';
	var topMargin = '0.2';
	var bottomMargin = '0.2';
	var leftMargin = '0';
	var rightMargin = '0';
	var sUriRequest = '';

	sUriRequest = 'author_id=' + authorId;
	sUriRequest += '&page=' + pageOrientation;
	sUriRequest += '&top=' + topMargin;
	sUriRequest += '&bottom=' + bottomMargin;
	sUriRequest += '&left=' + leftMargin;
	sUriRequest += '&right=' + rightMargin;

	var pURL = 'http://savepageaspdf.pdfonline.com/pdfonline/pdfonline.asp?cURL=' + escape(aURL) + '&' + sUriRequest;
	window.open(pURL, 'PDFOnline', 'scrollbars=yes,resizable=yes,width=640,height=480,menubar,toolbar,location');
}