/**
 * <pre>
 * Permet de rediriger un flux dans une popup.
 * La popup peut être configurée pour avoir certaines dimensions, s'auto fermer, ...
 *
 * Le contenu de la popup peut retourner des informations à l'appelant via la méthode :
 * 	Window.returnValue( datas );
 *
 * Le contenu de la popup peut savoir si il est appelé via une action contribution par la méthode :
 * 	Window.isContributionPopup();
 *
 * Options possibles :
 * 	title : '', // Titre de la popup. Par défaut on prend l'attribut title.
	width: 'auto', // largeur de la fenetre. auto: calcul automatique, sinon mettre une largeur css ex: 200px
	height: 'auto', // hauteur de la fenetre. auto: calcul automatique, sinon mettre une hauteur css : 300px
	refreshOnClose : false, // Dès que la fenetre sera fermée alors doit on rafraichir la fenetre parente
	refreshOnReload: false, // Dès que la fenetre sera rechargée doit on rafraichir la fenetre parent
	autoClose : false, // Doit -on fermer la fenêtre dès qu'elle se recharge toute seule (submit, etc ...)
	onClose : function() {}, // Evenement sur onClose (avant refreshOnClose et refreshOnReload)
	afterLoad: function(window) {}, // Evenement intervient apres le chargement demandé, le parametre est le document de popup
	url: '', // Url à afficher dans la fenetre de contribution. Par défaut on prend l'attribut href.
	onReturnValue: function(window, datas) {
		return;
	}
 *
 * Exemple :
 * <code>
 * 	&lt;a href="toto.pdf" title="kk" target="contribution"&gt;view pdf&lt;/a&gt;
 * </code>
 *
 * Exemple  :
 * <code>
 * 	&lt;a 	href="&lt;c:url value="/wcm.jspz?form_action=popinlist&form_object=activated&select=1,2"/&gt;"
 * 		target="contribution"
 * 		data-bov3-contribution-options="{title:'dddd',onReturnValue:function(window,datas){ alert(datas);  }}"&gt;
 * 		clicme
 * 	&lt;/a&gt;
 * </code>
 *
 * Exemple :
 *  Il est possible également de gérer l'ouverture de la fenetre de contribution soi-même.<br/>
 *  Pour cela, il suffit de créer un lien <a href=""/> et de gérer le click en appelant contribution() avec les options.<br/>
 *  Dans ce cas, il ne faut surtout pas qu'il y ait un attribut 'target' sur le lien, parce que sinon l'appel serait en double.
 * 	<code>
 * 	&lt;a href="#" name="mybutton"&gt;clicme&lt;/a&gt;
 * 	&lt;script type="text/javascript"&gt;
 * 		jQuery(document).ready(function($) {
 * 			$("#mybutton").click( function() {
 * 				// calcul du selected dynamiquement
 *				var tmp = objectLinked.val();
 *				if ($.isArray(tmp)) tmp = tmp.join(",");
 *				var params = {
 *					form_action: 'popinlist',
 *					form_object: configuration.form_object,
 *					selected: tmp };
 *				// calcul du href dynamiquement
 *				$(this).attr('href', boState.getContextPath()+ '/wcm.jspz?' + $.param(params));
 * 				$(this).contribution({
 * 					title: 'mlkml',
 * 					onReturnValue: function(window, datas) {
						$(datas.array_ids).each(function() {
							alert("id="+$(this).get(0));
						});
 * 					}
 * 				});
 * 				return false;
 * 			} );
 * 		});
 * 	&lt;/script&gt;
 * </code>
 * </pre>
 *
 * <div class="depends">
 * 	jQuery
 * </div>
 *
 * @class
 * @name contribution
 * @static
 * @version 1.0
 */
(function($){
	$.fn.extend({
		contribution: function(optionsExtend) {

			//if (typeof(console)!='undefined') console.log("obj.contribution()...");
			
			var in_progress = jQuery(this).attr('data-bov3-contribution_progressing');
//			if (typeof(console)!='undefined') console.log("obj.contribution()... in_progress="+in_progress);
			if (typeof(in_progress)!='undefined' && in_progress!=null && in_progress!='') {
//				if (typeof(console)!='undefined') console.log("obj.contribution()... deja en cours .......");
				return;
			}
			jQuery(this).attr('data-bov3-contribution_progressing', 'true');
			try {
				
				//if (typeof(console)!='undefined') console.log("obj.contribution() try ... "+jQuery(this).attr('data-bov3-contribution_progressing'));
				
				var options = $.extend({
					title : '', // Titre de la popup. Par défaut on prend l'attribut title.
					width: 'auto', // largeur de la fenetre. auto: calcul automatique, sinon mettre une largeur css ex: 200px
					height: 'auto', // hauteur de la fenetre. auto: calcul automatique, sinon mettre une hauteur css : 300px
					refreshOnClose : false, // Dès que la fenetre sera fermée alors doit on rafraichir la fenetre parente
					refreshOnReload: false, // Dès que la fenetre sera rechargée doit on rafraichir la fenetre parent
					autoClose : false, // Doit -on fermer la fenêtre dès qu'elle se recharge toute seule (submit, etc ...)
					onClose : function() {}, // Evenement sur onClose (avant refreshOnClose et refreshOnReload)
					afterLoad: function(window) {}, // Evenement intervient apres le chargement demandé, le parametre est le document de popup
					url: '', // Url à afficher dans la fenetre de contribution. Par défaut on prend l'attribut href.
					onReturnValue: function(window, datas) {
						return;
					}
				}, eval('('+jQuery(this).attr('data-bov3-contribution-options')+')'));
	
				//if (typeof(console)!='undefined') console.log("obj.contribution()... options");
				
				options = $.extend(options, optionsExtend);
				if (options.width==null || options.width=='') options.width='auto';
				if (options.height==null || options.height=='') options.height='auto';
	
				if (typeof(options.title)=='undefined' || options.title==null || options.title=='' || options.title.length==0) options.title = this.attr('title');
				if (typeof(options.title)=='undefined' || options.title==null) options.title = '';
	
				/* Lecture de l'url */
				if (options.url==null || options.url=='' || options.url.length==0) options.url = this.attr('href');
				/* Réparation de l'url au cas où le developpeur n'a pas mis light */
				if (typeof(options.url)=='undefined' || options.url==null) options.url='';
				else options.url = options.url.replace(/^(\/([^\/]*)\/?)?wcm\.jsp/,'$1wcmlight.jsp');
	
				var frame = jQuery("iframe#contribution");
				options.loading=true;
				bov3Contribution.setCurrentOptions(frame[0], options);
	
				//if (typeof(console)!='undefined') console.log("obj.contribution()... attr('src','"+options.url+"' ...");
				
				// Les browsers ne veulent pas ouvrir d'iframe sur une url qui est deja dans une autre iframe
				// pour soi-disant eviter la recursivite ...
				// Donc ajoutons une date sur l'url pour qu'elle soit unique ...
				if (options.url.length>0) {
					if (options.url.indexOf('?')>-1) options.url += "&t="+(new Date().valueOf());
					else options.url += "?t="+(new Date().valueOf());
				}
				
				frame.attr('src', options.url);
				frame.trigger('preshow');
			} finally {
				jQuery(this).removeAttr('data-bov3-contribution_progressing');
				//if (typeof(console)!='undefined') console.log("obj.contribution()... ok");
			}
		}
	});
})(jQuery);

/* Grosse bidouille  pour IE9
 * En effet, nous devons surcharger plus tard la methode close de window, 
 * mais IE9 ne trouvera la surcharge que si on cree une fonction close !?
 */
try {
	var function_code_native = Window.prototype.close;
	function close() {
	//	alert('close window sans window devant function_code_native='+function_code_native);
		function_code_native();
	//	console.log('close');
	}
} catch (e) {
}
/* fin bidouille */

window.isContributionPopup = function() {
	return false;
}

window.returnValue = function(datas) {};


var bov3Contribution = {
	build: function() {
		//if (typeof(console)!='undefined') console.log('contribution.build ...');
		var divpopup = jQuery("div#framePopup");
		if (divpopup!=null && divpopup.size()==1) {
			//if (typeof(console)!='undefined') console.log('contribution.build ... end refused');
			return;
		}
		if (divpopup==null || divpopup.size()==0) {
			divpopup = new jQuery("<div id='framePopup'></div>");
			divpopup.append(
					new jQuery("<div id='frameBar'></div>")
						.css('color', '#FFFFFF')
						.css('background-color','#000000')
						.css('height', '16px')
						.css('width','100%')
						.css('padding', '5px 0px 5px 0px')
						.append(new jQuery("<div class='framePopupTitle'></div>")
							.css('float','left')
							.css('padding', '0px')
							.css('margin-left', '20px')
							)
						.append(new jQuery("<a class='popinDataviewlightClose' href='#'>&nbsp;</a>")
							.css('float', 'right')
							.css('height', '16px')
							.css('width', '16px')
							.css('padding', '0px')
							.css('margin-right', '7px')
							.click(function(){
								bov3Contribution.hide();
								return false;
							}))
						.append(new jQuery("<div class='clear'></div>"))
				);

			var extendedName = 'contribution';
			if (window.name!=null && window.name.substring(0,extendedName.length)==extendedName) {
				extendedName = extendedName+'_'+(new Date().valueOf());
			}

			var div_container = new jQuery("<iframe scrolling='auto' frameborder='0' src='about:blank' id='contribution' name='"+extendedName+"'></iframe>")
				.css('background','#FFFFFF')
//				.css('opacity','1.0') a ne pas mettre sinon le menu disparait !!! sous IE8
			;
			// TODO il faut laisser le nom même si nous ne l'utilisons pas, il peut toujours y avoir un target sur un form ou autre
			//div_container.removeAttr('name');
			// TODO

			// content
			divpopup.append(div_container);

			jQuery("body").append(new jQuery("<div id='divContributionTranslucide'></div>")).append(divpopup);
		}
		//background-color:white;filter:alpha(opacity=100);-moz-opacity:1.0;opacity: 1.0;
		var divtranslucide = jQuery("#divContributionTranslucide");
		divtranslucide.css('background-color','black')
			.css('-moz-opacity','0.5')
			.css('opacity','0.5')
			.css('position','fixed')
			.css('z-index','9999')
			.css('top','0px')
			.css('left','0px')
			.css('width','100%')
			.css('height','100%')
			.hide();

		divpopup.css('top','0px');
		divpopup.css('left','0px');
		divpopup.css('z-index',9999);
		divpopup.css('position','fixed');

		var div_container = divpopup.find("iframe#contribution");
		div_container.css('width','100%');
		div_container.css('height','100%');

		var window_resize = function() {
			try {
				//if (typeof(console)!='undefined') console.log("resize");
				var divpopup = jQuery("div#framePopup");
				var frameBar = jQuery("#frameBar");
				var current_window = jQuery(window);
				
				if (!frameBar.is(':visible')) {
					divpopup.width( current_window.width() );
					divpopup.height( current_window.height() );
					return;
				}

				var frame = jQuery("iframe#contribution");
				var options = bov3Contribution.getCurrentOptions(frame[0]);
				if ('auto'==options.width) {
					divpopup.width( current_window.width()-60 );
				}

				if ('auto'==options.height) {

					divpopup.height( current_window.height()-60 );
					frame.height( divpopup.innerHeight()-frameBar.outerHeight() );
				}

				if ('auto'!=options.width && 'auto'!=options.height) {
					divpopup.center({transition:0, withScrolling:false});
				}

			} catch (e) {
				alert(e);
			}
		};
		var window_resize_time = null;
		
		jQuery(window).resize(function() {
			// gerons intelligemment le resize pour ne pas le faire tous les demo-pixel ...
			if (window_resize_time!=null) clearTimeout(window_resize_time);
			window_resize_time = setTimeout(window_resize, 100);
		});
		
		div_container.bind("preshow", function() {
			bov3Contribution.show();
		});
		div_container.load(function(event) {
			//if (typeof(console)!='undefined') console.log(event);
			var window_iframe = this.contentWindow;
			//if (typeof(console)!='undefined') console.log('iframe reloaded ! ' + jQuery(this).attr('src') + " " + window_iframe.location.href);
			
			var current_href = window_iframe.location.href;

			window_iframe.close = function() {
				window_iframe.location.href="about:blank";
				return false;
			};

			var options = bov3Contribution.getCurrentOptions(jQuery(this)[0]);
			if (current_href!=null && current_href!='' && current_href!='about:blank') {

				window_iframe.returnValue = function(datas) {
					return options.onReturnValue( window_iframe, datas );
				};
				window_iframe.isContributionPopup = function() {
					return true;
				}

				var subframe = jQuery(this).contents().find("iframe#contribution");
				if (subframe!=null && subframe.size()>0) {
					//var extendedName = subframe.attr('name');
					var links = jQuery(this).contents().find("a[target='contribution']");
					//links.attr('target',extendedName);
					links.removeAttr('target');
					links.attr('data-target-old','contribution');
				}

				if (options.loading==true) {
					bov3Contribution.show();
					options.loading=false;
				} else if (options.autoClose) {
					// On vient de nous demander de recharger la page alors que nous avions déjà chargé une page
					// Donc la fenetre vient d'être rafraichie
					jQuery(this)[0].src='';
					//
					if (options.refreshOnReload) window.location.href = window.location.href;
					return;
				}
				// La fenetre vient d'etre chargée ou rechargée
				options.afterLoad(window_iframe);

			} else {
				options.onClose();
				bov3Contribution.hide();
				if (options.refreshOnClose) window.location.reload(true); /*href = window.location.href;*/
			}
		});

		// Par défaut on cache
		divpopup.css('visibility','hidden');
		//if (typeof(console)!='undefined') console.log('contribution.build ... end');
	},
	//,
	setCurrentOptions: function(frame, opts) {
		jQuery.data(frame, '__bov3_contribution_saved_options', opts);
	},
	getCurrentOptions: function(frame) {
		var current_options = jQuery.data(frame, '__bov3_contribution_saved_options');
		if (current_options==null) {
			current_options = {
				title : '',
				width: 'auto',
				height: 'auto',
				refreshOnClose : false, // Dès que la fenetre sera fermée alors doit on rafraichir la fenetre parente
				refreshOnReload: false, // Dès que la fenetre sera rechargée doit on rafraichir la fenetre parent
				autoClose : false, // Doit -on fermer la fenêtre dès qu'elle se recharge toute seule (submit, etc ...)
				onClose : function() {}, // Evenement sur onClose (avant refreshOnClose et refreshOnReload)
				afterLoad: function() {}, // Evenement permettant apres le chargement demandé
				onReturnValue: function(window, datas) {
					return;
				},
				loading: true,
				url:''
			};
		};
		return current_options;
	},
	getWindow: function(obj) {
		var doc = null;
		if (obj.ownerDocument) doc = obj.ownerDocument;
		else doc = obj;
		return (doc.parentWindow?doc.parentWindow:doc.defaultView);
	},
	initSize: function(divpopup) {
		if (divpopup.size()==0) return;
		
		//if (typeof(console)!='undefined') console.log('contribution.initSize ...');
		
		var frameTitle = divpopup.find("div.framePopupTitle");
		var frame = divpopup.find("iframe#contribution");
		var frameBar = divpopup.find("#frameBar");

		frameBar.show();

		frame.css('overflow', '');

		var currentWindow = jQuery(bov3Contribution.getWindow(divpopup[0]));

		var options = bov3Contribution.getCurrentOptions(frame[0]);
		//if (typeof(console)!='undefined') console.log('options.title: ' + options.title + " w:" + options.width + " h:" + options.height + " src:" + frame.attr('src'));

		var subframe = frame.contents().find("body");

		var width = options.width;
		frame.css('width', '100%');
		frameBar.css('width', '100%');
		if (width!='auto') {
			// Largeur forcée
			divpopup.css('width', width);
		/*} else if (subframe.children().size()==1) {
			divpopup.width( subframe.children().first().width() );*/
		} else {
			// Largeur automatique
			divpopup.width( currentWindow.width()-60 );
		}
		if (divpopup.width()>currentWindow.width()-60) divpopup.width(currentWindow.width()-60);


		frameBar.height( 25 );

		var height = options.height;
		if (height!='auto') {
			// Hauteur forcée
			frame.css({'height': height});
			divpopup.height( frame.outerHeight()+frameBar.outerHeight() );
		/*} else if (subframe.children().size()==1) {
			frame.height(subframe.children().first().height());
			frameBar.height( frameBar.innerHeight());
			divpopup.height( frame.outerHeight()+frameBar.outerHeight() );*/
		} else {
			// Hauteur automatique
			divpopup.height( currentWindow.height()-60 );
			frame.height( divpopup.innerHeight()-frameBar.outerHeight() );
		}
		if (divpopup.height()>currentWindow.height()-60) {
			divpopup.height(currentWindow.height()-60);
			frame.height( divpopup.innerHeight()-frameBar.outerHeight() );
		}

		//if (typeof(console)!='undefined') console.log('contribution.initSize ... end');

	},
	show: function() {
		//if (typeof(console)!='undefined') console.log('contribution.show ...');

		var history_title = '';
		// On est sur la popinA et on veut afficher la popinB
		
		// en preshow: window == fenetre dans laquelle est mon iframe
		// en show : window == pareil
		
		// trouver le titre de la fenetre parente si il y en a
		if (window.parent!=null) {
			var pparent = window.parent;
			// on ne veut pas la fenetre dans laquelle nous sommes (iframe)
			// parce que sinon nous allons trouver notre titre et pas le precedent
			if (pparent!=window) {
				var parent_framePopup = $(pparent.document).find("div#framePopup"); // Conteneur de la popinA
				if (typeof(parent_framePopup)!='undefined' && parent_framePopup!=null && parent_framePopup.size()>0) {
					var frametitle = parent_framePopup.find("div.framePopupTitle > h1");
					if (frametitle.size()==0) {
						history_title = ""; //"pas trouvé div.framePopupTitle > h1";
					} else {
						history_title = frametitle.text();
					}
				} else history_title='';
			} else history_title='';
		} else history_title='';
		
		if (window.parent!=null) {
			// On va afficher une popinB dans une popinA

			// On doit trouver le parent de popinA
			// Redimenssionner la popinA pour prendre toute la place
			var parent = jQuery(window.parent.document); // parent de popinA
			parent.find("div#frameBar").hide(); // On cache le titre de la popinA
			var parent_framePopup = parent.find("div#framePopup"); // Conteneur de la popinA
			
//			history_title = parent_framePopup.find("div.framePopupTitle > h1").text("old").text();
			parent_framePopup.css({top:0,left:0}); // en 0,0

			//parent.find("iframe#contribution").css('overflow','hidden'); // Il n'y a plus d'ascenseur dans l'iframe de la popinA
			parent.find("iframe#contribution").css('width','100%').css('height','100%'); // l'iframe de la popinA va tout prendre
			// On supprime l'ascenseur sur la fenetre parent de la popin A
			var parent_body = parent.find("body"); 
			var old_attr = parent_body.attr('data-save-overflow');
			if (typeof(old_attr)=='undefined' || old_attr==null) {
				// on ne memorise pas deux fois
				parent_body.attr('data-save-overflow', parent_body.css('overflow'));
			}
			parent_body.css('overflow','hidden'); // Il n'y a plus d'ascenseur dans l'iframe de la popinA


			parent_framePopup.width(jQuery(window.parent).width()); // la popinA prend tte la largeur de son parent
			parent_framePopup.height(jQuery(window.parent).height()); // la popinA prend tte la hauteur de son parent

		} else {
			// On affiche la 1ere Popin
		}

		jQuery("#divContributionTranslucide").show();

		var divpopup = jQuery("div#framePopup");
		var frame = divpopup.find("iframe#contribution");
		if (frame.size()) {
			var frameTitle = divpopup.find("div.framePopupTitle");
			frameTitle.empty();
			
			var options = bov3Contribution.getCurrentOptions(frame[0]);
			if (options.title==null || options.title=='') options.title = "";

			var title = options.title;
			if (history_title!=null && history_title!='') {
				// Affichons l'ancien titre en le limitant
				if (history_title.length>100) history_title = "... " + history_title.substring(history_title.length-100);
				title = "<span>"+history_title + "</span> &gt; " + title;
			}
			frameTitle.html(new jQuery("<h1></h1>").html(title) );
		}
		bov3Contribution.initSize( 	divpopup	 );

		// Il faut que l'iframe soit invisible mais bien présente
		// pour que les targets fonctionnent correctement.
		divpopup.css('visibility','visible');

		divpopup.center({transition:0, withScrolling:false});

		// TODO : ca serait bien que l'iframe ait le focus
		//frame.contents().find("body").focus();
		
		
		//if (typeof(console)!='undefined') console.log('contribution.show ... end');

	},
	hide: function() {

		var divpopup = jQuery("div#framePopup");
		if (divpopup.css('visibility')=='hidden') return;
		//if (typeof(console)!='undefined') console.log('contribution.hide ...');

		/*
		 * On restaure sur le parent l'overflow
		 */
		if (window.parent!=null) {
			var parent = jQuery(window.parent.document);
			if (typeof(parent)!='undefined' && parent!=null) {
				var old_attr = parent.find("body").attr('data-save-overflow');

				/*if (typeof(old_attr)=='undefined' || old_attr==null) {
					old_attr='auto';
				}*/
				if (typeof(old_attr)!='undefined' && old_attr!=null) {
					parent.find("body").css('overflow', old_attr);
				}
				var parentPopup = parent.find("div#framePopup");
				if (typeof(parentPopup)!='undefined' && parentPopup!=null) {
					window.parent.bov3Contribution.initSize( parentPopup );
					parentPopup.center({transition:0, withScrolling:false});
				}
				
			}
			
		}

		jQuery("#divContributionTranslucide").hide();

		// Il faut que l'iframe soit invisible mais bien présente
		// pour que les targets fonctionnent correctement.

		divpopup.css('visibility','hidden');

		var frame = divpopup.find("iframe#contribution");
		if (frame!=null && frame.size()!=0) {
			var current_href = frame[0].contentWindow.location.href;
			if (current_href!=null && current_href!='' && current_href!='about:blank')
				frame[0].contentWindow.location.href = 'about:blank';
		}
		//if (typeof(console)!='undefined') console.log('contribution.hide ... end');

	}
};

(function($){
    $.fn.extend({
         center: function (options) {
              var options =  $.extend({ // Default values
                   inside:null, // element, center into window
                   transition: 0, // millisecond, transition time
                   minX:0, // pixel, minimum left element value
                   minY:0, // pixel, minimum top element value
                   withScrolling:false, // booleen, take care of the scrollbar (scrollTop)
                   vertical:true, // booleen, center vertical
                   horizontal:true // booleen, center horizontal
              }, options);
              return this.each(function() {
            	  options.inside=(options.inside?options.inside:bov3Contribution.getWindow(this));
            	  //if (typeof(console)!='undefined') console.log('center ...');
                   var props = {position:'fixed'};
                   if (options.vertical) {
                        var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                        if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                        top = (top > options.minY ? top : options.minY);
                        $.extend(props, {top: top+'px'});
                   }
                   if (options.horizontal) {
                         var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                         if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                         left = (left > options.minX ? left : options.minX);
                         $.extend(props, {left: left+'px'});
                   }

                   if (options.transition > 0) $(this).animate(props, options.transition);
                   else $(this).css(props);

                   return $(this);
              });
         }
    });

	$(function() {
		$(document).delegate("a[target='contribution'], a[data-target-old='contribution']", 'click', function() {
			$(this).contribution();
			return false;
		});
		bov3Contribution.build();
	});

    
})(jQuery);

