var GSPopin = (function (popinObject, openAtStart) {
	
	this.popin = popinObject;
	
	this.setSession = function () {
		new Ajax.Request(
				'inc/set-session.php',
				{
					method: 'post',
					parameters: {vu: "true"},
					onSuccess: function() { },
					onFailure: function() { if(window.console) {console.log("Echec écriture session!")} }
				}
			);
	};
	
	
	this.show = function (el) {
		Event.stop(el);
		var popinId = el.target.hash;

		popinId = popinId.replace("#", "");
		
		this.open(popinId);
	};
	
	
	this.close = function () {
		var popinId = this.popin.id;
		
		$("bgPopin").setStyle({display: "none"});
		$(popinId).setStyle({display: "none"});
		
		if (Prototype.Browser.IE && 
			parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6) {
			$$("select").each (function(el){
				$(el).setStyle({visibility: $(el).lastDisplay});
			});
		}
		
		this.setSession();
	};

	
	this.hidePopin = function (el) {
		Event.stop(el);
		this.close();
	};
	
	this.bgClose = function (el) {
		Event.stop(el);
		this.close();
	};
	
	this.open = function () {
		var popinId = this.popin.id;
		var mainObj = this;
		$("bgPopin").setStyle({display: "block"});
		$(popinId).setStyle({display: "block"});
		
		this.centerPopin();
				
		$("bgPopin").observe("click", this.bgClose.bind(this));
				
		if (Prototype.Browser.IE && 
			parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf("MSIE")+5)) == 6) {

			$("bgPopin").setStyle({height: $$("body")[0].getDimensions().height});
			
			$$("select").each (function(el){
				$(el).lastDisplay = $(el).getStyle("visibility");
				$(el).setStyle({visibility: "hidden"});
			});
		}
		
	};
	
	this.centerPopin = function (){
		var popinId = this.popin.id;
		
		var popDim = $(popinId).getDimensions();
		var screenDim = document.viewport.getDimensions();
		var scrollOffsets = document.viewport.getScrollOffsets();

		var popLeft = screenDim.width / 2 - popDim.width / 2 + scrollOffsets.left;
		var popTop = screenDim.height / 2 - popDim.height / 2 + scrollOffsets.top;

		$(popinId).setStyle({left: popLeft+"px", top: popTop+"px"});
		
	};
	
	this.init = function () {
		var mainObj = this;
		
		if($$('a.open-popin[href=#'+this.popin.id+']') != null && 
			$$('a.open-popin[href=#'+this.popin.id+']').length > 0) {
			
			$$('a.open-popin[href=#'+this.popin.id+']').each(function(el){
				$(el).observe('click', mainObj.show.bind(mainObj));
			});
		}

		$$("#" + this.popin.id + " .close-popin").each(function(el){
			$(el).observe ("click", mainObj.hidePopin.bind(mainObj));
		});
		
		Event.observe(window, "resize", this.centerPopin.bind(this) );
		Event.observe(window, "scroll", this.centerPopin.bind(this) );
				
		if(openAtStart) {
			this.open();
		}
	};
	
	this.init();
	
});

