//Initialize EventManager object to control JS loading synchro
var oEventsManager = new EventsManager( {iDelayTimeOut: 30000} );

/**
 * Position the footer when content is not too long for current page
 */
var putFooterAtRealBottom = function()
{
	if( $('header') && $('content-container') )
	{
		var dim = $("header").getSize();
		dim.x += $("content-container").getSize().x;
		dim.y += $("content-container").getSize().y;
		var dimWindow = window.getSize();

		window.addEvents({
			"resize": function()
			{
				if($("header").getStyle("display") != "none" && $("content-container").getStyle("display") != "none" )
				{
					if(dim.y < dimWindow.y)
					{
						var header = $("header").getSize();
						var footer = $("footer").getSize();
						// 12px : height of the image content_top.png, top of the white rectangular
						var pageHeight = dimWindow.y - header.y - $("main").getStyle("padding-top").toInt() - $("main").getStyle("padding-bottom").toInt() - 12 - footer.y;
						$("main").setStyle("height",pageHeight);
					}
				}
			}
		});

		if(dim.y < dimWindow.y)
		{
			var header = $("header").getSize();
			var footer = $("footer").getSize();
			// 12px : height of the image content_top.png, top of the white rectangular
			var pageHeight = dimWindow.y - header.y - $("main").getStyle("padding-top").toInt() - $("main").getStyle("padding-bottom").toInt() - 12 - footer.y;
			$("main").setStyle("height",pageHeight);
		}

		oEventsManager.fireEvent('nextStep');
	}
}

/**
 * Allow the menu to be shown at rollover
 */
var menuInteractivity = function()
{
	$$("div.menu>div").each(
		//For each menu item
		function( oMenu )
		{
			//Get current menu title and sub menu
			var oTitle = oMenu.getElement("a");
			var oSub = oMenu.getElement("ul");

			//If element exists
			if( $chk(oTitle) && $chk(oSub) )
			{
				//Title events
				oTitle.addEvents({
					"mouseenter": function()
					{
						//On Enter sub menu is unhidable
						bHidable = false;
						oSub.setStyle('display', 'block');

						//Title is put on hover on style
						oTitle.set('style', '');
						if( !oTitle.hasClass("menuHover"))
							oTitle.addClass("menuHover");
					}
				});

				oTitle.getParent().addEvents({
					'mouseleave': function()
					{
						//Hide Menu
						oSub.setStyle('display', 'none');

						//Show properly Menu Title
						if( oTitle.hasClass("menuHover"))
							oTitle.removeClass("menuHover");

						//Reload specific Font for Menu Title
						Cufon.set('fontFamily', 'Helvetica BD Con');
						Cufon.replace(
							oTitle,
							{
								color:"#FFFFFF",
								fontSize:'16px',
								hover:"true"
							}
						);
					}
				});
			}
		}
	);

	oEventsManager.fireEvent('nextStep');
}

/**
 * Allow lang switcher to select another language
 */
var langSwitcher = function()
{
	var oElement = $$('div.language>div>a')[0];
	var oMenu = $$('div.language>ul')[0];

	if( oElement && oMenu )
	{
		oElement.addEvents({
			'mouseenter': function()
			{
				oMenu.setStyle('display', 'block');
				$$('div.language')[0].setStyle('background-image', 'none');
			}
		});

		$$('div.language')[0].addEvents({
			'mouseleave': function()
			{
				oMenu.setStyle('display', 'none');
				this.set('style', '');
			}
		});
	}

	oEventsManager.fireEvent('nextStep');
}

var loginManager = function()
{
	//Define login shower animation
	var oShowConnector = function( iIDPage )
	{
		//Build request to get HTML Connector
		var oRequest = new Request({
			url: "../content/popup/login.php",
			onSuccess: function( sLoginReturn )
			{
				var oLoginResponse = JSON.decode( sLoginReturn );
				if( oLoginResponse.html != "" && oLoginResponse.message == "OK" )
				{
					//############# GET HTML ELEMENT AND INJECT IT ############
					//Get HTML result of AJAX
					var oCurrent = new Element('div');
					oCurrent.set('html', oLoginResponse.html);
					oCurrent.inject($$('body')[0]);
					//########## END GET HTML ELEMENT AND INJECT IT ###########

					//################ STYLING TRANSITION ################
					//Build elements style
					$$('.flash_bg')[0].setStyle('display', 'none');
					$('header').fade('0.4');
					$('content-container').fade('0.4');
					$('extranetConnector').setStyle('display', 'block');
					$('extranetConnector').setStyle('opacity', '0');
					$$('#extranetConnector .opaque').setStyle('opacity', '0.8');

					$('extranetConnector').fade('in');

					$$('body')[0].scrollTo(0);
					$$('body')[0].setStyle('overflow','hidden');
					$('pass').set('type', 'password');
					//############## END STYLING TRANSITION ##############

					//################ POSITION CONNECTION FORM ################
					//Move formular to the middle of the "page"
					var windowSize = window.getSize();
					var mainSize = $$('#extranetConnector .mainConnector')[0].getSize();
					var hauteur = windowSize.y/2 - mainSize.y/2;
					$$('#extranetConnector .mainConnector')[0].setStyle("padding-top",hauteur);
					//############## END POSITION CONNECTION FORM ##############

					//################ ADD NEW POPUP EVENT ################
					$$('#extranetConnector .close_button').addEvents({
						'click': function()
						{
							$$('.flash_bg')[0].setStyle('display', 'block');
							$('header').fade('in');
							$('content-container').fade('in');
							$('extranetConnector').getParent().destroy();
							$$('body')[0].set('style','');
						}
					});

					$('login_button').addEvents({
						'click': function()
						{
							var sLogin = $('login').get('value');
							var sPass = $('pass').get('value');
							if( sLogin != "" && sPass != "")
							{
								var oConnection = new Request({
									url: "../content/popup/login.php",
									onSuccess: function( sConnectReturn )
									{
										if( sConnectReturn != "")
										{
											var oResponse = JSON.decode(sConnectReturn);
											if( oResponse.message == "Connected" )
											{
												var oExtranetPage = new URI( oResponse.url );
												oExtranetPage.go();
											}
											else
											{
												$$('#extranetConnector input').setStyle('border', '1px solid red');
												$('login').set('value', "Login incorrect");
												$('pass').set('value', "Mot de passe incorrect");
												$('pass').set('type', 'text');

												//Add focus event
												var oFocus = function(){
													$('login').set('value', '');
													$('pass').set('value', '');
													$('pass').set('type', 'password');
													$('login').removeEvent('focus', oFocus);
													$('pass').removeEvent('focus', oFocus);
												};

												$('pass').addEvent('focus', oFocus);
												$('login').addEvent('focus', oFocus);
											}
										}
									}
								});

								var oURI = new URI(window.location);
								var aVersion = oURI.get('file').match(/^.*([0-9]+).html/);
								oConnection.send("login="+sLogin+"&pass="+sPass+"&id="+iIDPage+"&version="+aVersion[1]);
							}
							else
								$$('#extranetConnector input').setStyle('border', '1px solid red');
						}
					});
					//############## END ADD NEW POPUP EVENT ##############
				}
				else
				{
					if( oLoginResponse.url != "" && oLoginResponse.message == "Connected" )
					{
						var oExtranetPage = new URI( oLoginResponse.url );
						oExtranetPage.go();
					}
				}
			}
		});

		//Send request
		var oURI = new URI(window.location);
		var aVersion = oURI.get('file').match(/^.*([0-9]+).html/);
		oRequest.send( "id="+iIDPage+"&version="+aVersion[1] );
	}

	//Put on each extranet link, login showing
	$$('a.lock').addEvent('click', function()
	{
		oShowConnector( this.get('rel') );
	});

	//If extranet connection need to be shown at load, execute associated function
	if( iShowExtranet != "" )
		oShowConnector( iShowExtranet );

	oEventsManager.fireEvent('nextStep');
}

var bgManager = function()
{
	var dim = $("header").getSize();
	dim.x += $("content-container").getSize().x;
	dim.y += $("content-container").getSize().y;

	$$('.flash_bg')[0].setStyle('height', dim.y);

	var flashvars = {
		id:$("bg_id").value,
		source:"xml/customer/conformable-background.xml",
		url:$('link_flash').get('value')
	};
	var params = {
		menu: "false",
		scale: "noScale",
		allowFullscreen: "true",
		allowScriptAccess: "always",
		wmode:'transparent',
		bgcolor: "#0f000f"
	};
	var attributes = {
		id:"SIDASheader"
	};
	swfobject.embedSWF("swf/SIDASheader.swf", "altContent", "100%", "100%", "9.0.0", "swf/expressInstall.swf", flashvars, params, attributes);
	oEventsManager.fireEvent('nextStep');
}

if ( oEventsManager && oEventsManager != null && oEventsManager != undefined )
{
	oEventsManager.registerEvent('putFooterAtRealBottom', putFooterAtRealBottom);
	oEventsManager.registerEvent('menuInteractivity', menuInteractivity);
	oEventsManager.registerEvent('langSwitcher', langSwitcher);
	oEventsManager.registerEvent('loginManager', loginManager);
	oEventsManager.registerEvent('bgManager', bgManager);
}
