var samplecal;
var lastPage;
var finHide = true;
var arrayFrise = new Array();
var mouseX;
var	mouseY;	

// On positionne le logo 
function applyDynamicLayout() {
  var winwidth = (Element.getWidth(document.body) / 2) - 250;
	$("GRT_Logo").setStyle({left: winwidth});
	$("GRT_Logo").show();
 }
//Run applyDynamicLayout function when window is ready and when it resizes.
Event.observe(document, 'dom:loaded', applyDynamicLayout);
Event.observe(window, 'resize', applyDynamicLayout);


/*****
	NEW EFFECTS
 *****/
 Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height-2, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
      effect.element.makeClipping().setStyle({
        width: '0px',
        height: (effect.dims[0]-2) + 'px'
      }).show();
    },
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};

Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      scaleMode: 'box',
      scaleContent: false,
      restoreAfterFinish: true,
      afterSetup: function(effect) {
        effect.element.makeClipping().setStyle({
          height: (effect.dims[0]-2) + 'px'
        }).show();
      },
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};

/*****
	ModalBox Specific function with calendar
 *****/
Object.extend(Modalbox, {
_hide: function(event) { // Internal hide method to use with overlay and close link
		event.stop(); // Stop event propaganation for link elements
		/* Then clicked on overlay we'll check the option and in case of overlayClose == false we'll break hiding execution [Fix for #139] */
		if(event.element().id == 'MB_overlay' && !this.options.overlayClose) return false;
		this.hide();
		if(samplecal) {
			$('samplecal').hide();
			samplecal.destroy();
			samplecal= null;
			//alert("samplecalHide");
		}
		if(lastPage) {
			document.location.replace(lastPage);
			lastPage = null;
			document.location.reload();
			//alert("Update");
		}
		//this._removeElements();
	}
});


Object.extend(Modalbox, {
	show: function(content, options) {
		if(samplecal) {
			$('samplecal').hide();
			samplecal.destroy();
			samplecal= null;
			//alert("samplecalInit");
		}
		
		if(!this.initialized) this._init(options); // Check for is already initialized
		
		this.content = content;
		this.setOptions(options);
		//setRequestHeader( 'Set-Cookie' , 'PHPSESSID=' + this.options.phpsession );
		//alert(this.options.phpsession);
		
		if(this.options.title) // Updating title of the MB
			$(this.MBcaption).update(this.options.title);
		else { // If title isn't given, the header will not displayed
			$(this.MBheader).hide();
			$(this.MBcaption).hide();
		}
		
		if(this.MBwindow.style.display == "none") { // First modal box appearing
			this._appear();
			this.event("onShow"); // Passing onShow callback
		}
		else { // If MB already on the screen, update it
			this._update();
			this.event("onUpdate"); // Passing onUpdate callback
		} 
	}
});
/*****
	END ModalBox Specific function with calendar
 *****/



function respondToClick(event) {
	var element = event.element();
  	
  	if(!$('errmsg').visible() && !$('errmsg2').visible()) {
  		//element.disable();
  		$('loading').show();
		var form = $('ModalNextPage');
		var buttons = form.getInputs('image');

  		for (var index = 0, len = buttons.length; index < len; ++index) {
  			var item = buttons[index];
			item.disable();
		}
  	}
};
			
function respondToSubmit(event) {
	$('loading').show();
};
			

function load_formHeader() {
	if($('samplecal') != null) {
		var options = Object.extend({
				titleformat:'mmmm yyyy',
				closebutton:'X',
				dayheadlength:2,
				weekdaystart:0,
				planner: true
				},arguments[0] || { });
		samplecal = new scal('samplecal', updateyear, options);
		if($('day') != null)
			$('day').value =  samplecal.startdate.format('dd');
		if($('month') != null)
			$('month').value = samplecal.startdate.format('mm');
		if($('year') != null)
			$('year').value =  samplecal.startdate.format('yyyy');
		if($('samplecal_value') != null)
			$('samplecal_value').update(samplecal.startdate.format('dd mmmm yyyy'));
	}
};
			
/*****
	Calendar function
 *****/
function updateyear(d){
	$('samplecal_value').update(d.format('dd mmmm yyyy'));
	$('day').value = d.format('dd');
	$('month').value = d.format('mm');
	$('year').value = d.format('yyyy');
	this.toggleCalendar();
};

function displayCalendar(divCalendar,imgCalendar){
	var options = Object.extend({
			setWidth:false,
			setHeight:false,
			offsetLeft:20,
			offsetTop:-10
			},arguments[0] || { });
            
	new Element.clonePosition($(divCalendar),$(imgCalendar),options);
	samplecal.toggleCalendar();
};


/*****
	Quinzaine function
 *****/
 function displayQuinzaine(divQuinzaine,imgQuinzaine){
 //alert('displayQuinzaine');
	var options = Object.extend({
			setWidth:false,
			setHeight:false
			},arguments[0] || { }); 
	new Element.clonePosition($(divQuinzaine),$(imgQuinzaine),options);
	new Effect.Appear(divQuinzaine);
};


/*******
	Frise effect
********/
function displayAmout(img,div) {
	if ($(img).src.indexOf('Images/transparent.gif') < 0) {
		Effect.BlindDown(div);
	}
}

function hideAmout(div) {
	//alert("hide2");
	if($(div).visible() && finHide == true) {
		finHide = false;
		//alert("vrai");
		Effect.BlindUp(div);
		finHide = true;
		}
	//$(div).hide;
}


function grtsous_antiframe() {
	//if (!document.all) { 
	//	window.stop(); 
	//} else { 
	//	window.document.execCommand('Stop'); 
	//}   
}


/*******
	Popup effect
********/
function updateMouseCoordonate(e) {
	mouseX = Event.pointerX(e)-85;
	mouseY = Event.pointerY(e)-55;	
}

/*******
	Check form
********/
function checkRadio(elementName) {
	var form = $('ModalNextPage');	
	var checked = form.getInputs('radio', elementName).find(
		function(re) {return re.checked;}
		);

	if (checked != null && checked.name == "Operations") {
		if ($F(checked) == 3) {
			//alert(form.elements['Comptes2'].options[form.elements['Comptes2'].selectedIndex].value);
			form.elements['Comptes2'].enable();
			form.elements['TVA'].disable();
			form.getInputs('radio', 'Check').invoke('disable');
			checkListeVirement();
		} else {
			form.elements['Comptes2'].disable();
			form.elements['TVA'].enable();
			form.getInputs('radio', 'Check').invoke('enable');
		}
	}		
}
 
function checkListeVirement() {
	var form = $('ModalNextPage');
	if (form.elements['Comptes'].options[form.elements['Comptes'].selectedIndex].value == form.elements['Comptes2'].options[form.elements['Comptes2'].selectedIndex].value) {
			if (form.elements['Comptes'].selectedIndex == 0) 
				form.elements['Comptes2'].options[form.elements['Comptes'].selectedIndex+1].selected = true;
			else
				form.elements['Comptes2'].options[form.elements['Comptes'].selectedIndex-1].selected = true;
	}
};

// ***************************** DEPRECATED
// ********* ATTENTION CETTE FONCTION EST TOUJOURS UTILISEE
function checkForm(url, titleModal, methodModal, formName) {
	
	alert("Fonction grtsous.js:checkForm a remplacer par --globalEvents.fireEvent('evtCheckModalForm',Form.serialize('ModalNextPage',true))--");
		ok = true;
		
		if($('errmsg').visible()) {
			$('errmsg').hide();
			Modalbox.resizeToContent();
		}
	
		$$(".mandatory").each(  
			function(input) { 
				if (!input.present()) {
					//alert(input.type);
					if (ok)
						input.focus();
					ok = false;
					$(input).setStyle({
  						borderColor: '#7E0105'  						
						});
					}
			});
			
		if (ok) {
			new Ajax.Request('grtsous.php', {
				parameters: Form.serialize(formName),
  				onComplete: function(transport) {
  					returnString = transport.responseText.strip();
  					//alert('checkForm'+returnString);
  					if(returnString.startsWith("KO - ")) {
  						$('errtext').update(returnString.substring(5).stripScripts().toUpperCase());
  						$('loading').hide();
  						Modalbox.resizeToInclude('errmsg', {afterResize: function(){ $('errmsg').hide();new Effect.Appear('errmsg');}});

 						arrayEvtToFire	= returnString.substring(5).extractScripts();
  						arrayEvtToFire.each(function(evtToFire) {
							globalEvents.fireEvent(evtToFire);
						});
  					} else {
  						alert("A MIGRER : checkForm (else)");
  						$(formName).elements['action'].value = $(formName).elements['action'].value.sub('action','view');
  						$(formName).elements['action'].value = $(formName).elements['action'].value.sub('Login','Home');						
  					
  						if (titleModal.empty()) {
  							//$(formName).submit();
  							Modalbox.hide();
  							globalEvents.fireEvent("evtLoadDashboard");
  						}
  						else
  							Modalbox.show(url, {title: titleModal, width: 600, method: methodModal, params: Form.serialize(formName)});
  					}
				}
			});
		} else
			Modalbox.resizeToInclude('errmsg', {afterResize: function(){ $('errmsg').hide();new Effect.Appear('errmsg');}});
};


/*******
	Charts
********/
var requiredMajorVersion = 9;
var requiredMinorVersion = 0;
var requiredRevision = 45;

var chart_mensuel = AC_FL_RunContent(
	'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
	'width', '500',
	'height', '400',
	'scale', 'noscale',
	'salign', 'TL',
	'bgcolor', '#777788',
	'wmode', 'transparent',
	'movie', 'Images/charts/charts',
	'src', 'Images/charts/charts',
	'FlashVars', 'library_path=Images/charts/charts_library&xml_source=p_stats_news_xml.php%3FType%3Dmensuel',
	'id', 'my_chart',
	'name', 'my_chart',
	'menu', 'true',
	'allowFullScreen', 'true',
	'allowScriptAccess','sameDomain',
	'quality', 'high',
	'align', 'middle',
	'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
	'play', 'true',
	'devicefont', 'false');

var chart_moyenne = AC_FL_RunContent(
	'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
	'width', '500',
	'height', '400',
	'scale', 'noscale',
	'salign', 'TL',
	'bgcolor', '#777788',
	'wmode', 'transparent',
	'movie', 'Images/charts/charts',
	'src', 'Images/charts/charts',
	'FlashVars', 'library_path=Images/charts/charts_library&xml_source=p_stats_news_xml.php%3FType%3Dmoyenne',
	'id', 'my_chart',
	'name', 'my_chart',
	'menu', 'true',
	'allowFullScreen', 'true',
	'allowScriptAccess','sameDomain',
	'quality', 'high',
	'align', 'middle',
	'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
	'play', 'true',
	'devicefont', 'false');
	
var chart_histo = AC_FL_RunContent(
	'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
	'width', '500',
	'height', '400',
	'scale', 'noscale',
	'salign', 'TL',
	'bgcolor', '#777788',
	'wmode', 'transparent',
	'movie', 'Images/charts/charts',
	'src', 'Images/charts/charts',
	'FlashVars', 'library_path=Images/charts/charts_library&xml_source=p_stats_news_xml.php%3FType%3Dhisto',
	'id', 'my_chart',
	'name', 'my_chart',
	'menu', 'true',
	'allowFullScreen', 'true',
	'allowScriptAccess','sameDomain',
	'quality', 'high',
	'align', 'middle',
	'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
	'play', 'true',
	'devicefont', 'false');
	
var chart_epargne = AC_FL_RunContent(
	'codebase', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,45,0',
	'width', '500',
	'height', '400',
	'scale', 'noscale',
	'salign', 'TL',
	'bgcolor', '#777788',
	'wmode', 'transparent',
	'movie', 'Images/charts/charts',
	'src', 'Images/charts/charts',
	'FlashVars', 'library_path=Images/charts/charts_library&xml_source=p_stats_news_xml.php%3FType%3Depargne',
	'id', 'my_chart',
	'name', 'my_chart',
	'menu', 'true',
	'allowFullScreen', 'true',
	'allowScriptAccess','sameDomain',
	'quality', 'high',
	'align', 'middle',
	'pluginspage', 'http://www.macromedia.com/go/getflashplayer',
	'play', 'true',
	'devicefont', 'false');
function displayChart(swf_string) {
	$(mycharts).update(swf_string);
};