/**
 *	Personal APIs JavaScript Library
 */
if (!personalapis){
	
	var personalapis={
		
		/**
		 *	PHP Library  path
		 */
		//libAccessPath:'https://personalapis.orange.fr/xjax/paa/',
		libAccessPath:'http://mdsp.orange.fr/paa-xjax/xjax/paa/',
		//libAccessPath:'http://personalapis-pprod.orange.fr/xjax/paa/',
		//libAccessPath:'http://personalapis-int.orange.fr/xjax/paa/',
		//libAccessPath:'http://sla.mdsp.rec.orange.fr/paa-xjax/xjax/paa/',
		//libAccessPath:'http://personalapis-test.orange.fr/chronodev/paa/',
		//libAccessPath:'http://personalapis-test.orange.fr/xjax/paa/',
		//libAccessPath:'http://mdsp.orange.fr/paa-xjaxtest/xjax/paa/', // through WT
		resourcesAccessPath:'http://personalapis.orange.fr/xjax/paa/', // direct access
		//libAccessPath:'http://localhost/xjax/paa/',
		/**
		 *	Service caller URL 
		 */
		serviceUrl:'',
		
		/**
		 *	PersonalAPIs parameters
		 */
		authentication:'',
		contacts:'',
		contents:'',
		calendar:'',
		favourites:'',
		richprofile:'',
		messages:'',
		photos:'',
		ad:'',
		
		/**
		 *	Pictures path prefix
		 */
		imgprefix:'small_',

		/**
		 *	Get the JSON object from the API script and execute the data manager function
		 *	
		 *	@param jsonPath String The JSON script to execute
		 *	@param onloadFunction String The JavaScript function to execute after JSON script return
		 */
		getJSON:function (jsonPath, onloadFunction, removeSplash) {
			
			if( this.isPartnerVarSet() ) {
			
				response = undefined;
				
				if( removeSplash == undefined || typeof(removeSplash) == 'undefined' ){
					removeSplash = true;
				}
				var head = document.getElementsByTagName('head')[0];			
				// Internet Explorer
				//if (navigator.appName == "Microsoft Internet Explorer") {
					//alert(navigator.appName);
					var s2 = document.createElement("script");
					s2.type = "text/javascript";
					s2.src= this.resourcesAccessPath+"iescriptloader.php?olf="+onloadFunction+"&removeSplash="+removeSplash;
					head.appendChild(s2);
				//}
				
				var s = document.createElement("script");
				s.type = "text/javascript";
				s.src = jsonPath;
				head.appendChild(s);
			}
		},

		/**
		 *	Forward to authentication page
		 */
		manageAuthentication:function (federation){
			this.setCookie("redirected", "true");
			if (typeof(federation)=="undefined")
				federation=false;
			window.location=this.libAccessPath+'auth.php?federation='+federation+'&caller='+this.serviceUrl+'&partner='+partner;
		},
		
		/**
		 *	Forward to privacy manager page
		 */
		managePrivacy:function (interactionUrl, canBePartial, apiName){
			/*if (typeof(canBePartial)=="undefined")
				canBePartial = false;
				
			if (!canBePartial){
				if (this.getCookie("privacy")=="tested"){
					this.notifyError("Vous n'avez pas autoris&eacute; ce site &agrave; acc&eacute;der &agrave; vos services personels Orange. <a href='"+interactionUrl+"&urlRetour="+this.serviceUrl+"'>Autoriser</a>","");
				}
				else{
					//this.setCookie("privacy", "tested");
					//window.location=interactionUrl+'&urlRetour='+this.serviceUrl;
					this.notifyError("Vous devez autoriser ce site &agrave; acc&eacute;der &agrave; vos services personels Orange. " +
							"<input type=\"button\" value=\"Seulement cette fois\" onClick=\"javascript:personalapis.setCookie('privacyTempRule','true');javascript:personalapis.manageRedirectionsBis();javascript:personalapis.discard('notifyDiv');\" />&nbsp;&nbsp;" +
							"<input type=\"button\" value=\"D&eacute;finitivement\" onClick=\"javascript:personalapis.setCookie('privacyTempRule','false');javascript:personalapis.manageRedirectionsBis();javascript:personalapis.discard('notifyDiv');\" />&nbsp;&nbsp;" +
							"<input type=\"button\" value=\"Non merci !\" onClick=\"javascript:personalapis.discard('notifyDiv');\" />&nbsp;&nbsp;" +
							"Plus d'information sur votre vie priv&eacute;e sur <a href='"+interactionUrl+"&urlRetour="+this.serviceUrl+"'>Orange privacy</a>","");
				}
				this.setCookie("redirected", "true");
			}
			
			else{*/
				this.notifyError("Vous n'avez autoris&eacute; ce site &agrave; n'acc&eacute;der qu'&agrave; une partie de vos donn&eacute;es Orange. <a href='"+interactionUrl+"&urlRetour="+this.serviceUrl+"'>Modifier vos autorisations</a> ou <a href='javascript:"+apiName+".reloadWithoutPrivacy()'>Continuer</a>","");
				this.setCookie("redirected", "true");
			//}
		},
		 
		/**
		 *	Check the current operation
		 *	
		 *	@param callingOperation String The current operation
		 *	@return boolean
		 */
		checkOperation:function (callingOperation) {

			if (this.getCookie("redirected")=="true" && (this.getCookie("operation")==callingOperation)){
				this.setCookie("redirected", "false");
				this.displaySplash();
				return true;
			}
			else {
				return false;
			}
		},

		/**
		 *	Check the current operation
		 *	
		 *	@param callingOperation String The current operation
		 *	@return boolean
		 */
		manageRedirectionsBis:function(callingOperation){
						
			//alert(callingOperation+"-"+this.getCookie("operation"));
			if(this.getCookie("redirected")=="true"){
			//&&(this.getCookie("operation")==callingOperation)){
				this.setCookie("redirected","false");

				this.displaySplash();

				// Check if there is a partner-integrated-privacy
				privacy = undefined;
				if( this.getCookie("privacyTempRule")!= null ) privacy = this.getCookie("privacyTempRule");
				
				// For each operation call again after authent or privacy
				try{
					// CONTACT
					if(this.getCookie("operation")=="getcontactlist"){
						this.contacts.getcontactlist(this.getCookie("onlyOneChoice")=="true", privacy);
					}
				/* Deleted on 04/11/2009 same test with previous statement	
					else if(this.getCookie("operation")=="getcontactlist"){
						this.contacts.getcontactlist(this.getCookie("onlyOneChoice"));
					}
				*/
					else if(this.getCookie("operation")=="getcontact")
						this.contacts.getcontact(this.getCookie("contactid"), this.getCookie("nextFunction"));
					else if(this.getCookie("operation")=="addcontact"){
						this.contacts.setContactDetails(this.getCookie("contactindex"),this.contacts.contactDetailsStringToTable(this.getCookie("contactdetails")));
						this.contacts.addContact(this.getCookie("contactindex"), privacy);
					}
					// CONTENT
					else if(this.getCookie("operation")=="uploadcontent"){
						this.contents.uploadContent(this.getCookie("contentUrl"),this.getCookie("contentName"),this.getCookie("contentindex"),privacy);
					}
					// CALENDAR
					else if( this.getCookie("operation")=="addevent" ){
						this.calendar.setEventDetails(this.getCookie("eventindex"),this.calendar.eventDetailsStringToTable(this.getCookie("eventdetails")));
						this.calendar.addEvent( this.getCookie("eventindex"), privacy );
					}
					else if(this.getCookie("operation")=="checkavailability"){
						this.calendar.checkAvailability(this.getCookie("eventindex"), privacy);
					}
					// PROFILE
					else if(this.getCookie("operation")=="getprofile"){
						this.richprofile.getProfile(false, privacy);
					}
					else if(this.getCookie("operation")=="getprofilewithoutfed"){
						this.richprofile.getProfile(true, privacy);
					}
					// FAVOURITES
					else if(this.getCookie("operation")=="addbookmark"){
						this.favourites.addBookmark(this.getCookie("bookmarkindex"), privacy);
					}
					// MESSAGES
					else if(this.getCookie("operation")=="getmessages"){
						this.messages.getUnreadMessages(privacy);
					}
					else if(this.getCookie("operation")=="displaymessages"){
						this.messages.displayUnreadMessages(privacy);
					}
					// AUTHENTICATION
				/*	else if( this.getCookie("operation")=="connect" ){
						this.authentication.connect(this.getCookie("profileAttributes"));
					}*/
				}
				catch(err){	
					alert("err : "+err);
					var errObj={
						type: 'manageRedirection error',
						detail: err
					};
					this.displayError(errObj);
				}
			} 
		},
		
		manageRedirections:function( callingOperation ){
			//alert(callingOperation);
			window.onload=personalapis.manageRedirectionsBis(callingOperation);
		},
		
		/**
		 *	Check the API-call return code
		 *	
		 *	-1 : invalid token exception, forward to authentication page
		 *	-3 : privacy exception, access denied to PAA
		 *	
		 *	@param api Object The API that calls this function
		 *	@return boolean
		 *	
		 */
		checkErrors:function (api){
			//alert('response : '+this.objectToString(response,0));
			//alert(typeof(response));
			if (typeof(response.error) != "undefined"){
				if (response.error.code == "-1"){ //invalid token exception
					this.manageAuthentication(response.error.federation);
return true;
				}
				else if (response.error.code == "-3"){ //privacy exception
					this.managePrivacy(response.error.url);
return true;
				}
				else {
					this.notifyError("", response);
				}
				return true;
			}
			else if (typeof(response.authenticate) != "undefined"){
				//alert("Authenticate");
				response.authenticate();
				return true;
			}
			else if (typeof(response.displayError) != "undefined"){
				response.displayError();
				return true;
			}
			return api.checkAPIErrors();
		},

		/*checkErrors:function (){
			alert('response 2: '+this.objectToString(response,0));
			if (typeof(response.error) != "undefined"){
				if (response.error.code == "-1"){ //invalid token exception
					this.manageAuthentication(response.error.federation);
				}
				else if (response.error.code == "-3"){ //privacy exception
					this.managePrivacy(response.error.url);
				}
				else {
					this.notifyError(response);
				}
				return true;
			}
			else if (typeof(response.authenticate) != "undefined"){
				response.authenticate();
				return true;
			}
			else if (typeof(response.displayError) != "undefined"){
				response.displayError();
				return true;
			}
			return false;
		},*/

		/**
		 *	Discard the error message from the web page
		 */
		discardMessage:function (){
			this.discard("screendiv");
			this.discard("errorFrame");
		},

		/**
		 *	Discard an element from the web page
		 *	
		 *	@param elementId String The element ID to discard
		 */
		discard:function (elementId){
			var d = document.getElementById(elementId);
			if (d)
				document.body.removeChild(d);
		},

		/**
		 *	Display a dark splashscreen
		 */
		displaySplash:function (){
			var screendiv = document.getElementById("screendiv");
			var test = false;
			if (!screendiv){
				screendiv = document.createElement("div");	
				screendiv.id="screendiv";
				test = true;
			}
				
			screendiv.style.opacity=0.70;
			screendiv.style.filter='alpha(opacity=70)'; 
/* 			screendiv.style.width=""+screen.availWidth+"px";
			screendiv.style.height=""+screen.availHeight+"px"; */
			screendiv.style.width="100%";
			screendiv.style.height="100%";
			screendiv.style.backgroundColor="#aaaaaa";
			if (navigator.appName == "Microsoft Internet Explorer") 
				screendiv.style.position="absolute";
			else
				screendiv.style.position="fixed";
			screendiv.style.left="0px";
			screendiv.style.bottom="0px";
			if (test)
				document.body.appendChild(screendiv);
		},

		/**
		 *	Discard the dark splashscreen
		 */
		deleteSplash:function (){
			this.discard("screendiv");
		},
		
		/**
		 *	Display error message on web page
		 *	
		 *	@param response 
		 */
		displayError:function (resp){
			this.discard("notifyDiv");
			this.displaySplash();
			var div = document.createElement("div");
			div.id = "errorFrame";
			div.style.width = "400px";
			div.style.position = "absolute";
			div.style.left = ""+(screen.availWidth-400)/2+"px";
			div.style.bottom = ""+(screen.availHeight-400)/2+"px";
			div.style.textAlign = "left";
			if( response.error ){
				errorCode = response.error.code;
				errorDetail = response.error.detail;
			} 
			else{
				errorCode = 'Unknown';
				errorDetail = resp;
			}
			 
			div.innerHTML = '<div style="height:25px;">'+
					'	<div style="background-image:url(\''+this.resourcesAccessPath+'orange/img/border_top_left.gif\'); background-repeat:no-repeat; height:25px; width:8px; position:absolute; left:0px; top:0px;"></div>'+
					'	<div style="background-image:url(\''+this.resourcesAccessPath+'orange/img/border_top_1px.gif\'); background-repeat:repeat-x; height:25px; margin-left:8px; margin-right:8px;">'+
					'		<img style="float:right; margin:5px; cursor:pointer;" src="'+this.resourcesAccessPath+'orange/img/icons/tiny_close.gif" onclick="personalapis.deleteSplash();personalapis.discardMessage();" />'+
					'		<span style="line-height:25px; color:#FFFFFF; font-family:helvetica; font-size:12px; font-weight:bold; height:25px;">:( Erreur</span>'+
					'	</div>'+
					'	<div style="background-image:url(\''+this.resourcesAccessPath+'orange/img/border_top_right.gif\'); background-repeat:no-repeat; height:25px; width:8px; position:absolute; right:0px; top:0px;"></div>'+
					'</div>'+
					'<div style="background:url(\''+personalapis.resourcesAccessPath+'orange/img/fond.gif\') #F6F6F6 repeat-x; border:1px solid #444444; border-bottom:0px; padding:5px;">'+
					'	<div style="margin:7px; padding-top:10px; border:2px ridge #dddddd; background-color:#ffffff;">'+
					'		<div style="height:60px;">'+
					'			<div style="float:left;"><img height="48px" src="'+this.resourcesAccessPath+'orange/img/icons/msg_alert.gif" /></div>'+
					'			<div style="font-family:helvetica; font-size:12px; font-weight:bold; height:96px;">Code:&nbsp;'+errorCode+'<br/>Detail:&nbsp;'+errorDetail+'</div>'+
					'		</div>'+
					'	</div>'+
					'	<div style="text-align:right; margin-right:50px;">'+
							'<img src="'+this.resourcesAccessPath+'orange/img/buttons/large_ok.png" style="cursor:pointer;" onclick="personalapis.deleteSplash();personalapis.discardMessage();" />'+
					'	</div>'+
					'</div>'+
					// Bottom box border
					'<div style="height:8px;">'+
					'	<div style="background-image:url(\''+this.resourcesAccessPath+'orange/img/border_f6_bot_left.gif\'); background-repeat:no-repeat; height:8px; width:8px; position:absolute; left:0px;"></div>'+
					'	<div style="background-image:url(\''+this.resourcesAccessPath+'orange/img/border_f6_bot_right.gif\'); background-repeat:no-repeat; height:8px; width:8px; position:absolute; right:0px;"></div>'+
					'	<div style="border-bottom:1px solid #444444; background-color:#F6F6F6; margin-left:8px; margin-right:8px; height:8px"></div>'+
					'</div>';
			
			document.body.appendChild(div);
		},
		
		notifyError:function (message, details){
			this.deleteSplash();
			var label = message == "" ? "Une erreur est survenue lors du traitement de votre requ&ecirc;te." : message;
			var div = document.getElementById("notifyDiv");
			var test = false;
			if (!div){
				div = document.createElement("div");	
				div.id="notifyDiv";
				test = true;
			}
			
			div.style.width = "99%";
			div.style.textAlign = 'left';
			div.style.border = "1px solid #FF6600";
			div.style.backgroundColor = "#FFCC00";
			div.style.padding = "3px";
			div.innerHTML = '<img height="15px" style="float:left" src="http://i5.woopic.com/I/Header/orange.gif"/>'+
							'<span style="float:right;">'+
								'<a href="javascript:personalapis.discard(\'notifyDiv\');" ><img style="border: 0px none;float:left" src="'+this.resourcesAccessPath+'orange/img/icons/tiny_close.gif"/></a>'+
							'</span>'+
							'<span style="line-height:15px; color:#555555; font-family:verdana; font-size:11px">'+
								'&nbsp;&nbsp;'+label+'&nbsp;'+
								(details == '' ? '' : '<a style="color:#FF6600; font-family:verdana; font-size:11px" href="javascript:personalapis.displayError(\''+details+'\');">Plus de d&eacute;tails</a>')+
							'</span>';
			if (test)
				document.body.insertBefore(div, document.body.firstChild);
		},
		
		alert:function (response){
			this.displaySplash();
			var div = document.createElement("div");
			div.id="alertFrame";
			//div.style.width="200px";
			//div.style.height="100px";
			div.style.textAlign='center';
			div.style.border="1px solid #FF6600";
			div.style.backgroundColor="#FFFFFF";
			div.style.position="absolute";
			div.style.left=""+(screen.availWidth-200)/2+"px";
			div.style.bottom=""+(screen.availHeight-200)/2+"px";
			div.innerHTML='<div style="padding: 10px;vertical-align: middle; text-align: center; color: #0F0F0F; font-family: arial; font-size: 12px;">'+response+'</div><div style="text-align: center"><a href=\'javascript:personalapis.discard("alertFrame");\' style="color: #FF6600; font-family: arial; font-size: 10px">OK</a></div>';
			/*var resp = document.createElement("textarea");
			resp.id='errorDetails';
			resp.style.display='inline';
			resp.rows=5;
			resp.cols=45;
			resp.value=this.objectToString(response,0);
			div.appendChild(resp);*/
			//document.body.appendChild(screendiv);			
			document.body.appendChild(div);
		},
		
		/**
		 *	Get the cookie by name
		 *	
		 *	@param cookie_name String The name of the cookie
		 */
		getCookie:function ( cookie_name )
		{
			var results = document.cookie.match ( '(^|;) ?' + cookie_name + '=([^;]*)(;|$)' );
			if ( results )
				return ( unescape ( results[2] ) );
			else
				return null;
		},
		
		/**
		 *	Set a cookie
		 *	
		 *	@param name String The name of the cookie
		 *	@param value String The value of the cookie
		 *	@param [exp_y] String The expiration year (2009)
		 *	@param [exp_m] String The expiration month (05)
		 *	@param [exp_d] String The expiration day (22)
		 *	@param [domain] String The cookie domain name
		 *	@param [secure] boolean If the cookie is secured
		 */
		setCookie:function (name, value, exp_y, exp_m, exp_d, path, domain, secure )
		{
			var cookie_string = name + "=" + escape ( value );
			if ( exp_y )
			{
				var expires = new Date ( exp_y, exp_m, exp_d );
				cookie_string += "; expires=" + expires.toGMTString();
			}
			if ( path )
				cookie_string += "; path=" + escape ( path );
			if ( domain )
				cookie_string += "; domain=" + escape ( domain );
			if ( secure )
				cookie_string += "; secure";
			document.cookie = cookie_string;
			if (!document.cookie)
				alert("Votre navigateur n'accepte pas les cookies. Veuillez modifier sa configuration pour pouvoir utiliser les APIs Orange.");
		},
		
		clearCookiesAndReload:function(){
		    var cookies = document.cookie.split(";");
			for (var i = 0; i < cookies.length; i++) {
		        var cookie = cookies[i];
				var eqPos = cookie.indexOf("=");
				var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
				document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
			}
			window.location.reload();
		},
		
		/**
		 *	Convert a JavaScript object into String
		 *	
		 *	@param object Object The JavaScript object
		 *	@param id int Number of space character 
		 *	@return String
		 */
		objectToString:function (object, id){
			var sProp, oString ='';
			for(sProp in object)
			{
				for(var k=0 ; k < id ; k++)
					oString += "\t";
				if (typeof(object[sProp]) == "object")
					oString += sProp + " : \r\n" +this.objectToString(object[sProp], ++id)+"\r\n";
				else
					oString += sProp + " : " + object[sProp]+"\r\n";
			}
			return oString;
		},

		/**
		 *	Check if the partner variable is set 
		 *	
		 *	@return boolean
		 */
		isPartnerVarSet:function()
		{
			if( typeof(partner) == "undefined" ) {
				var errObj={
					type: 'partnerId error',
					detail: 'partner ID not found'
				};
				personalapis.displayError(errObj);
				return false;
			}
			else
			{
				return true;
			}
		}
	};
}

personalapis.serviceUrl = encodeURIComponent(window.location.href);
