









 
/**
 * Copyright (c) 2005 - 2010, James Auldridge
 * All rights reserved.
 *
 * Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
 *  http://code.google.com/p/cookies/wiki/License
 *
 */
var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function(){var resolveOptions,assembleOptionsString,parseCookies,constructor,defaultOptions={expiresAt:null,path:'/',domain:null,secure:false};resolveOptions=function(options){var returnValue,expireDate;if(typeof options!=='object'||options===null){returnValue=defaultOptions;}else
{returnValue={expiresAt:defaultOptions.expiresAt,path:defaultOptions.path,domain:defaultOptions.domain,secure:defaultOptions.secure};if(typeof options.expiresAt==='object'&&options.expiresAt instanceof Date){returnValue.expiresAt=options.expiresAt;}else if(typeof options.hoursToLive==='number'&&options.hoursToLive!==0){expireDate=new Date();expireDate.setTime(expireDate.getTime()+(options.hoursToLive*60*60*1000));returnValue.expiresAt=expireDate;}if(typeof options.path==='string'&&options.path!==''){returnValue.path=options.path;}if(typeof options.domain==='string'&&options.domain!==''){returnValue.domain=options.domain;}if(options.secure===true){returnValue.secure=options.secure;}}return returnValue;};assembleOptionsString=function(options){options=resolveOptions(options);return((typeof options.expiresAt==='object'&&options.expiresAt instanceof Date?'; expires='+options.expiresAt.toGMTString():'')+'; path='+options.path+(typeof options.domain==='string'?'; domain='+options.domain:'')+(options.secure===true?'; secure':''));};parseCookies=function(){var cookies={},i,pair,name,value,separated=document.cookie.split(';'),unparsedValue;for(i=0;i<separated.length;i=i+1){pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');try
{value=decodeURIComponent(pair[1]);}catch(e1){value=pair[1];}if(typeof JSON==='object'&&JSON!==null&&typeof JSON.parse==='function'){try
{unparsedValue=value;value=JSON.parse(value);}catch(e2){value=unparsedValue;}}cookies[name]=value;}return cookies;};constructor=function(){};constructor.prototype.get=function(cookieName){var returnValue,item,cookies=parseCookies();if(typeof cookieName==='string'){returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}else if(typeof cookieName==='object'&&cookieName!==null){returnValue={};for(item in cookieName){if(typeof cookies[cookieName[item]]!=='undefined'){returnValue[cookieName[item]]=cookies[cookieName[item]];}else
{returnValue[cookieName[item]]=null;}}}else
{returnValue=cookies;}return returnValue;};constructor.prototype.filter=function(cookieNameRegExp){var cookieName,returnValue={},cookies=parseCookies();if(typeof cookieNameRegExp==='string'){cookieNameRegExp=new RegExp(cookieNameRegExp);}for(cookieName in cookies){if(cookieName.match(cookieNameRegExp)){returnValue[cookieName]=cookies[cookieName];}}return returnValue;};constructor.prototype.set=function(cookieName,value,options){if(typeof options!=='object'||options===null){options={};}if(typeof value==='undefined'||value===null){value='';options.hoursToLive=-8760;}else if(typeof value!=='string'){if(typeof JSON==='object'&&JSON!==null&&typeof JSON.stringify==='function'){value=JSON.stringify(value);}else
{throw new Error('cookies.set() received non-string value and could not serialize.');}}var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options){var allCookies={},name;if(typeof options!=='object'||options===null){options={};}if(typeof cookieName==='boolean'&&cookieName===true){allCookies=this.get();}else if(typeof cookieName==='string'){allCookies[cookieName]=true;}for(name in allCookies){if(typeof name==='string'&&name!==''){this.set(name,null,options);}}};constructor.prototype.test=function(){var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue){this.del(testName);returnValue=true;}return returnValue;};constructor.prototype.setOptions=function(options){if(typeof options!=='object'){options=null;}defaultOptions=resolveOptions(options);};return new constructor();})();(function(){if(window.jQuery){(function($){$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options){return this.each(function(){var i,nameAttrs=['name','id'],name,$this=$(this),value;for(i in nameAttrs){if(!isNaN(i)){name=$this.attr(nameAttrs[i]);if(typeof name==='string'&&name!==''){if($this.is(':checkbox, :radio')){if($this.attr('checked')){value=$this.val();}}else if($this.is(':input')){value=$this.val();}else
{value=$this.html();}if(typeof value!=='string'||value===''){value=null;}$.cookies.set(name,value,options);break;}}}});},cookieFill:function(){return this.each(function(){var n,getN,nameAttrs=['name','id'],name,$this=$(this),value;getN=function(){n=nameAttrs.pop();return!!n;};while(getN()){name=$this.attr(n);if(typeof name==='string'&&name!==''){value=$.cookies.get(name);if(value!==null){if($this.is(':checkbox, :radio')){if($this.val()===value){$this.attr('checked','checked');}else
{$this.removeAttr('checked');}}else if($this.is(':input')){$this.val(value);}else
{$this.html(value);}}break;}}});},cookieBind:function(options){return this.each(function(){var $this=$(this);$this.cookieFill().change(function(){$this.cookify(options);});});}};$.each(extensions,function(i){$.fn[i]=this;});})(window.jQuery);}})();

var portalUrls = {
	"registration": "http://www.mobylines.nl/wps/portal/web/!ut/p/b0/04_Sj9CPykssy0xPLMnMz0vMAfGjzOIt3JyDLZwMHQ3cTT3MDDxN3ZwdzZ3cjIFc_UigAnOcCiyM9EP0o_SjiktSC_Qji1KLSxKLSvQLshMjAW6m-w4!/",
	"profile": "http://www.mobylines.nl/wps/myportal/web/!ut/p/b0/04_Sj9CPykssy0xPLMnMz0vMAfGjzOIt3JyDLZwMHQ38ncMsDDxNwwJDPXxcDQ3cDfQjgQrMcSqwMNQP0Y_SjyouSS3QjyxKLS5JLCrRL8hOjAQACwh7Xg!!/",
	"extprofile": "http://www.mobylines.nl/wps/myportal/web/!ut/p/b0/04_Sj9CPykssy0xPLMnMz0vMAfGjzOIt3JyDLZwMHQ38ncMsDDxNwwJDPXxcDQ3cTfUjgQrMcSqwMNYP0Y_SjyouSS3QjyxKLS5JLCrRL8hOjAQAyBm3dA!!/",
	"passwordrecovery": "http://www.mobylines.nl/wps/portal/web/!ut/p/b0/04_Sj9CPykssy0xPLMnMz0vMAfGjzOIt3JyDLZwMHQ38ncMsDDxNwwJDPXxcDQ0MzPQjgQrMcSqwMNIP0Y_SjyouSS3QjyxKLS5JLCrRL8hOjAQATkeqJA!!/"
}

var m20request = {
	"domain" : ".mobylines.nl" 
}
/* Moby 2.0 Scripts - Debug support */
var m20debug = true;

function m20log(params) {
	if (window.console) {
		console.log(params);
	}
}

/* Moby 2.0 Scripts - Widgets */
var m20VPpath = "web/";	// Moby Virtual Portal Path
var mobylang = jQuery("#m20scripts").attr("sitelang");
// postLoginRefres: true -> refresh full page after login / false -> only refresh the page login box after a succesfull login  
var postLoginRefresh = jQuery("#m20scripts").attr("postLoginRefresh");
/* m20refreshafteruserbox 
 * 
 * Se true al termine del caricamento del profilo/setup dei cookie effettua un refresh.
 * Impiegato per l'inizializzazione corretta. Settato in postjanrainlogin_refresh
 */
var m20refreshafteruserbox = false;
/*
 * m20login2mobyclub
 * 
 * Se true dopo il login si effettua un redirect alla pagina del mobyclub.
 * Viene impostato a true nel contesto della portlet di registrazione.
 */
var m20login2mobyclub = false;
/*
 * m20logout2home
 * 
 * Se true dopo il logout scatta il redirect alla home. Altrimenti refresh del solo "userbox".
 * Viene impostato a true nel contesto della portlet di modifica profilo/profilo esteso/mobyclub.
 */
var m20logout2home = false; // Se true il logout manda gli utenti alla homepage, altrimenti rinfresca soltanto il login-box
/*
 * m20reloaduserdata
 * 
 * Se true ricarica i dati utente dal backend, controlla anche la cache dei dati di profilo
 */
var m20reloaduserdata = false;
/*
 * m20postlogincallback
 * 
 * La funzione da chiamare post login
 */
var m20postlogincallback;
var m20postlogoutcallback;

function mobylogin(userlang) {
	
		mobySelf = this; // Object instance reference
		
		this.cmRegistrationDoneCookie = 'cmRegDone';
	
		this.lang = userlang;
		this.mdsLoginEndPoint = '/mds/web/wmclogin.xpd?mode=js_login&lang=' + this.lang + '&token=';
		this.userProfile = null;

		/*
		 * Coremetrics features
		 */
		
		this.cmRegistrationTag = function() {
			if (this.userProfile != null && this.userProfile.loggedin) {
				profile = this.userProfile.user;

				try {

				exploreParams = (profile.mailingList ? "YES" : "NO") + "-_-" + // 1 Newsletter Subscriber
					profile.name + "-_-"+ // 2 First Name
					profile.surname + "-_-"+ // 3 Last Name
					profile.birthDate + "-_-"+ // 4 Date of Birth
					"-_-" + // 5 Age
					(profile.gender === 'M' ? "MALE" : "FEMALE") + "-_-"+ // 6 Gender
					profile.residenteMC + "-_-"+ // 7 Residency
					profile.street + "-_-"+ // 8 Address
					profile.postalCode + "-_-"+ // 9 Post Code
					profile.locality + "-_-"+ // 10 City
					profile.stateOrProvince + "-_-"+ // 11 Province
					profile.country + "-_-"+ // 12 Country
					"-_-" + // 13 Telephone number
					"-_-" + // 14 Preferred desitination
					"-_-" + // 16 Preferred desitination frequency
					"-_-" + // 17 Other Destination Interest
					"-_-" + // 18 Purpose of Trip
					"-_-" + // 19 Accommodation Preference
					"-_-" + // 20 Travel Partners
					"-_-" + // 21 Vehicle Ownership
					"-_-" + // 22 Profession
					"-_-" + // 23 Education Level
					(profile.existingMobyCustomer ? "YES" : "NO") + "-_-" + // 24 Existing Moby Customer
					(profile.bonusOptional ? "YES" : "NO")  + "-_-" + // 25 100 Bonus Points
					profile.codiceCliente + "-_-" + // 26 Moby Club Membership Number
					profile.puntiTot + "-_-" + // 27 Points Balance
					"-_-" + // 28 Social Profile
					profile.lifeTimeMultichannelValue; // 29 Lifetime Multichannel Value
				
					if (m20debug) m20log("creating registration tag");
					if (m20debug) m20log(exploreParams);
					cmCreateRegistrationTag(
							profile.codiceCliente,
							profile.mail,
							profile.locality,
							profile.stateOrProvince,
							profile.postalCode,
							profile.lang.toUpperCase(),
							exploreParams);		
					
				} catch (e) {
					if (m20debug) m20log(e);
				}
			}
		}
		
		/* Effettua accesso / deprecato
		 * 
		 *  this.doLogin =  function() {
		 *  			window.alert("Performing login");
		 *  		};
		*/
		
		// Effettua password recovery
		this.doPasswordRecovery = function() {
			top.location.href = portalUrls.passwordrecovery;
		};
		// Avvia processo di registrazione
		this.doRegistration = function() {
			top.location.href = portalUrls.registration;
		};
		this.doProfile = function() {
			top.location.href = portalUrls.profile;
		};
		this.doExtProfile = function() {
			top.location.href = portalUrls.extprofile;
		};
		this.doLogout = function() {
			// 
			var port = window.location.port != null && window.location.port != '' ? ':' + window.location.port : '';

			jQuery.cookies.del('rememberMeToken', {path: '/'});
			jQuery.cookies.del(this.cmRegistrationDoneCookie, {path: '/', domain: m20request.domain});

			jQuery.ajax( { url: 'http://www.' + m20request.domain + '/mds/web/wmobyclub_logout.xpd?mode=logout', success: function(data) { if (m20debug) { m20log(data); } }, async: false });
			jQuery.ajax( { url: 'https://secure.' + m20request.domain + '/mds/web/wmobyclub_logout.xpd?mode=logout', success: function(data) { if (m20debug) { m20log(data); } }, async: false });

			// Portal / web logout
			if (m20logout2home) {
				window.location.href = '/moby20/registration/sso/logout?redirect=/';
			} else {
				jQuery.ajax( { url: '/moby20/registration/sso/logout', success: function(data) { mobySelf.setupUserElement(); }, async: false });
				if (postLoginRefresh) {
					window.top.location.reload();
				}
			}
			
			if (m20postlogoutcallback != undefined) {
				if (m20debug) { m20log("Performing: m20postlogoutcallback"); }
				m20postlogoutcallback();
			}
		};
		this.myProfile = function() {
			window.location.href = '/mds/web/mobyclub/wuser_load.xpd?mode=after_login&lang=' + mobylang;
		};

		// *** Remember me
		this.setRememberMe = function(rememberMeFlag) {
			var isEnabled = jQuery(rememberMeFlag).is(":checked");
			if (m20debug) {
				m20log('Switching rememberme: ' + rememberMeFlag + " - Currently: " + isEnabled);
			}
			if (isEnabled) {
				var rememberExpire = new Date();
				rememberExpire.setFullYear(rememberExpire.getFullYear()+1);
				jQuery.cookies.set('rememberMeToken', mobySelf.userProfile.user.rememberMeToken, {expiresAt: rememberExpire, path: '/'});
			} else {
				jQuery.cookies.del('rememberMeToken', {path: '/'});
			} 
		};

		// *** Login Box Widget
		this.loginAndRefresh = function() {
			var profile;
			jQuery.ajax({
				url: "/moby20/registration/sso/user",
				dataType: 'json',
				async: false,
				success: function(data) {
					profile = data;
					
					// Esecuzione della call a MDS
					jQuery.ajax({
						url: '/mds/web/wmclogin.xpd?mode=js_login&lang=' + profile.user.lang + '&token=' + encodeURIComponent(profile.user.userToken),
						success: function(data) { m20log("logged in to MDS"); },
						async: false
					});
					window.top.location.reload();
				},
				cache: false
			});
		};
		
		this.setupUserElement = function() {
			// var userInstance = this;
			
			// 1. get userinfo json from json service
			jQuery.ajax({
				url: "/moby20/registration/sso/user" + (m20reloaduserdata ? "?forcereload=true" : ""),
				dataType: 'json',
				success: function(data) {

					if (m20debug) {
						m20log(mobySelf);
						m20log(mobySelf.userProfile);
					}
					
					mobySelf.userProfile = data;
					// var userProfile = userInstance.userProfile;
					
					// 2. if "loggedin" load user information panel
					if (mobySelf.userProfile.loggedin) {
						
						if (jQuery.cookies.get(mobySelf.cmRegistrationDoneCookie) == null) {
							jQuery.cookies.set(mobySelf.cmRegistrationDoneCookie, 'done', {path: '/', domain: m20request.domain});
							mobySelf.cmRegistrationTag();
						}
						
						
						if (jQuery('#login_swf').length) {
							jQuery.ajax({
								url: "/moby20/registration/login/userinfo.jsp",
								success: function(data) {
									// Cookie clean up:
									if (jQuery.cookies.get("WASReqURL") != null) {
										m20log("Cleaning up cookies");
										jQuery.cookies.del("WASReqURL");
										jQuery.cookies.del("enrollToken");
									}
									
									// Profile data setup
									jQuery("#login_swf").html(data);
									jQuery("#userCommonName").html(mobySelf.userProfile.user.fullName);
									jQuery("#userAccountBalance").html(mobySelf.userProfile.user.puntiTot);
									
									// Esecuzione della call a MDS
									jQuery.get('/mds/web/wmclogin.xpd?mode=js_login&lang=' + mobySelf.userProfile.user.lang + '&token=' + encodeURIComponent(mobySelf.userProfile.user.userToken),
											function(data) { m20log("logged in to MDS"); }
									);
									
									try {
										if (m20debug) {
											m20log('Setup rememberme flag');
										}
										rememberMeFlag = jQuery("#rememberMe");
										if (jQuery.cookies.get('rememberMeToken')) {
											jQuery(rememberMeFlag).attr('checked',true);
										}
									} catch (e) {}
									
									if (m20postlogincallback != undefined) {
										if (m20debug) { m20log("Performing: m20postlogincallback"); }
										m20postlogincallback();
									}
									
								},
								cache: !m20reloaduserdata
							});
						}
						if (jQuery('#flash_bottom').length) {
							jQuery.ajax({
								url: "/moby20/registration/login/userinfo_bottom.jsp",
								success: function(data) {
									jQuery("#socio_mc").html("");
									jQuery("#flash_bottom").html(data);	

									jQuery("#bottomUserCommonName").html(mobySelf.userProfile.user.fullName);
									jQuery("#bottomUserAccountBalance").html(mobySelf.userProfile.user.puntiTot);
								},
								cache: false
							});
							jQuery("#div_flash_bottom").css('display','');
						}
						if (m20login2mobyclub) { // We're requested to move to mobyclub page.
							mobySelf.myProfile();
						}
						if (m20refreshafteruserbox) {
							if (m20debug) { m20log("Refresh after user box"); }
							window.top.location.reload();
						}
					} else {
						// 2b. otherwise load login / register / passwordrecovery panel (uid + pwd + social + register + recover)
						if (m20debug) m20log('setup login fragment');
						jQuery.ajax({
							url: "/moby20/registration/login/login.jsp?refresh=" + postLoginRefresh,
							success: function(data) {
								jQuery("#login_swf").html(data);	
								jQuery("#login_link").colorbox({iframe:true,width:700,height:400,scrolling:false});
							},
							cache: false
						});
						// Elemento per il login da preventivo
						if (jQuery('#flash_bottom').length) {
							if (m20debug) m20log('setup bottom login fragment');
							jQuery.ajax({
								url: "/moby20/registration/login/login_bottom.jsp",
								success: function(data) {
									jQuery("#flash_bottom").html(data);	
									jQuery("#div_flash_bottom").css('display','');
									jQuery("#bottom_login_link").colorbox({iframe:true,width:700,height:400,scrolling:false});
								},
								cache: false
							});
						}
					}
				},
				cache: ! m20reloaduserdata
			});
			
		};
}

var mobyuser = new mobylogin(mobylang);

// Service method fo captcha in registration
function reloadCaptcha(input){
	jQuery(input).val('');
	var img = jQuery("img#captcha");
	jQuery(img).attr('src',jQuery(img).attr('src')+"?timestamp="+new Date());
	return false;
}

//Moby classic overrides
function openRecoverWin() {
	mobyuser.doPasswordRecovery();
};

function loginSwf() {
	mobyuser.setupUserElement();
}

// Initialization of Moby login lightbox/widget
jQuery(document).ready(function(){
	jQuery(".lightbox").colorbox({width:'70%',height:'90%'});
});
