/*  Popup Enquête Satisfaction
 *  (c) 2008-2010 Sociabliz (http://www.sociabliz.com)
 *  Written by StÃ©phane Akkaoui - modification VSC
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *  
 *      * Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *  
 *      * Redistributions in binary form must reproduce the above copyright
 *        notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 *  
 *      * Neither the name of Sociabliz nor the names of its contributors may
 *        be used to endorse or promote products derived from this software
 *        without specific prior written permission.
 *  
 *  THIS SOFTWARE IS PROVIDED BY SOCIABLIZ ''AS IS'' AND ANY EXPRESS OR IMPLIED
 *  WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 *  IN NO EVENT SHALL SOCIABLIZ BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 *  TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 *  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 *  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *  
 *
 *--------------------------------------------------------------------------*/


function SATPopup(options) {	
	var defaultSettings = {
		nextSiteUrl: "http://srv1.cawi.fr/cgi-bin/cawi/Q/satvsc1004/satvsc1004.pl",
		waitingPopupUrl: "http://www.voyages-sncf.com/leisure/fr/popup/attente_enquete.html",
		waitingPopupWidth: 400,
		waitingPopupHeight: 360,
		displayRate: 1,
		cookiePrefix: "__SAT_",
		cookieName: "coolCookie",
		cookieTTL: 60,
		cookieValue: "true",
		cookieDomain: ".voyages-sncf.com",
		imageTypes: [ 'png', 'jpg', 'jpeg', 'gif' ],
		loadingImage: 'http://www.voyages-sncf.com/design/commons/img/loadinfo.gif',
		closeImage: 'http://www.voyages-sncf.com/design/commons/img/b.gif',
		okImage: 'http://www.voyages-sncf.com/design/commons/img/b.gif',
		opacity: 0.3,
		overlay: false,
		popupContent: '<h1>Cher(e) internaute,</h1><p>Votre avis compte beaucoup pour nous ! <br />Nous vous invitons donc à participer à notre enquête. Elle apparaîtra dans une nouvelle fenêtre, après avoir terminé votre visite. Cette enquête vous prendra environ 5 minutes.</p><p class="participate">Souhaitez vous y participer ?</p>',
		html: '<div id="SATPopup" style="display:none;"><div id="SATPopup_body"><p id="SATClose" class="close_button"><a href="#">Fermer X</a></p><div id="SATPopup_content"></div><div class="SATPopup_footer"> <p class="p_submit"><a class="button-primary" href="#" id="SATPopup_close" title="Je ne souhaite pas participer à l\'enquête">Non<img src="" id="SATPopup_close_image" /></a><a class="button-primary" href="#" id="SATPopup_ok" title="Je souhaite participer à l\'enquête">Oui<img src="" id="SATPopup_ok_image" /></a></p> </div></div></div>'
	};
	this.pendingPopup = null;
	this.displayed = false;
	this.settings = this.extend(defaultSettings, options || {});
};
 
SATPopup.prototype = {
	cookieName: function(name) {
		return this.settings.cookiePrefix + name;
	},
	
	setCookie: function(name, value, ttl) {
		if (!ttl) {
			var ttl = this.settings.cookieTTL;
		}
		var date = new Date();
/*		date.setTime(date.getTime() + (ttl * 24 * 60 * 60 * 1000));	*/
		date.setTime(date.getTime());
		var expires = "; expires=" + date.toGMTString();		
		var domain = (this.settings.cookieDomain) ? ";domain=" + this.settings.cookieDomain : ""

		document.cookie = this.cookieName(name) + "=" + escape(value) + expires + "; path=/" + domain;
	},

	getCookie: function(name) {
		var nameEQ = this.cookieName(name) + "=";
		var ca = document.cookie.split(';');
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	},

	removeCookie: function(name) {
		this.setCookie(name, "", -1);
	},
	
	hasCookies: function() {
		return (this.getCookie(this.settings.cookieName) == null);
	},
	
	extend: function(destination, source) {
		for (var property in source)
			destination[property] = source[property];
		return destination;
	},
	
	bind: function(functionName, obj, params) {
		var __method = functionName;
	    return function(event) {
	      return __method.apply(obj, [event || window.event].concat(params));
	    }
	},
	
	observe: function(element, eventName, handler) {
      if (element.addEventListener) {
        element.addEventListener(eventName, handler, false);
      } else {
        element.attachEvent("on" + eventName, handler);
      }

      return element;
    },
	
	getPageScroll: function() {
	  	var xScroll, yScroll;

	  	if (self.pageYOffset) {
	    	yScroll = self.pageYOffset;
	    	xScroll = self.pageXOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
	    	yScroll = document.documentElement.scrollTop;
	    	xScroll = document.documentElement.scrollLeft;
	  	} else if (document.body) {// all other Explorers
			yScroll = document.body.scrollTop;
	    	xScroll = document.body.scrollLeft;
	  	}

	  	return new Array(xScroll,yScroll);
	},

	getPageHeight: function() {
	  	var windowHeight;

	  	if (self.innerHeight) {	// all except Explorer
	    	windowHeight = self.innerHeight;
	  	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
	    	windowHeight = document.documentElement.clientHeight;
	  	} else if (document.body) { // other Explorers
	    	windowHeight = document.body.clientHeight;
	  	}

	  	return windowHeight;
	},
	
	skipOverlay: function() {
    	return this.settings.overlay == false || this.settings.opacity === null
  	},

  	showOverlay: function() {
    	if (this.skipOverlay()) return;

    	if (document.getElementById('SATPopup_overlay') == null) {
			if (! document.width) {
				var documentWidth = document.width ? document.width : document.documentElement.offsetWidth;
				var documentHeight = document.height ? document.height : document.documentElement.offsetHeight;
				document.body.style.height = documentHeight + 'px';
				document.body.style.width = documentWidth + 'px';
			}
			var node = document.createElement('div');
			node.className = 'SATPopup_overlayBG';
			node.id = 'SATPopup_overlay';
			
			node.style.opacity = this.settings.opacity;
			node.style.filter = "alpha(opacity=" + this.settings.opacity * 100 + ")";

	   		document.body.appendChild(node);
		}

    	return false;
	},
	
	hideOverlay: function() {
		if (this.skipOverlay()) return;
		
		var overlay = document.getElementById('SATPopup_overlay');
		
		overlay.style.className = 'SATPopup_hide'
   		overlay.parentNode.removeChild(overlay);

    	return false;
  	},
	
	close: function() {
		this.setCookie(this.settings.cookieName, this.settings.nextSiteUrl, this.settings.cookieTTL);
		this.setCookie(this.settings.cookieName, this.settings.cookieValue, this.settings.cookieTTL);
		document.getElementById('SATPopup').style.display = "none";
     	this.hideOverlay();
		
		var loadingNode = document.getElementById('protofacebox_loading');
		if (loadingNode != null) loadingNode.parentNode.removeChild(loadingNode);
		
      	return false;
	},
	
	waitForUnload: function() {
		if (this.settings.waitingPopupUrl != null) {
			this.pendingPopup = window.open(this.settings.waitingPopupUrl, 
											'SATPopup_window',
			 								'height=' + (this.settings.waitingPopupHeight || window.screen.availWidth) + 
											',width=' + (this.settings.waitingPopupWidth || window.screen.availHeight) +
											',scrollbars=yes,toolbars=no,location=no,resizable=yes');
			if(this.pendingPopup != null) {
				this.pendingPopup.blur();
				this.pendingPopup.nextSiteUrl = this.settings.nextSiteUrl;
			}
			window.focus();
		}

		this.close();
	},
	
	init: function() {
		if (this.settings.displayed) return true;
    	else this.settings.displayed = true;

    	var imageTypes = this.settings.imageTypes.join('|');
    	this.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')$', 'i');

		var node = document.createElement('div');
		node.innerHTML = this.settings.html;
		
   		document.body.appendChild(node);
	
		this.observe(document.getElementById('SATPopup_close'), 'click', this.bind(this.close, this));
		this.observe(document.getElementById('SATPopup_ok'), 'click', this.bind(this.waitForUnload, this));
		
    	document.getElementById('SATPopup_close_image').setAttribute('src', this.settings.closeImage);
		document.getElementById('SATPopup_ok_image').setAttribute('src', this.settings.okImage);	
	},
	
	loading: function() {
		if (document.getElementById('SATPopup_loading') != null) return true;
		this.showOverlay();
		
		document.getElementById('SATPopup_content').innerHTML = "";
		
		var node = document.createElement('div');
		node.id = 'SATPopup_loading';
		node.innerHTML = '<img src="' + this.settings.loadingImage + '" />';
		
		document.getElementById('SATPopup_body').appendChild(node);

		var top = this.getPageScroll()[1] + (this.getPageHeight() / 10);

		var documentWidth = document.width ? document.width : document.documentElement.offsetWidth;
		var left = documentWidth / 2 - 205;
		
		var popStyle = document.getElementById('SATPopup').style
		popStyle.top = top + 'px';
		popStyle.left = left + 'px';
		popStyle.display = "block"
	},
	
	reveal: function(data) {
		var node = document.createElement('div');
		node.innerHTML = data;
		
		document.getElementById('SATPopup_content').appendChild(node);
		
		var loadingNode = document.getElementById('SATPopup_loading');
		if (loadingNode) loadingNode.parentNode.removeChild(loadingNode);
		
		var documentWidth = document.width ? document.width : document.documentElement.offsetWidth;
		var left = documentWidth / 2 - (document.getElementById('SATPopup').offsetWidth / 2)
		var popStyle = document.getElementById('SATPopup').style
		popStyle.left = left + 'px';
	},
	
	randomizer: function() {
		randomNumber = Math.floor(Math.random() * 100 / this.settings.displayRate);
		return randomNumber == 0;
	},
	
	show: function() {
		if (!this.displayed && this.hasCookies() && this.randomizer()) {
			this.init();
			this.loading();
			this.reveal(this.settings.popupContent);
			this.setCookie('crmseen', 'seen', 60);
		}
	}
};


function SATWaintingPopup(options) {
	this.intervalID = setInterval(this.bind(this.revealNext, this), 10);
};

SATWaintingPopup.prototype = {
	bind: function(functionName, obj, params) {
		var __method = functionName;
	    return function(event) {
	      return __method.apply(obj, [event || window.event].concat(params));
	    }
	},
	
	cookieName: function(name) {
		return '__SAT_' + name;
	},
	
	getCookie: function(name) {
		var nameEQ = this.cookieName(name) + "=";
		var ca = document.cookie.split(';');
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	},
	
	revealNext: function(e) {
		if (!window.opener || window.opener.closed) {
			clearInterval(this.intervalID);
			setTimeout(function() { 
				window.focus(); 
				window.moveTo(0,0); 
				window.resizeTo(window.screen.availWidth, window.screen.availHeight);
				window.location.href = nextSiteUrl;
			}, 100);
		}
	}
};

