/*
* Params for the tips and menu
*/
tipsList = [];
tipsIndex = 0;
delay=0;
timeout = null;
pause = false;
menuOpen = false;
previousMenuId = null;
defaultModelChoiceText = null;
otherChoiceText = null;

/*
* Test
*/
function test(id){
	console.debug(id);
	var widget = dijit.byId(id);
	console.debug(widget);
}

/*
* Change text zone in OFX mobile page
*/
function changeMobileTextZone(id,type,side){
var xb4 = dojo.query('#bottom_part .xb4top')[0];
var xb3 = dojo.query('#bottom_part .xb3top')[0];
var xb2 = dojo.query('#bottom_part .xb2top')[0];
switch(side){
	case 'left':
		xb4.style.margin = '0 1px 0 0';
		xb3.style.margin = '0 2px 0 0';
		xb2.style.margin = '0 3px 0 0';
	break;
	case 'middle':
		xb4.style.width = 'auto';
		xb3.style.width = 'auto';
		xb2.style.width = 'auto';
		xb4.style.margin = '0 1px 0 1px';
		xb3.style.margin = '0 2px 0 2px';
		xb2.style.margin = '0 3px 0 3px';	
	break;
	case 'right':
		xb4.style.width = '801px';
		xb3.style.width = '800px';
		xb2.style.width = '799px';
		xb4.style.margin = '0 0 0 0px';
		xb3.style.margin = '0 0 0 1px';
		xb2.style.margin = '0 0 0 2px';	
	break;
}
//on efface toute les zones
if(type == 'mobile'){
	dojo.byId("text_application").style.display = 'none';
	dojo.byId("text_browser").style.display = 'none';
	dojo.byId("text_mail").style.display = 'none';
}
else if(type == 'pc'){
	dojo.byId("text_widget").style.display = 'none';
	dojo.byId("text_config").style.display = 'none';
	dojo.byId("text_synchro").style.display = 'none';
}
//on met toutes les bordures des div à 1px
dojo.forEach(dojo.query('.middle_div_top,.image_zone,.sentence, #top_part .normal_border, #top_part .large_border, .xb1top, .xb1bottom'), function(node){
	node.style.borderLeftWidth = '1px';
	node.style.borderRightWidth = '1px';
	node.style.borderTopWidth = '1px';
	node.style.borderBottomWidth = '1px';
	node.style.borderColor = '#DCDCDC';
});
dojo.forEach(dojo.query('.xb1top, .xb1bottom'), function(node){
	node.style.height = '1px';
});
// on met la bordure des bonnes divs à 2px
dojo.forEach(dojo.query('#'+id+' div, #top_part #'+id+' .normal_border, #'+id+' .large_border'), function(node){
	node.style.borderLeftWidth = '2px';
	node.style.borderRightWidth = '2px';
	node.style.borderColor = '#CCCCCC';
});
dojo.forEach(dojo.query('#'+id+' .xb1top, #'+id+' .xb1bottom'), function(node){
	node.style.height = '2px';
});
//dojo.query('#'+id+' .box_title')[0].style.borderTopWidth = '2px';
dojo.query('#'+id+' .middle_div_top')[0].style.borderBottomWidth = '2px';
dojo.forEach(dojo.query('#top_part .normal_height'), function(node){
	node.style.height = '1px';
	node.style.backgroundColor = '#DCDCDC';
});
dojo.forEach(dojo.query('#top_part #'+id+' .normal_height'), function(node){
	node.style.height = '2px';
	node.style.backgroundColor = '#CCCCCC';
});
// on affiche la bonne zone
var nodeId = "text_"+id;
dojo.byId(nodeId).style.display = 'block';
// on positionne la div qui joint les blocs
var middle_top_node = dojo.query("#"+id+" .middle_div_top")[0];
var middle_bottom_node = dojo.byId('text');
var div_height = middle_bottom_node.offsetTop - middle_top_node.offsetTop + 1;
var join_div = dojo.byId("join_div");
join_div.style.top = middle_top_node.offsetTop + 'px';
join_div.style.height = div_height + 'px';
join_div.style.left = dojo.byId(id).offsetLeft + 'px';
// on reajuste la taille du content
var text_node = dojo.byId('text');
// the line below is necessary to correct the width in IE
text_node.style.width = dojo.byId("synchro").offsetLeft+dojo.byId("synchro").offsetWidth-dojo.byId("widget").offsetLeft;
var content_height = text_node.offsetHeight + text_node.offsetTop + 25;
if(dojo.isIE == 7){
	content_height += 5;
}
dojo.byId('content').style.height = content_height + 'px';
dojo.byId('left').style.height = content_height + 'px';
//console.debug(dojo.query('#'+id+' div'));
}

/*
* Enable browser button if the cgu checkbox is checked
*/
function acceptCGU(node){
dijit.byId('application_button').setDisabled(!node.checked);
}

/*
* Check or uncheck where there is a click
*/
function checkCGUBox(){
var checkBox = dojo.byId('cgu_checkbox');
checkBox.checked = !checkBox.checked;
acceptCGU(checkBox);
}

/* Fills the two SELECT lists of the main form with the JSON file's data. */
function ofxLoadSelectList(companyDefaultText, modelDefaultText, _otherChoiceText){
	defaultModelChoiceText = modelDefaultText;
	otherChoiceText = _otherChoiceText;
	dojo.xhrPost({
		url: '/toolbox/ofxPortableModel.json',
		handleAs: "json-comment-filtered",
		timeout: 5000,
		load: function(response, ioArgs){ 
			var companyText = "";
			var modelText = "";
			var first = true;
			for(var key in response){
				companyText += '<option value="'+key+'">'+key+'</option>';
				if(first){
					var tab = response[key].models;
					for(var id in tab){
						modelText += '<option value="'+id+'">'+tab[id]+'</option>';
					}
					modelText += '<option value="other">'+otherChoiceText+'</option>';
				}
				first = false;
			}
			companyText += '<option value="other">'+otherChoiceText+'</option>';
			// IE8 also requires this operation
			if(dojo.isIE >= 6 && dojo.isIE <= 8){
				dojo.byId('company').outerHTML = '<select id="company" name="company" onchange="ofxChangeMobileModel(this)">\n<option value="default">'+companyDefaultText+'</option>\n'+companyText+'</select>';
				dojo.byId('modelId').outerHTML = '<select id="modelId" name="modelId" onchange="onMobileModelSelected(dojo.byId(\'company\'),this)">\n<option value="default">'+modelDefaultText+'</option>\n</select>';
			}
			else{
				dojo.byId('company').innerHTML = '\n<option value="default">'+companyDefaultText+'</option>\n'+companyText;
				dojo.byId('modelId').innerHTML = '\n<option value="default">'+modelDefaultText+'</option>\n';
			}
			// by default, the choice is invalid
			dijit.byId("modelValidationButton").setDisabled(true);
			dijit.byId("questionnaireValidationButton").setDisabled(true);
			dojo.byId("modelId").disabled = true;

			return response;
		},
		error: function(response, ioArgs) {
		    console.error("HTTP status code: ", ioArgs.xhr.status);
		    return response;
		}
	});
}

function showFormPane(idPrefix, displayAttribute){
	dojo.byId(idPrefix+"FormStepImage").style.display = displayAttribute;
	dojo.byId(idPrefix+"FormHeader").style.display = displayAttribute;
	dojo.byId(idPrefix+"FormPane").style.display = displayAttribute;
	dojo.byId(idPrefix+"FormButtonPane").style.display = displayAttribute;
}

/**
 * Opens the hidden pane of the form in the main questionnaire and hides the visible pane.
 *
 * @param imageUrl the URL of the image to display in the right column 
 */
function switchFormPane(imageUrl){
	// set the appropriate image for the visible form pane
	dojo.query(".homePageIllustration")[0].src = imageUrl;
	if(dojo.byId("detailsFormPane").style.display == "none"){
		// first show the first form's pane
		showFormPane("details", "block");
		// now hide the second form's pane
		showFormPane("device", "none");
	}
	else{
		// first hide the first form's pane
		showFormPane("details", "none");
		// now show the second form's pane
		showFormPane("device", "block");
	}
}

/**
 * Sends a HTTP request to determine whether the provided identity is valid.
 *
 * @return true or false, according to whether the identity is recognized
 */
function checkIdentity(urlPattern){
	dojo.xhrPost({
		// use the SMS sending script omitting the typeSMS parameter to check the identity
		url: "/toolbox/sendSms.php",
		handleAs: "text",
		timeout: 10000,
		content: {
			phone: dojo.byId("phone").value,
			ident: dojo.byId("ident").value,
			mdp: dojo.byId("mdp").value,
			bu: dojo.byId("bu").value
		},
		load: function(response){
			// response may be either "0" or "1"
			switch(response){
				case "1":
					chooseBestInterface(urlPattern);
				break;
				case "2":
					dojo.byId("number_error").style.display = "block";
					dojo.byId("phone").focus();
				break;
				case "3":
					dojo.byId("id_error").style.display = "block";
					dojo.byId("ident").focus();
				break;
				case "4":
					dojo.byId("password_error").style.display = "block";
					dojo.byId("mdp").value = "";
					dojo.byId("mdp").focus();
				break;
				case"5":
					var server_span = dojo.byId("server_error");
					server_span.innerHTML = server_span.innerHTML+" (5)";
					server_span.style.display = "block";
				break;
				case "6":
					var server_span = dojo.byId("server_error");
					server_span.innerHTML = server_span.innerHTML+" (6)";
					server_span.style.display = "block";
				break;
				default:
					console.error("code error");
				break;
			}
		},
		error: function(response){
			console.dir(response);
		}
	});
}

/**
 * Checks and submits the main questionnaire.
 *
 * @param urlPattern the pattern of the URL to invoke if the form is valid
 * (@PGNAME@ will be replaced with the actual page name)
 */
function submitMainQuestionnaire(urlPattern){
	// first hide all the error messages
	dojo.forEach(dojo.query("#error_div span"),function(errorLabel){
		errorLabel.style.display = "none";
	});
	// locally perform a first check upon the phone number
	if(dojo.byId("phone").value.match(/^[\s0-9()+\.\-]+$/) == null){
		dojo.byId("phone").focus();
		dojo.byId("number_error").style.display = "block";
		return false;
	}

	// will asynchronously launch the interface choice if the identity is valid
	checkIdentity(urlPattern);
}

/**
 * Called after the form validation to choose the best mail interface.
 *
 * @param urlPattern the pattern of the URL to invoke if the form is valid
 * (@PGNAME@ will be replaced with the actual page name)
 */
function chooseBestInterface(urlPattern){
	var company = dojo.byId("company").value;
	var modelName = dojo.byId("model").value;
	var destinationPage;

	if(company == "Apple" && modelName == 'iPhone'){
		// propose the iPhone application
		destinationPage = "interface_description_iphone";
	}
	else if(modelName == "other" || company == "other"){
		// propose the webmail
		destinationPage = "interface_description_wap";
	}
	else{
		// propose the appropriate Java application
		destinationPage = "interface_description_app";
	}

	dojo.byId("homeQuestionnaireForm").action = urlPattern.replace("@PGNAME@", destinationPage);
	dojo.byId("homeQuestionnaireForm").submit();
}

/*
* Load the two select list in the sms application form with the json file
*/
function loadSelectList(compagnyDefaultText,modelDefaultText){
defaultModelChoiceText = modelDefaultText;
	dojo.xhrPost({
		url: '/toolbox/portableModel.json',
		handleAs: "json-comment-filtered",
		timeout: 5000,
		load: function(response, ioArgs) { 
			var compagnyText = '';
			var modelText = '';
			var first =true;
			for(key in response){
				compagnyText += '<option value="'+key+'">'+key+'</option>';
				if(first){
					var tab = response[key];
					for(var i=0; i<tab.length; i++){
						modelText += '<option value="'+tab[i]+'">'+tab[i]+'</option>';
					}
				}
				first =false;
			}
			// IE8 also requires this operation
			if(dojo.isIE >= 6 && dojo.isIE <= 8){
				dojo.byId('company').outerHTML = '<select id="company" name="company" onchange="changeMobileModel(this)">\n<option value="default">'+compagnyDefaultText+'</option>\n'+compagnyText+'</select>';
				//dojo.byId('model').outerHTML = '<select id="model" name="model">\n<option value="default">'+modelDefaultText+'</option>\n'+modelText+'</select>';
				dojo.byId('model').outerHTML = '<select id="model" name="model">\n<option value="default">'+modelDefaultText+'</option>\n</select>';
			}
			else{
				dojo.byId('company').innerHTML = '\n<option value="default">'+compagnyDefaultText+'</option>\n'+compagnyText;
				//dojo.byId('model').innerHTML = '\n<option value="default">'+modelDefaultText+'</option>\n'+modelText;	
				dojo.byId('model').innerHTML = '\n<option value="default">'+modelDefaultText+'</option>\n';
			}
		    return response;
		},
		error: function(response, ioArgs) {
		    console.error("HTTP status code: ", ioArgs.xhr.status);
		    return response;
		}
	});
}

/*
* Update mobile model list when the company change
*/
function ofxChangeMobileModel(companyList, modelList){
var modelDefaultText = defaultModelChoiceText;
var _otherChoiceText = otherChoiceText;
//ajax post
	dojo.xhrPost({
		url: '/toolbox/ofxPortableModel.json',
		handleAs: "json-comment-filtered",
		timeout: 5000,
		load: function(response, ioArgs) { 
			var text = '';
			for(var key in response){
				if(key == companyList.value){
					var tab = response[key].models;
					for(var id in tab){
						text += '<option value="'+id+'">'+tab[id]+'</option>\n';
					}
					if(companyList.value != "Apple"){
						text += '<option value="other">'+otherChoiceText+'</option>';
					}
					dojo.byId("instructions").value = response[key].instructions.replace(/"/g, "&quot;");
				}
			}
			if(dojo.isIE >= 6 && dojo.isIE <= 8){
				dojo.byId('modelId').outerHTML = '<select id="modelId" name="modelId" '+
					'onchange="onMobileModelSelected(dojo.byId(\'company\'),this)">\n<option value="default">'+
					modelDefaultText+'</option>\n'+text+'</select>';
				// setting the outerHTML makes us lose the object in IE
				modelList = dojo.byId("modelId");
			}
			else{
				dojo.byId('modelId').innerHTML = '\n<option value="default">'+modelDefaultText+'</option>\n'+text;
			}
			if(companyList.value == "Apple"){
				modelList.disabled = "disabled";
				modelList.selectedIndex = 1;
			}
			else{
				// the model list is disabled if no valid constructor is selected
				var noConstructorSelected = (companyList.value == "default" || companyList.value == "other");
				modelList.disabled = noConstructorSelected ? "disabled" : "";
			}
			checkMobileModelValidity(companyList, modelList);

			return response;
		},
		error: function(response, ioArgs) {
		    console.error("HTTP status code: ", ioArgs.xhr.status);
		    return response;
		}
	});
}

/**
 * Called when a model is selected to check the form validity.
 *
 * @param companyList the DOM node of the company list
 * @param modelList the DOM node of the model list
 */
function onMobileModelSelected(companyList, modelList){
	checkMobileModelValidity(companyList, modelList);
}

/**
 * Checks the drop down lists to validate the form.
 *
 * @param companyList the DOM node of the company list
 * @param modelList the DOM node of the model list
 */
function checkMobileModelValidity(companyList, modelList){
	// the validation button is disabled if no valid model is selected
	var validChoice = (companyList.value == "other" || (companyList.value != "default" && modelList.value != "default"));
	dijit.byId("modelValidationButton").setDisabled(!validChoice);
	if(validChoice == true){
		// store the model's readable name (necessary to choose the interface and for the next pages' titles)
		var modelIdList = dojo.byId("modelId");
		var selectedModel = modelIdList.options[modelIdList.selectedIndex];
		if(modelIdList.value == "other"){
			// for unknown models, "other" must be specified
			dojo.byId("model").value = selectedModel.value;
		}
		else{
			// for known models, use the real name of the phone
			dojo.byId("model").value = selectedModel.innerHTML;
		}
	}
}

/**
 * Checks the validity of the contact and enable the validation button if needed.
 */
function checkContactFormValidity(){
	// trick: wait 1ms so the input's content is updated according to the current key press
	setTimeout(function(){
		var invalid = (dojo.byId("phone").value == "" || dojo.byId("ident").value == "" || dojo.byId("mdp").value == "");
		dijit.byId("questionnaireValidationButton").setDisabled(invalid);
	}, 1);
}

/*
* Update mobile model list when the company change
*/
function changeMobileModel(node){
var modelDefaultText = defaultModelChoiceText;
//ajax post
	dojo.xhrPost({
		url: '/toolbox/portableModel.json',
		handleAs: "json-comment-filtered",
		timeout: 5000,
		load: function(response, ioArgs) { 
			var text = '';
			var model = node.value;
			for(key in response){
				if(key == node.value){
					var tab = response[key];
					for(var i=0; i<tab.length; i++){
						text += '<option value="'+tab[i]+'">'+tab[i]+'</option>\n';
					}
				}
			}
			if(dojo.isIE >= 6 && dojo.isIE <= 8){
				dojo.byId('model').outerHTML = '<select id="model" name="model">\n<option value="default">'+modelDefaultText+'</option>\n'+text+'</select>';
			}
			else{
				dojo.byId('model').innerHTML = '\n<option value="default">'+modelDefaultText+'</option>\n'+text;
			}
		    return response;
		},
		error: function(response, ioArgs) {
		    console.error("HTTP status code: ", ioArgs.xhr.status);
		    return response;
		}
	});
}

/**
 * Called when the user accepts the proposed interface. This function either sends
 * an installation SMS or redirects the user to the AppStore.
 *
 * @param nextPageUrl URL of the page where top redirect in case of
 *	success (either the interface manual or a link to the AppStore)
 * @param errorPageUrl page where to redirect in case of an error
 * @param interfaceType the type of the chosen interface (app, wap, iphone)
 */
function confirmInstallation(nextPageUrl, errorPageUrl, interfaceType){
	var form = dijit.byId("installationForm");

	// for iPhone's, simply go to the App store
	if(interfaceType == "iphone"){
		window.location.replace(nextPageUrl);
		return;
	}

	// for other interfaces, trigger the appropriate SMS sending
	ofxDisplayLoader();
	dojo.xhrPost({
		url: form.action,
		form: form.id,
		handleAs: "text",
		timeout: 10000,
		load: function(response, ioArgs){
			dojo.forEach(dojo.query("#error_div span"),function(node){
				node.style.display = "none";
			});
			hideLoader();
			switch(response){
				case "1":
					var confirmationForm = dojo.byId("confirmationForm");
					confirmationForm.action = nextPageUrl;
					confirmationForm.submit();
				break;
				case "2":
					dojo.byId("number_error").style.display = "block";
				break;
				case "3":
					dojo.byId("id_error").style.display = "block";
				break;
				case "4":
					dojo.byId("password_error").style.display = "block";
				break;
				case"5":
				case "6":
					var server_span = dojo.byId("server_error");
					server_span.innerHTML = server_span.innerHTML+" (6)";
					server_span.style.display = "block";
				break;
				default:
					console.error("code error");
			}
			return response;
		},
		error: function(response, ioArgs){
			hideLoader();
			var server_span = dojo.byId("server_error");
			server_span.innerHTML = server_span.innerHTML+" (6)";
			server_span.style.display = "block";
			console.error(form.action+": error '"+response.toString()+"'");
		}
	});
}

/*
* SMS Form Post
*/
function SMSPost(id, redirect){
var form = dijit.byId(id);
var confirm = dojo.byId('confirmation_message');
var input = dojo.query("#"+id+" input[type='text'], #"+id+" input[type='password']");
var select = dojo.query("#"+id+" select");
var spanTmp = dojo.query("#"+id+" span");
var span = new Array();
for(var i=0;i<spanTmp.length;i++)
	span.push(spanTmp[i]);
var i = 0;
var valid = true;
//pour les selects
if(id == 'application_form'){
	var selectSpan = span[0];
	//on enlève les spans de la select liste et des boutons radio
	span.shift();
	span.shift();
	span.shift();
	dojo.forEach(select, function(node){
		if(node.value=='default'){
			selectSpan.className = 'errorShow';
			valid = false;
			dojo.byId('button_td').style.paddingRight = selectSpan.offsetWidth+'px';
			if(dojo.byId('cgu_row') != null)
				dojo.byId('cgu_row').style.paddingRight = selectSpan.offsetWidth+'px';
		}
		else{
			selectSpan.className = 'errorHide';
		}	
	});
}
//pour chaque input...
dojo.forEach(input, function(node){
	//on regarde d'abord si les champs sont vides
	var empty = false;
	if(node.value==''){
		span[i].className = 'errorShow';
		valid = false;
		dojo.byId('button_td').style.paddingRight = span[i].offsetWidth+'px';
		if(dojo.byId('cgu_row') != null)
				dojo.byId('cgu_row').style.paddingRight = span[i].offsetWidth+'px';
		empty = true;
	}
	else{
		span[i].className = 'errorHide';
	}
	//si le champ téléphone n'est pas vide on regarde qu'il n'y a que des chiffres
	if(!empty){
		if(i == 0 && !node.value.match(/^[\s0-9()+\.\-]+$/)){
			node.focus();	
			dojo.byId('number_error').style.display = 'block';
			valid = false;
			dojo.byId('button_td').style.paddingRight = 0;
			if(dojo.byId('cgu_row') != null)
				dojo.byId('cgu_row').style.paddingRight = 0;
		}
		else if(i == 0 && node.value.match(/^[\s0-9()+\.\-]+$/)){
			dojo.byId('number_error').style.display = 'none';
		}	
	}
	i++;
});
//si le formulaire n'est pas valide on arrete
if(!valid){
	return;
}
dojo.byId('button_td').style.paddingRight = 0;
if(dojo.byId('cgu_row') != null)
	dojo.byId('cgu_row').style.paddingRight = 0;
//ajax post
	displayLoader();
	dojo.xhrPost({
		url: form.action,
		form: form.id,
		handleAs: "text",
		timeout: 10000,
		load: function(response, ioArgs) { 
			//traitement selon la réponse renvoyée par le script
			dojo.forEach(dojo.query('#error_div span'),function(node){
				node.style.display = 'none';
			});
			hideLoader();
			switch(response){
				case '1':
					form.domNode.style.display = 'none';
					dojo.byId('error_div').style.display = 'none';
					dojo.byId('required').style.display = 'none';
					confirm.style.display = 'block';
					dojo.query('.borderTop')[0].style.display = 'block';
					dojo.query('.borderBottom')[0].style.display = 'block';
					dojo.byId('introduction').style.display = 'none';
					dojo.byId('inner_form_section').style.borderLeft = '1px solid #DCDCDC';
					dojo.byId('inner_form_section').style.borderRight = '1px solid #DCDCDC';
				break;
				case '2':
					dojo.byId('number_error').style.display = 'block';
					input[0].focus();					
				break;
				case '3':
					dojo.byId('id_error').style.display = 'block';
					input[1].focus();					
				break;
				case '4':
					dojo.byId('password_error').style.display = 'block';
					input[2].value = '';
					input[2].focus();
				break;	
				case'5':
					var server_span = dojo.byId('server_error');
					server_span.innerHTML = server_span.innerHTML+' (5)';
					server_span.style.display = 'block';
					setTimeout('window.location.replace(\''+redirect+'\')',5000);
				break;
				case '6':
					var server_span = dojo.byId('server_error');
					server_span.innerHTML = server_span.innerHTML+' (6)';
					server_span.style.display = 'block';
					setTimeout('window.location.replace(\''+redirect+'\')',5000);
				break;
				default:
					console.error('code error');
				break;
			}
		    return response;
		},
		error: function(response, ioArgs) {
			hideLoader();
		    return response;
		}

	});
}

/*
* Display the loader for OFX BU.
*/
function ofxDisplayLoader(){
	var wait = new dijit.DialogUnderlay({ id: "oop"});
	wait.show();
	var viewport = dijit.getViewport();
	var ecart = (viewport.w-1000)/2;
	var left = viewport.w/2-50;
	if(dojo.isFF != 0)
		left = left-ecart;
	var top = viewport.h/2-50;
	wait.domNode.innerHTML='<img src="/extension/OOPro/design/OOProDesign/images/r_loading_ofx.gif" style="z-index:999;position:absolute;left:'+left+'px; top:'+top+'px;" />\n'+wait.domNode.innerHTML;
	}

/*
* Display the loader
*/
function displayLoader(){
	var wait = new dijit.DialogUnderlay({ id: "oop"});
	wait.show();
	var viewport = dijit.getViewport();
	var ecart = (viewport.w-1000)/2;
	var left = viewport.w/2-50;
	if(dojo.isFF != 0)
		left = left-ecart;
	var top = viewport.h/2-50;
	wait.domNode.innerHTML='<img src="/extension/OOPro/design/OOProDesign/images/r_loading.gif" style="z-index:999;position:absolute;left:'+left+'px; top:'+top+'px;" />\n'+wait.domNode.innerHTML;
	}

/*
* Hide the loader
*/
function hideLoader(){
	dijit.byId('oop').destroy();
}

/*
* Init tips variable
*/
function initTips(index,hour,minute){
  tipsIndex=index;
 // delay=(hour*3600+minute*60)*1000;
  delay = 30000;
}

/*
* Go to the previous tip
*/
function previousTip(){
clearTimeout(timeout);
tipsIndex-= 2;
if(tipsIndex==-1)
	tipsIndex=tipsList.length-1;
if(tipsIndex==-2)
	tipsIndex=tipsList.length-2;
displayAllTips();
}

/*
* RollOver
*/
function rollOver(name){
var img = dojo.byId(name);
if(dojo.isIE==6){
img.style.filter = img.style.filter.replace("actif","rollover");
}
else{
img.src = img.src.replace("actif","rollover");
}
}

/*
* RollOut
*/
function rollOut(name){
var img = dojo.byId(name);
if(dojo.isIE==6){
img.style.filter = img.style.filter.replace("rollover","actif");
}
else{
	img.src = img.src.replace("rollover","actif");
}
}

/*
* Go to the next tip
*/
function nextTip(){
clearTimeout(timeout);
if(tipsIndex==tipsList.length)
	tipsIndex=0;
displayAllTips();
}

/*
* Pause in the tip
*/
function pauseTip(name){
var img = dojo.byId(name);
if (!pause){
	clearTimeout(timeout);
	if(dojo.isIE==6){
		img.style.filter = img.style.filter.replace("play","pause");
	}
	else{
		img.src = img.src.replace("play","pause");
	}
}
else{
	timeout=setTimeout(function(){displayAllTips()},delay);
	if(dojo.isIE==6){
		img.style.filter = img.style.filter.replace("pause","play");
	}
	else{
		img.src = img.src.replace("pause","play");
	}
	}
pause = !pause;
}

/*
* Add a tip in the tipList
*/
function addToTipsList(tip){
tipsList.push(tip.substring(1,tip.length-1));
}

/*
* Display a tip in the tips area
*/
function displayTip(index){
var tipUrl = tipsList[index];
dojo.xhrGet({
url: tipUrl,
handleAs: "text",
timeout: 5000,
load: function(response, ioArgs) {
          dojo.byId("textTip").innerHTML = response;
		  dojo.byId("count").innerHTML = (index+1)+"/"+tipsList.length;
          return response;
        },
error: function(response, ioArgs) { 
          console.error("HTTP status code: ", ioArgs.xhr.status);
          return response;
          }

});
tipsIndex++;
if(tipsIndex==tipsList.length)
	tipsIndex=0;
}

/*
* Display all tips
*/
function displayAllTips(){
displayTip(tipsIndex);
timeout=setTimeout(function(){displayAllTips()},delay);
}

/*
* Display contact page
*/
function displayContactPage(){
var values = dijit.byId("contactForm").getValues();
}

/*
* Add the site to the bookmarks with the title identifier
*/
function addToBookmark(title,fftext,saftext){
	if ( dojo.isIE !=0 && window.external && typeof(window.sidebar) == 'undefined') {
        window.external.AddFavorite(location.href,title);
		return;
    }
	var dialog = new dijit.Dialog({ id: "bookmark_dialog", title: "", style: "width:250px; height:130px;" });
	var dialogText = '<div><h2 id=\'bookmark_text\'></h2></div><button title="" dojoType="dijit.form.Button" style="position:absolute; bottom:5px; left:105px" onclick="dialogAction2()">OK</button>';
	dialog.titleBar.style.display='none';
	dialog.draggable = false;
	dialog.setContent(dialogText);
	dojo.body().appendChild(dialog.domNode);
	dialog.startup();
	dialog.show();	
	if(dojo.isFF != 0){
	dialog.layout();
	var top = dialog.domNode.style.top;
	top = top.substr(0,top.length-2);
	var left = dialog.domNode.style.left;
	left = left.substr(0,left.length-2);
	var width = dialog.domNode.style.width;
	width = width.substr(0,width.length-2)
	var height = dialog.domNode.style.height;
	height = height.substr(0,height.length-2)
	var newTop = top - height/2;
	var newLeft = left - width/2;
	dialog.domNode.style.top = newTop+'px';
	dialog.domNode.style.left = newLeft+'px';
	dojo.byId('bookmark_text').innerHTML = fftext;
	return;
	}
	if(dojo.isSafari != 0){
	dojo.byId('bookmark_text').innerHTML = saftext;
	return;
	}
}

/*
* Redirect to the same page with the new language
*/
function chooseLanguage(){
var link = dojo.byId('linkBox').value;
var lang = dojo.byId('langBox').value;
if(lang == 'empty')
	return
window.location.replace(link+lang);
}


/*
* Close the other TitlePane
*/
function closeOtherTitlePane(id){
var pane_clicked = dijit.byId(id);
var content = dojo.byId('content');
//special treatment for ie6 (ie sucks...)
if(dojo.isIE == 6 && dojo.byId('faq_cat') == undefined){
	content.style.overflow = 'hidden';
	var paneNode = pane_clicked.domNode.parentNode;
	setTimeout(function(){
		var newHeight = paneNode.clientHeight+76;
		if(newHeight < 465)
			newHeight = 470;
		var finish = false;
		var anim = setInterval(function(){
			var t = content.clientHeight;
			if(t < newHeight && !finish){
				t+= 40;
				content.style.height = t+'px';
				if(t >= newHeight){
					finish = true;
					clearInterval(anim);
				}
			}
			if(t > newHeight && !finish){
				t-= 40;
				content.style.height = t+'px';
				if(t <= newHeight){
					finish = true;
					clearInterval(anim);
				}
			}
			if(finish && content.style.height.substr(0,content.style.height.length-2) < paneNode.clientHeight+76){
				content.style.height = paneNode.clientHeight+76+'px';
				}
		},1);
	},300);
}
//align the left part to the content part
var left = dojo.byId('left');
setTimeout(function(){
	var contentHeight = content.clientHeight;
	left.style.height = contentHeight+'px';
},500);
var panes = [];
var nodes = dojo.query(".oopTitlePane");
for(var i=0;i<nodes.length;i++){
	if(id!=nodes[i].id)
		panes.push(dijit.byId(nodes[i].id));
}
for(var i=0;i<panes.length;i++){
	if(panes[i].open)
		panes[i].toggle();
}
}

/*
* Delete input fields
*/
function resetForm(){
var inputtext = dojo.query("input[type='text']");
var inputpass = dojo.query("input[type='password']");
for(var i=0;i<inputtext.length;i++){
	inputtext[i].value="";
}
for(var i=0;i<inputpass.length;i++){
	inputpass[i].value="";
}
}

/*
* Submit a form
*/
function submitForm(formId){
var form  = dijit.byId(formId);
if(form.validate()){
	if(formId=='retrieve_data_form'){
		exportPIM();
	}
	else{
	form.submit();
	}
}
}

/*
* Open the demo pop-up
*/
function openDemo(node,link,width,height){
window.open (link,'Demo', config='width='+width+',height='+height+',toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, directories=no, status=no')
}

/*
* Go to the FAQ section
*/
function goToFAQ(lien_faq){
var reg=new RegExp("(&amp;)", "g");
lien_faq = lien_faq.replace(reg,"&");
window.location.replace(lien_faq);
}

/*
* Go to the previous page
*/
function goBack(tabC,tabCUrl){
if(tabC==false){
	javascript:history.go(-1);
	return;
	}
var reg=new RegExp("(&amp;)", "g");
tabCUrl = tabCUrl.replace(reg,"&");
window.location.replace(tabCUrl);
}

/*
* Close the other Question
*/
function closeOtherQuestion(id){
var question = dijit.byId(id);
var panes = [];
var nodes = dojo.query("#faq_cat .oopFAQTitlePane");
for(var i=0;i<nodes.length;i++){
	if(id!=nodes[i].id){
		panes.push(dijit.byId(nodes[i].id));
		}
}
for(var i=0;i<panes.length;i++){
	if(panes[i].open)
		panes[i].toggle();
}
}

/*
 * Classic redirection
 */
function redirect(url){
    window.location.replace(url);
}

/*
* Check the dijit component with the inputId
*/
function checkInput(inputId){
	(dijit.byId(inputId) != undefined) ? dijit.byId(inputId).setChecked(true) : dojo.byId(inputId).checked=true;
}

/*
* show a basic dojo dialog form
*/
function showDialog(text,redirect){
	var dialogText = '<div><h2>'+text+'</h2></div><button title="" dojoType="dijit.form.Button" style="position:absolute; bottom:5px; left:105px" onclick="dialogAction(\''+redirect+'\')">OK</button>';
	var dialog = new dijit.Dialog({ id: "form_dialog", title: "", style: "width:250px; height:130px;" });
	dialog.titleBar.style.display='none';
	dialog.draggable = false;
	dialog.setContent(dialogText);
	dojo.body().appendChild(dialog.domNode);
	dialog.startup();
	dialog.show();	
	dialog.layout();
	if(dojo.isFF != 0){
		var top = dialog.domNode.style.top;
		top = top.substr(0,top.length-2);
		var left = dialog.domNode.style.left;
		left = left.substr(0,left.length-2);
		var width = dialog.domNode.style.width;
		width = width.substr(0,width.length-2)
		var height = dialog.domNode.style.height;
		height = height.substr(0,height.length-2)
		var newTop = top - height/2;
		var newLeft = left - width/2;
		dialog.domNode.style.top = newTop+'px';
		dialog.domNode.style.left = newLeft+'px';
	}
}

/*
* Hide the forum feedback dialog form and redirect
*/ 
function dialogAction(redirect){
	var dialog = dijit.byId('form_dialog');
	dialog.destroy();
	window.location.replace(redirect);
}
function dialogAction2(){
	var dialog = dijit.byId('bookmark_dialog');
	dialog.destroy();
}

/*
* Post forum topic and reply and redirect
*/
function forumPost(id,url,redirect,textDialogForm,type){
//form validation
	var tab = new Array();
	var form = dojo.query("#"+id+" input[type='text']");
	for(var i=0;i<form.length;i++)
		tab.push(form[i]);
	var textarea = dojo.query("#"+id+" textarea");
	tab.push(textarea[0]);
	var span = dojo.query("#"+id+" span");
	var i = 0;
	var valid = true;
	dojo.forEach(tab, function(node){
		if(node.value==''){
			span[i].className = 'errorShow';
			valid = false;
		}
		else{
			span[i].className = 'errorHide';
		}
		i++;
	});
	if(!valid){
		var ind = 0;
		if(type == 'topic')
			ind = 3;
		if(type == 'reply')
			ind = 2;		
		if(span[ind].className == 'errorShow')
			dojo.byId('button_td').style.paddingRight = span[ind].offsetWidth+'px';
		if(span[ind].className == 'errorHide')
			dojo.byId('button_td').style.paddingRight = 0;			
		return;
	}
	dojo.byId('button_td').style.paddingRight = 0;
//ajax post
	var wait = new dijit.DialogUnderlay({ id: "oop"});
	wait.show();
	dojo.xhrPost({
		url: url,
		form: id,
		handleAs: "text",
		timeout: 20000,
		load: function(response, ioArgs) { 
			showDialog(textDialogForm,redirect);
			wait.destroy();
		    return response;
		},
		error: function(response, ioArgs) {
		    console.error("HTTP status code: ", ioArgs.xhr.status);
		    return response;
		}

	});
}

/*
* Validate a form
*/
function validateForm(id,mailError){
	var form  = dojo.byId(id);
	var inputTmp = dojo.query("#"+id+" input[type='text']");
	var input = new Array();
	for(var i=0;i<inputTmp.length;i++)
		input.push(inputTmp[i]);
	var textarea = dojo.query("#"+id+" textarea");
	input.push(textarea[0]);
	var span = dojo.query("#"+id+" span");
	var i = 0;
	var valid = true;
	dojo.forEach(input, function(node){
		//on regarde si les champs sont vides
		if(node.value=='' && node.name!='customer_number'){
			span[i].className = 'errorShow';
			valid = false;
		}
		else{
			//sinon le message d'erreur disparait
			span[i].className = 'errorHide';
			//on regarde le mail
			if(node.name == 'mail'){
				//si il matche pas la regexp
				if(!node.value.match(/^\s*[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,3}\s*$/)){
					span[i].className = 'errorShow';
					span[i].innerHTML = mailError;
					valid = false;
				}
				else{
					span[i].className = 'errorHide';	
				}
			}
		}
		i++;
	});
	if(!valid){
		if(span[3].className == 'errorShow')
			dojo.byId('button_td').style.paddingRight = span[3].offsetWidth+'px';
		if(span[3].className == 'errorHide')
			dojo.byId('button_td').style.paddingRight = 0;			
		return;
	}
	dojo.byId('button_td').style.paddingRight = 0;
	form.submit();
}

/*
* Toggle the left menu
*/
function toggleMenu(menuId) {
	//Precondition
	if(menuId == '')
		return;
	if (dojo.byId(menuId)==null) {
		return;
	}	
	// the block to show	
	var box = dojo.query("ul", dojo.byId(menuId).parentNode)[0];

	// hide all but that block
	dojo.forEach(dojo.query("#menuUL ul"),function(node) {
		if(!menuOpen) { 
			if(node==box) {
				dojo.fx.wipeIn({node:node, duration:500}).play();
				if(node.parentNode.className=="expanded_menu_2"){
					node.parentNode.className="expanded_menu_2";
				}
				else{
					if(node.parentNode.className == "expanded_menu_4"){
						node.parentNode.className="expanded_menu_3";
					}
					else{
						node.parentNode.className="expanded_menu";
					}
				}
			}
			else {			
				dojo.fx.wipeOut({node:node, duration:0}).play();
					if(node.parentNode.className == "expanded_menu_4" || node.parentNode.className == "expanded_menu_3"){
						node.parentNode.className="expanded_menu_4";
					}
					else{
						node.parentNode.className="expandable_menu";
					}
			}
		}
		else{ 
			if(previousMenuId == menuId){
				if(node==box) {
					dojo.fx.wipeOut({node:node, duration:500}).play();
					if(node.parentNode.className == "expanded_menu_3"){
						node.parentNode.className="expanded_menu_4";
					}
					else{
						if(node.parentNode.className == "expanded_menu_4" || node.parentNode.className == "expanded_menu_3"){
							node.parentNode.className="expanded_menu_4";
						}
						else{
							node.parentNode.className="expandable_menu";
						}
					}
				}
			}
			else{		
				if(node==box) {
					if(menuOpen){
						dojo.fx.wipeIn({node:node, duration:500}).play();
						if(node.parentNode.className == "expanded_menu_4"){
							node.parentNode.className="expanded_menu_3";
						}
						else{
							node.parentNode.className="expanded_menu";
						}
					}
				}
				else {
					dojo.fx.wipeOut({node:node, duration:0}).play();
					if(node.parentNode.className == "expanded_menu_4"  || node.parentNode.className == "expanded_menu_3"){
						node.parentNode.className="expanded_menu_4";
					}
					else{
					node.parentNode.className="expandable_menu";
					}
				}
				menuOpen = false;				
			}
		}
  });
  	menuOpen = !menuOpen;
	previousMenuId = menuId;
}

/*
* Init function which is called when a page is loaded
*/
function init() {
  // initialize ofx page
  if(dojo.byId('top_part') != null){
	if(dojo.byId('application') != null)
		changeMobileTextZone('application','mobile','left');
	if(dojo.byId('widget') != null)
		changeMobileTextZone('widget','pc','left');  
	if(dojo.isIE == 6)
		dojo.byId('oop').style.width = '980px';
  }
  if(dojo.isIE == 6 && dojo.byId('inner_form_section_ofx') != null){
	dojo.byId('oop').style.width = '980px';
  }
  //remove the Tab tooltip in the oaf widgets
  if(dojo.byId('oaf_widget_layout_TabContainer_0_tablist') != null){
	var tabList = dojo.byId('oaf_widget_layout_TabContainer_0_tablist');
	tabList.title = '';
	//tabList.style.width = 800+'px'; // useless and harmful: should be done in CSS (800 is too much for IE)
  }
  var labelTabList = dojo.query('#oaf_widget_layout_TabContainer_0_tablist span');
  if(labelTabList.length != 0){
	dojo.forEach(labelTabList,function(node){
		node.title = '';
	});
  }
  //align the left part to the content part
  var content = dojo.byId('content');
  var left = dojo.byId('left');
  var leftHeight = (content.clientHeight<465) ? 465 : content.clientHeight;
  leftHeight = leftHeight+1;
  left.style.height = leftHeight+"px";
  //tabContainer special treatment for ie6
  if(dojo.isIE == 6){
	var tabPane = dojo.byId('pane');
	if(tabPane != undefined){
		var paneHeight = tabPane.clientHeight+76;
		content.style.height = paneHeight+'px';
	}
  }
  //menu initialisation
  menuOpen = false;
  var menus = dojo.query("#menuUL .expandable_menu .sub_item_2");
  if(menus.length != 0){
  menuOpen = true;
  var menuToOpen = menus[0].parentNode;
  if(dojo.isIE == 6){
  previousMenuId = menuToOpen.parentNode.childNodes[0].id;
  }
  else{
  previousMenuId = menuToOpen.parentNode.childNodes[1].id; 
  }
  menuToOpen.parentNode.className = "expanded_menu_3";
  dojo.fx.wipeIn({node:menuToOpen, duration:0}).play();
  }
  // connect the menu titles to the toggle function
  dojo.forEach(dojo.query("#menuUL .expandable_menu"),function(node) {
	dojo.connect(node, "onclick", function(evt){toggleMenu(node.id);});
  });
  //connect the titlepane to the titlepane function
  dojo.forEach(dojo.query(".dijitTitlePaneTitle"),function(node){
	dojo.connect(node, "onclick", function(){closeOtherTitlePane(node.parentNode.id);})
  });
  //connect the question to the question function
    dojo.forEach(dojo.query("#faq_cat .dijitTitlePaneTitle"),function(node){
	dojo.connect(node, "onclick", function(){closeOtherQuestion(node.parentNode.id);})
  });
  //faq question treatment if the question is displayed on two lines for ff
  if(dojo.isIE == 0){
	dojo.forEach(dojo.query("#oop #content #faq_cat .dijitInline"),function(node){
		node.style.height = node.parentNode.clientHeight+'px';
	});
  }
}

