$(document).ready(function() {
	// Handler
	handlerForLinks();
	handlerForRel();
	// displayOnce();
});

function displayOnce()
{
	if( ($.cookie('first_visit') == null) && (pv_ULG == "FR_FR") ){

		//var sAjaxPageUrl = oLink.attr('href');
		//var sFlash = "http://4frmgaora:9080/w/Wskins/mcl2008/images/750x450_voeux2012.swf";
		
		var sFlash = '<object width="700" height="450" style=""><param value="/Wskins/mcl2008/flashes/750x450_voeux2012.swf" name="movie"><param value="high" name="quality"><param value="transparent" name="wmode"><embed width="700" height="450" src="http://4frmgaora:9080/w/Wskins/mcl2008/images/750x450_voeux2012.swf" allowscriptaccess="always" flashvars="file=http://4frmgaora:9080/w/Wskins/mcl2008/images/750x450_voeux2012.swf&amp;autostart=true" style=""></object>'
		
		sFlash = "<div class=\"popupInner2\">" + sFlash + "<span class=\"clear\">&nbsp;</span>";
		$(this).easyPopup({sHtml:sFlash});
		$.cookie('first_visit', 'true', { expires: 90 });
	}
}

//////////////
// HANDLERS //
//////////////
// To handle all the links giving actions like 'ADDFIELDSET', 'REMOVEFIELDSET' etc ...
function handlerForLinks()
{
	//Check all the links 'a' using rel attributes
	$("a[rel]").each( function() {
		// Rel format : ACTION##...##...
		var aAllValues = $(this).attr("rel").split("##");
		
		// 'ADDFIELDSET' used with '+' in the dynformitem fieldsetend
		if ( aAllValues[0] == "ADDFIELDSET" )
		{
			$(this).bind("click", {oCurrentElement: $(this), lookForType: "FIELDSET"}, cloneAndCopyElement);
		}
		
		// 'DELETEFIELDSET' used with '-' in the dynformitem fieldsetend
		if ( aAllValues[0] == "REMOVEFIELDSET" )
		{
			$(this).bind("click", {oCurrentElement: $(this), lookForType: "FIELDSET"}, removeElement);
		}
	});
}

// To handle all the submit buttons or links for next(+1), previous(-1) or specific(+/- n) action
function handlerForRel()
{
	$("input[type=submit][rel], a[rel], button[rel], input[type=radio][rel]").each( function() {
		// Rel format : ACTION##NUMBEROFSTEPS or ACTION##FIELD1//FIELD2//FIELD3##VALUE1//VALUE2//VALUE3##FORMID
		var aAllValues = $(this).attr("rel").split("##");
		
		// To submit form
		if ( aAllValues[0] == "SUBMITFORM")
		{
			$(this).bind("click", function( event ) {
				event.preventDefault();
				$("#formNextStep").val( aAllValues[1] );
				$("#formNextStep").parent().submit();
			});
		}
		
		// To fill fields and submit form
		if ( aAllValues[0] == "FILLANDSUBMIT")
		{
			$(this).bind("click", function( event ) {
				event.preventDefault();
				
				var aAllFields2 = aAllValues[1].split("//");
				var aAllValues2 = aAllValues[2].split("//");
				
				for (var k=0; k<aAllFields2.length; k++)
				{
					$("#" + aAllFields2[k]).val( aAllValues2[k] );
					
					if ( k == (aAllFields2.length-1) ) $("#" + aAllValues[aAllValues.length-1]).submit(); 
				} 
			});
		}
		
		// To use a specifi function with parameters
		if ( aAllValues[0] == "USEFUNCTION" )
		{
			// FORMAT :: USEFUNCTION##function##param1//param2 etc ...
			$(this).bind("click", function( event ) {
				
				var aAllParams = aAllValues[2].split("//");
				var sParams = "";
				
				for (var k=0; k<aAllParams.length; k++)
				{
					if ( k>0 ) sParams += ", ";
					sParams += "'" + aAllParams[k] + "'";
				}
				
				eval( aAllValues[1] + "(" + sParams + ")" );
			});
		}
	});
}

///////////////
// FUNCTIONS //
///////////////
// To clone a specified element and copy
function cloneAndCopyElement(event)
{
	// Prevent default action
	event.preventDefault();
	
	var oCurrentElement = event.data.oCurrentElement;
	var sLookForType    = event.data.lookForType;
	var oParent 		= getSpecificParent( oCurrentElement, sLookForType );

	// Copy element
	var oCopy = oParent.clone();
	
	// Insert the element after the current element
	oCopy.insertAfter( oParent );
	
	// Reset the copied element
	$(':input', oCopy).not(':button, :submit, :reset, :hidden').val('').removeAttr('checked').removeAttr('selected');
	
	// Rename the fieldset legend, the delete link and fields name etc ...
	renameProperties(sLookForType, oParent.next(), null, "");

	// Re handle all the specific links
	handlerForLinks();
}

// To delete a specified element
function removeElement(event)
{
	// Prevent default action
	event.preventDefault();
	
	var oCurrentElement = event.data.oCurrentElement;
	var sLookForType    = event.data.lookForType;
	var oParent 		= getSpecificParent( oCurrentElement, sLookForType );
	var sLegendTitle    = $("legend", oParent).html();
	var oGrandParent    = oParent.parent();
	
	// Remove the element
	oParent.remove();
	
	// Rename the fieldset legend, the delete link and fields name etc ...
	renameProperties(sLookForType, null, oGrandParent, sLegendTitle);
}

// To rename all the properties (legend, links, fields etc ...) according to the type of duplication
function renameProperties(sLookForType, oReference, oGrandParent, sLegendTitle)
{
	// FIELDSET case
	if ( sLookForType == "FIELDSET" )
	{
		// Delete case
		if ( (oReference == null) && (oGrandParent != null) )
		{
			sLegendTitle = transformEditoString( sLegendTitle );
			
			$("legend", oGrandParent.children()).each( function() {
				if ( $(this).html().indexOf( sLegendTitle ) != -1 ) oReference = $(this).parent();
			});			
		}
		
		// Delete and add cases
		var sNocssRemove 	= "nocss_removefieldset";
		var sTitle 	     	= transformEditoString( $("legend", oReference).html() );
		var sLinkTitle   	= transformEditoString( $("a." + sNocssRemove, oReference).html() );
		var aAllElems    	= new Array();
		var aHiddenMultiple = getHiddenMultipleValues( "hidden_multiple" );
						
		// Build array of fieldsets
		$(sLookForType + " legend", oReference.parent()).each( function() {
			// Same title part
			if ( $(this).html().indexOf( sTitle ) != -1 ) aAllElems[aAllElems.length] = $(this).parent();
		});
		
		// Rename the legend -- link -- link title -- field names
		for (var k=0; k<aAllElems.length; k++)
		{
			var sNewTitle 	  = sTitle;
			var sNewLinkTitle = sLinkTitle;
			
			if ( aAllElems.length > 1) 
			{
				sNewTitle 	  += " (" + (k+1) + ")";
				sNewLinkTitle += " (" + (k+1) + ")";
				
				// Visible delete link
				$("a." + sNocssRemove, aAllElems[k]).parent().css("visibility", "visible");
			}
			
			$("legend:first", aAllElems[k]).html( sNewTitle );
			$("a." + sNocssRemove + ":last", aAllElems[k]).html(sNewLinkTitle);
			$("a." + sNocssRemove + ":last", aAllElems[k]).attr("title", sNewLinkTitle);
			
			// Rename fields
			$("input, textarea, select", aAllElems[k]).each( function(){
				var sSeparator 	  = "##";
				var sFieldName 	  = $(this).attr("name");
				var sFieldId   	  = ( $(this).attr("id") != undefined ) ? $(this).attr("id") : "";
				var aNames     	  = sFieldName.split( "--" );
				var aFieldId   	  = sFieldId.split( sSeparator );
				var sNewFieldName = aNames[0];
				var sNewFieldId	  = aFieldId[0];
								
				if ( k > 0)	
				{
					sNewFieldName += "--" + (k+1);
					sNewFieldId   += sSeparator + (k+1);
				}
				
				$(this).attr("name", sNewFieldName);
				$(this).attr("id", sNewFieldId);
				$("label[for=" + sFieldId + "]", aAllElems[k]).attr("for", sNewFieldId);
				
				// Global container to modify
				if ( k > 0 )
				{
					var sParentId = $("label[for=" + sNewFieldId + "]", aAllElems[k]).parent().attr("id");

					if ( sParentId != undefined )
					{
						var aParentId = sParentId.split( sSeparator );
				
						$("label[for=" + sNewFieldId + "]", aAllElems[k]).parent().attr("id", aParentId[0] + sSeparator + (k+1));
					}
				}
				
				// Field counter to hide
				var aKeys = sFieldName.split("--");
				aHiddenMultiple[aKeys[0]] = (k+1);
			});

			// Invisible delete link
			if ( aAllElems.length <= 1) $("a." + sNocssRemove + ":last", aAllElems[k]).parent().css("visibility", "hidden");
		}
		
		makeHiddenMultipleValues( "hidden_multiple", aHiddenMultiple, aAllElems[0] );
	}
}

// To get an array of the hidden field for the multiple values
function getHiddenMultipleValues( sHiddenField )
{
	// Data format :: FIELDNAME__NUMBERELEMENTS##FIELDNAME2__NUMBERELEMENTS2##........
	var aHiddenMultiple = new Array();
		
	if ( $("#" + sHiddenField).size() > 0 )
	{
		var aTmp = $("#" + sHiddenField).val().split("##");
		for (var p=0; p<aTmp.length; p++)
		{
			var aTmp2 = aTmp[p].split("__");
			aHiddenMultiple[aTmp2[0]] = aTmp2[1];
		}
	}

	return aHiddenMultiple;
}

// To create the hidden multiple values
function makeHiddenMultipleValues( sHiddenField, aAllValues, oReference )
{
	var sValue  = "";
	var bPassed = false;
	
	for (var i in aAllValues)
	{
		if ( bPassed ) sValue += "##";
		sValue += i + "__" + aAllValues[i]
	
		bPassed = true;
	}
	
	// Add value to hte hidden field
	if ( $("#" + sHiddenField).size() > 0 ) $("#" + sHiddenField).val( sValue );
	else
	{
		var sHidden = "<input type=\"hidden\" name=\"" + sHiddenField + "\" id=\"" + sHiddenField + "\" value=\"" + sValue + "\" />";
		$( sHidden ).insertBefore( oReference );
	}
}

// To transform the string with (X) part
function transformEditoString( sString )
{
	var Expression = new RegExp("(\\((\\d)+\\)){1}$");
	
	if ( Expression.test(sString) ) sString = rtrim( sString.substring(0, sString.lastIndexOf("(")) );
	
	return sString;
}

// To get the wanted parent type element
function getSpecificParent( oCurrentElement, sWantedElement )
{
	do
	{
		oCurrentElement = oCurrentElement.parent();
		var sCurrentTag = oCurrentElement.get(0).tagName.toLowerCase();
	}
	while( (sCurrentTag != sWantedElement.toLowerCase()) || (sCurrentTag == "html") )
	
	return oCurrentElement;
}

// To disable a form input 
function disableInput( inputId )
{
	$("#" + inputId).attr("disabled", "true");
}

// To disable a form input 
function enableInput( inputId )
{
	$("#" + inputId).removeAttr("disabled");
}

// To trim string
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
// To left trim string
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
// To right trim string
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

////////////////////////
// SPECIFIC FUNCTIONS //
////////////////////////
// WEB CV (wcv)
function wcvCheckAgreement( inputName, inputSubmitId )
{
	if ( ($("#" + inputName + "1").size()>0) && ($("#" + inputName + "2").size()>0) )
	{
		var sTrue  = ($("#" + inputName + "1").val() == "true") ? "#" + inputName + "1" : "#" + inputName + "2";
		var sFalse = ($("#" + inputName + "1").val() == "false") ? "#" + inputName + "1" : "#" + inputName + "2";
		
		$(sFalse).bind("click", function( event ) { $("#" + inputSubmitId).attr("disabled", "true"); });
		$(sTrue).bind("click", function( event )  { $("#" + inputSubmitId).removeAttr("disabled"); });
		
		if ( $(sTrue).attr("checked") == true ) $("#" + inputSubmitId).removeAttr("disabled");
		else $("#" + inputSubmitId).attr("disabled", "true");
	}
}

function wcvDisablePrevious( inputId )
{
	if ( $("#" + inputId).size() > 0 ) $("#" + inputId).css("display", "none");
}

/*
function wcvForceSubmit()
{
	$("div.selectOption select").bind("keyup", forceSubmit);
	$("div.inputText input").bind("keyup", forceSubmit);
}

function forceSubmit(event)
{
	event.preventDefault();
	
	var bSend = false;
	
	if ( event.keyCode == "13")
	{
		var aSelects = $("div.selectOption select");
		var aInputs  = $("div.inputText input");
		
		for (var i=0; i<aSelects.length; i++)
		{
			
		}
	}
	
	// .genericForm
}
*/
