/* 
 * @author 3ACWebTemplate
 * Script réalisé par Nours312, contact[at]nours312.com
 * copyright nours312 !
 * -- Il existe de nombreux script Gratuits, évitez de pirater ceux qui n'ont pas été conçus pour vous !... merci ! --
 */

var PopupLink = Class.create({
	initialize : function(){
		$$('a[rel="popup3ac"]').invoke('observe', 'click', this.clickLink.bindAsEventListener(this));
	},
	clickLink : function(e){
		e.stop();
		var el = (e.element().href)?e.element():e.element().ancestors()[0];
		var title = el.title;
		var coo = [e.clientX, e.clientY];
		var hrefNet = el.href.substring(0,el.href.lastIndexOf('/')+1);

		new Ajax.Request(el.href, {
			method:'get',
			onComplete : function(xhr){
				var content = xhr.responseText.gsub(/\<head\>(.*?)\<\/head\>/, '').gsub(/\<title\>(.*?)\<\/title\>/, '').gsub(/\<meta\>(.*?)\<\/meta\>/, '').gsub(/\<link(.*?)\/\>/, '').gsub(/\<meta(.*?)\/\>/, '').gsub(/\<meta(.*?)\>/, '').gsub(/\<body (.*?)\<\/body\>/, '#{1}').gsub(/src\=\"([a-zA-Z0-9\/\.]*?)\"/, 'src="'+hrefNet+'#{1}"').gsub(/href\=\"([a-zA-Z0-9\/\.]*?)\"/, 'href="'+hrefNet+'#{1}"');
				new Popup3acTemplate(content, title, {'reloadAfterClick':true}, coo);
			}
		});
	}
});
var Popup3acTemplate = Class.create({
	popupOptions : {},
	titleOptions : {},
	backGroundOptions : {},
	backFrame : null,
	floatFrame : null,
	floatTit : null,
	floatTitle : null,
	closeSpan : null,
	floatCont : null,
	removable : false,
	reloadAfterClick : false,

	initialize : function(content, title, options, coo, removeable, multi){
		this.popupOptions = {
			border : "black 1px solid", // couleur de la bordure
			background: "#b5deb3", // couleur du BackGround
			position : 'absolute',
			zIndex : '1000' // IMPORTANT
		};
		this.titleOptions = {
			background : '#b5deb3',
			margin:0,
			postion:"relative",
			width:"100%",
			height:"20px",
			zIndex : 1010,
			borderBottom : "1px solid black"
		};
		this.backGroundOptions = {
			background: "#b5deb3", // couleur du BackGround
			width : "100%" , // IMPORTANT
			height : "100%", // IMPORTANT
			position : 'fixed', // IMPORTANT
			opacity : 0.5,
			cursor:'pointer',
			zIndex : '990', // IMPORTANT
			top:0,
			left:0
		};
		this.removable = (removeable != 'notRemovable')? true : false;
		if(multi !== true){
			if($('FloatFrameBack'))$('FloatFrameBack').remove();
			if($('FloatFrame'))$('FloatFrame').remove();
		}
		this.backFrame = new Element('div', {id : 'FloatFrameBack', className:'closeWithAjax'});
		if(options && options != 'undefined'){
			if(options.popupOptions && options.popupOptions != 'undefined')
				this.popupOptions = Object.extend(this.popupOptions, options.popupOptions || {});
			if(options.backGroundOptions && options.backGroundOptions != 'undefined')
				this.backGroundOptions = Object.extend(this.backGroundOptions, options.backGroundOptions || {});
			if(options.reloadAfterClick && options.reloadAfterClick != undefined){
				this.reloadAfterClick = options.reloadAfterClick;
			}
		}
		this.backFrame.setStyle(this.backGroundOptions);
		this.backFrame.setOpacity(this.backGroundOptions.opacity);
		this.floatFra = new Element('div', {id : 'FloatFrame'});
		$(document.body).insert({top:this.backFrame}).insert({top:this.floatFra});
		this.floatFra.setStyle(this.popupOptions);
		if(title != null && title != ''){
			this.floatTit = new Element('div', {className:'handle'});
			this.floatTit.setStyle(this.titleOptions);
			this.floatTitle = new Element('span', {style:'margin:5px;'});
			this.closeSpan = new Element('span', {className:'Close closeWithAjax',style:'position:absolute;right:5px; cursor:pointer;'});
			this.insertInto(this.floatTitle, title);
			this.closeSpan.innerHTML = 'X'; // texte ou HTML d'une image pour le lien de fermeture
			this.insertInto(this.floatTit, [this.closeSpan, this.floatTitle]);
			this.floatFra.insert(this.floatTit);
		}
		this.floatCont = new Element('div', {id:'floatCont3AcWebTemplatePopup', style:'margin:0; padding:0;width:100%;'});
		this.floatFra.insert(this.floatCont);
		this.insert(content);
		this.loadClick();
		this.open();
	},
	update : function(content){
		this.floatCont.innerHTML = '';
		this.insert(content);
	},
	insert : function(content){
		this.insertInto(this.floatCont, content);
	},
	insertInto : function(element, content){
		var reInsert = this.insertInto.bind(this);
		(content.message && content.message != undefined)? element.innerHTML += content.message : ((Object.isString(content))? element.innerHTML += content : ((Object.isArray(content))? content.each(function(el){reInsert(element, el);}) : element.insert(content)));
		if (this.reloadAfterClick){
			if(this.reloadAfterClick !== true)
				this.reloadAfterClick(content);
			else
				this.loadClick();
		}
	},
	open : function(){
		var dim = this.floatFra.getDimensions();
		var scroll = document.viewport.getScrollOffsets();
		this.floatFra.setStyle({top:((document.viewport.getHeight()-dim.height)/2)+scroll[1]+'px', left:((document.viewport.getWidth()-dim.width)/2)+scroll[0]+'px'});
		this.floatFra.hide();
		this.loadClick();
		var floatFra = this.floatFra;
		Effect.Grow(floatFra, {scaleFromCenter:true, afterFinish:function(){
			new Draggable(floatFra, {handle:'handle'});
		}});
	},
	loadClick : function(){
		var links = $$('#FloatFrame a').findAll(function(el){return (!el.hasClassName('closeWithAjax') && !el.hasClassName('gallery'));});
		links.invoke('stopObserving', 'click');
		links.invoke('observe', 'click', this.clickLink.bindAsEventListener(this));
		var forms = $$('#FloatFrame form');
		forms.invoke('stopObserving', 'submit');
		if(forms.length>0)
			forms[0].observe('submit', this.submitForm.bindAsEventListener(this))
		if(this.removable)
			$$('.closeWithAjax').invoke('observe', 'click', this.closeAll.bindAsEventListener(this));
		if($$('.tinyMceText')[0] != undefined)
			this.creatTinyMceElement();
	},
	clickLink : function(e){
		e.stop();
		var el = (e.element().nodeName.capitalize() == 'A') ? e.element() : e.element().ancestors()[0];
		var href = el.href;
		var insert = this.update.bind(this);
		var callBack = this.reloadAfterClick;
		new Ajax.Request(href, {parameters:{'ajax':1}, onComplete:function(xhr){insert(xhr.responseText.evalJSON());if(callBack !== true)callBack(xhr.responseText.evalJSON());}});
	},
	submitForm : function(e){
		e.stop();
		var insert = this.update.bind(this);
		var form = e.element();
		form.request({parameters:{'ajax':1}, onComplete:function(xhr){insert(xhr.responseText.evalJSON());}});
	},
	closeAll:function(e){
		if(e)
			e.stop();
		var b = [this.backFrame, this.floatFra];
		var f = this.floatFra;
		new Effect.SlideUp(f, {afterFinish:function(){
				b.invoke('remove');
			}});
	},
	creatTinyMceElement : function(){
		try{
			var tinymce_advanced_with_save_options = {
				theme : "advanced",
				mode : "textareas",
				language : "fr",
				skin : "o2k7",

				theme_advanced_buttons1 : "justifyleft,justifycenter,justifyright,justifyfull,|,bold,italic,underline,strikethrough,|,undo,redo,|,link,unlink,|,forecolor,backcolor,|,hr,removeformat,visualaid",
				theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,insertdate,inserttime,|,sub,sup,|,charmap,advhr,|,cite,abbr,acronym,del,ins,attribs,|,visualchars",
				theme_advanced_buttons3 : "styleselect,formatselect,fontselect,fontsizeselect,|,",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "center",
				theme_advanced_statusbar_location : true,
				theme_advanced_resizing : true,
				plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				content_css : "http://"+window.location.hostname+"/mail.css",
				template_replace_values : { username : "Some User", staffid : "991234" }
			};
			tinyMCE.init({
				theme : "advanced",
				mode : "textareas",
				language : "fr",
				skin : "o2k7",

				theme_advanced_buttons1 : "justifyleft,justifycenter,justifyright,justifyfull,|,bold,italic,underline,strikethrough,|,undo,redo,|,link,unlink,|,forecolor,backcolor,|,hr,removeformat,visualaid",
				theme_advanced_buttons2 : "bullist,numlist,|,outdent,indent,blockquote,|,insertdate,inserttime,|,sub,sup,|,charmap,advhr,|,cite,abbr,acronym,del,ins,attribs,|,visualchars",
				theme_advanced_buttons3 : "styleselect,formatselect,fontselect,fontsizeselect,|,",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "center",
				theme_advanced_statusbar_location : true,
				theme_advanced_resizing : true,
				plugins : "safari,spellchecker,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
				content_css : "http://"+window.location.hostname+"/mail.css",
				template_replace_values : { username : "Some User", staffid : "991234" }
			});
			var element = this.containerZone;
			var id = this.id;
			var Inpl = new Ajax.InPlaceRichEditor(element, '../AjaxRequest.html?&module=modules&function=savePageContent&env=admin&param='+id, {
				tinymceSave: true,
				tinymceToElementSize: true,
				cancelText: "annuler",
				okControl:false,
				cancelControl:false,
				highlightcolor:'#FF00FF',
				highlightendcolor:'#d8edd7'
			}, tinymce_advanced_with_save_options);
			Inpl.enterEditMode();
		} catch(e){console.log(e);}
	}
});
var Img = Class.create({
	options:{
		src:null,
		title:null,
		alt:'',
		loaderUrl:'http://'+window.location.hostname+'/adminDesign/loader.gif'
	},
	element:null,
	element2:null,
	callBack:null,

	initialize : function(options, callBackAfterLoad){
		this.callback = (callBackAfterLoad && callBackAfterLoad != 'undefined')?callBackAfterLoad : Prototype.emptyFunction;
		this.options = Object.extend(this.options, options || {});
		this.element = new Element('img');
		this.element.src = this.options.loaderUrl;
		this.element.title = this.options.title;
		this.element.alt = this.options.alt;
		this.element2 = new Element('img');
		this.element2.src = this.options.src;
		$(document.body).insert(this.element2);
		this.element2.hide();
		window.setTimeout(this.loading.bind(this), 100, this.callBack);
	},
	render : function(){
		return this.element;
	},
	loading: function(callBack){
		var dim = this.element2.getDimensions();
		if((!dim.width || !dim.height) || (dim.width<1 && dim.height<1) ){
			window.setTimeout(this.loading.bind(this), 100, callBack);
		}else{
			this.element.src = this.options.src;
			this.element.setStyle({width:dim.width+'px', height:dim.height+'px'});
			if(this.element.ancestors())
				this.element.ancestors()[0].setStyle({minWidth:dim.width+'px', minHeight:dim.height+'px'});
			callBack();
			this.element2.remove();
		}
	}
});
var Loading = Class.create({
	pop:null,
	text:null,
	initialize:function(text){
		var h3 = new Element('h3');
		var img = new Element('img');
		img.src = 'http://'+window.location.hostname+'/adminDesign/loader.gif';
		h3.innerHTML = text;
		this.pop = new Popup3acTemplate([h3, img], '', '', '', 'notRemovable', true);
	},
	close : function(){
		this.pop.closeAll();
	}
});

var ContextMenu = Class.create({
	container:null,
	elements : [],
	
	cssContainer : {
		position:'absolute',
		padding:'10px',
		background:'#B5DEB3'
	},
	cssElements : {

	},
	initialize : function(element, elements, options){
		this.elements = elements;
		element.observe('contextmenu', this.openContextMenu.bindAsEventListener(this));
		$(document.body).observe('click', this.close.bindAsEventListener(this));
		this.cssContainer = Object.extend(this.cssContainer, options || {});
	},
	openContextMenu : function(e){
		e.stop();
		this.container = new Element('ul', {className:'contextMenu'});
		this.container.setStyle(this.cssContainer);
		$$('.contextMenu').invoke('remove');
		$(document.body).insert(this.container);
		for(i=0; i<this.elements.length; i++){
			var li = new Element('li');
			li.innerHTML = this.elements[i][0];
			li.observe('click', this.elements[i][1]);
			this.container.insert(li);
			li.setStyle(this.cssElements);
		}
		var scroll = document.viewport.getScrollOffsets();
		this.container.setStyle({top:e.clientY-(this.container.getHeight()/2)+scroll[1]+'px', left:e.clientX-(this.container.getWidth()/2)+scroll[0]+'px'})
	},
	close : function(){
		if($(this.container))
			this.container.remove();
	}
});

var RetractableMenu = Class.create({
	actif:null,
	timer:null,
	menu:null,
	opennables:[],
	effectQueues:null,
	initialize : function(menu, classRetract){
		this.opennables = $$('.'+classRetract);
		this.menu = $(menu);
		//		this.menu.observe('mouseover', this.overMenu.bindAsEventListener(this));
		//		this.menu.observe('mouseout', this.outMenu.bindAsEventListener(this));
		$('MenuButton').observe('click', this.click.bindAsEventListener(this));
		$('MenuButton').setStyle({top : ((document.viewport.getHeight()/2)-20)+'px'});
		//		console.log($('MenuButton'));
	},
	overMenu : function(e){
		window.clearTimeout(this.timer);
		var func = this.openMenu.bind(this);
		if(!this.actif)
			this.timer = window.setTimeout(func, 300);
	},
	outMenu : function(e){
		var func = this.closeMenu.bind(this);
		this.timer = window.setTimeout(func, 500);
	},
	click : function(e){
		if (e.element().hasClassName('opennig')){
			e.element().removeClassName('opennig');
			e.element().src = e.element().src.gsub('pin', 'pout');
			this.closeMenu();
		} else {
			e.element().addClassName('opennig');
			e.element().src = e.element().src.gsub('pout', 'pin');
			this.openMenu();
		}
	},
	openMenu : function(e){
		var menu = this.menu;
		var actif = this.actif;
		var queues = this.effectQueues;
		var mainFunc = this.retractMain.bind(this);
		if (this.effectQueues != null)
			this.effectQueues.each(function(effect) { effect.cancel(); });
		new Effect.Move(menu, {
			x: 0, y: 0, mode: 'absolute',
			transition: Effect.Transitions.spring,
			afterFinish : function(){
				actif = true;
				mainFunc();
			}//,
			//			queue: { position: 'end', scope: queues }
		});
	},
	closeMenu : function(e){
		var menu = this.menu
		var actif = this.actif;
		var queues = this.effectQueues;
		var mainFunc = this.openMain.bind(this);
		if (this.effectQueues != null)
			this.effectQueues.each(function(effect) { effect.cancel(); });
		new Effect.Move(menu, {
			x: -240, y: 0, mode: 'absolute',
			transition: Effect.Transitions.spring,
			beforStart : function(){
				actif = false;
				mainFunc();
				//				console.log('start');
			}//,
			//			queue: { position: 'end', scope: queues }
		});
	},
	retractMain : function(){
		//		console.log(this.opennables, 'retract');
		this.opennables.invoke('setStyle', {'marginLeft':'260px'});
	},
	openMain : function(){
		///		console.log(this.opennables, 'open');
		this.opennables.invoke('setStyle', {'marginLeft':'20px'});
	}
});

/**
 *  manpulation automatique au passage de la souris ...
 */

var mouseOverEvent = Class.create({
	element:null,
	orignalSrc:null,
	image:false,
	initialize : function(element, effect){
		this.element = element;
		this.image = (element.hasAttribute('src'))?true:false;
		this.orignalSrc = (this.image) ? element.readAttribute('src') : element.getStyles('backgroundImage');
		this.element.observe('mouseover', this[effect+'Over'].bindAsEventListener(this));
		this.element.observe('mouseout', this[effect+'Out'].bindAsEventListener(this));
		this[effect+'Out']();
	},
	changeOver : function(e){
		if (this.image)
			this.element.writeAttribute('src', this.element.readAttribute('src').gsub(/\.(jpg|jpeg|png|gif)/, function(match){return 'Over'+match[0];}));
		else
			this.element.setStyle({'backgroundImage' :  this.element.getStyle('backgroundImage').gsub(/\.(jpg|jpeg|png|gif)/, function(match){return 'Over'+match[0];})});
	},
	changeOut : function(e){
		if (this.image)
			this.element.writeAttribute('src', this.element.readAttribute('src').gsub(/Over/, ''));
		else
		this.element.setStyle({'backgroundImage' :  this.element.getStyle('backgroundImage').gsub(/Over/, '')});
	},
	opacityOver : function(e){
		new Effect.Opacity(this.element, { from: 0.5, to: 1, duration: .5 , queue: { position: 'end', scope: 'menuxscope' } });
	},
	opacityOut : function(e){
		new Effect.Opacity(this.element, { from: 1.0, to: 0.5, duration: 2, queue: { position: 'end', scope: 'menuxscope' } });
	}
});

var lancement = "";
document.observe('dom:loaded', function(){
	lancement = new PopupLink();
	new RetractableMenu('colgauche', 'retractMenuOpen');
	$$('.imgOver').each(function(el){new mouseOverEvent(el, 'change')});
	$$('.opaOver').each(function(el){new mouseOverEvent(el, 'opacity')});
});

var  copy2Clipboard = function(obj){
	var textRange = document.body.createTextRange();
	textRange.moveToElementText(obj);
	textRange.execCommand("Copy" );
}
