////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Object : App 
//
// Holds Application main functions.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

var App = {
	
	// Loads the application.
	//
	load: function(args) {
		App.startTime = (new Date()).getTime();

		// Load logger if required
		App.initLogger(args);

		// Check browser compatibility
		if (App.checkClient()) {

			// Init components
			App.initSearchField();
			App.initGlobalElements();
			App.loadCookie();
			
			App.setLang("addContentButton","");
			App.setLang("menuwwgMobile","WEBWAG_ON_YOUR_MOBILE");

			// Load the user
			dataHandler.loadUser();
			window.onunload = dataHandler.quit;
		}
	},
	
	// Init global HTML elements
	//
	initGlobalElements: function() {
		App.elTabContent		= $("webwag_tab_content");
		App.elTabContentTable	= $("tabContentTable");

		App.elLogin				= $("loginLink");
		if (App.elLogin) {
			App.elLogin.innerHTML = _("SIGN_IN");
			App.elLogin.onclick = App.loginClick.bind(dataHandler);
		}

		App.elSettingsLink 		= $("webwagSettings");
		if (App.elSettingsLink) {
			App.elSettingsLink.appendChild(_Node("SETTINGS"));
		}
	},
	
	// Load logger if required
	//
	initLogger: function(args) {

		if (args && args.indexOf("debug") >= 0) {
			debugMode = true;
			renderer.renderLogger();
		}
	},

	// Checks client capabilities
	//
	checkClient: function() {

		// cookies capabilities test
		setCookie('ct','');
		if (getCookie("ct")) {
			alert("It seems that you haven't enabled cookies, they are necessary for using this Application.");
			return false;
		}
		deleteCookie("ct");

		// browser capabilities test
		if (!(document.createTextNode && encodeURIComponent && document.getElementsByTagName && document.createElement &&
			document.body.insertBefore && deleteCookie && setCookie) ) {

			alert("Browser not supported!\n");
			return false;
		}
		if (document.all && !window.XMLHttpRequest && !window.ActiveXObject) {
			alert("You must have ActiveX enabled into Internet Explorer!");
			return false;
		}

		if (typeof logger == "undefined" || typeof dataHandler == "undefined" ||typeof user == "undefined" ||typeof renderer == "undefined" ||typeof global == "undefined"
			||typeof Widget == "undefined" ||typeof dataHandler == "undefined"||typeof User == "undefined") {
			alert(_("Core objects not correctly initialized!\n\nAn error occured into one of the javascripts files :(\n"));
			return false;
		}
		return true;
	},

	// Init search field
	initSearchField: function(usr) {

		// Handle search field focus
		var searchField = $("menuSearchQuery");
		if (searchField) {
			searchField.value = "";
			
			$("menuSearchQuery").focus();
			
/* 			$("cse-search-box").onsubmit = function () {
			  if (!user.searchTab)
					dataHandler.addTab({type: "search", name:_("SEARCH"), search:searchField.value},1);
				else
					user.searchTab.show({search:searchField.value});
				return false;
			}*/

/* 		#yahoo search desactivate
				$("searchYahoo").style.display = "";
				searchField.style.background = "url("+WWG_STATIC+"images/search_bg.jpg)";

				searchField.onfocus = function(e) {
					if(!e){
						var e = window.event;
					}

					var target = e.target;
					if(Browser.isIE) {
						target = e.srcElement;
					}
					target.style.background = "#ffffff";
				};

				searchField.onblur = function(e) {
					if(!e){
						var e = window.event;
					}

					var target = e.target;
					if(Browser.isIE) {
						target = e.srcElement;
					}
					if (target.value == "") {
						target.style.background = "url("+WWG_STATIC+"images/search_bg.jpg)";
					}

				};

				searchField.onkeypress = function(e) {
					if(!e){
						var e = window.event;
					}

					var target = e.target;
					if(Browser.isIE) {
						target = e.srcElement;
					}

					// press return
					if(e.keyCode == 13) {
						App.doSearch();
					}
				};
*/

		}

		// Init search button
		var searchBtn = $("runSearchBtn");
		if (searchBtn){
			searchBtn.innerHTML=_("SEARCH");
		}
	},
	
	shadowDesktop : function(st) {
		var e=document.getElementById("shadow");
		var d=$(document.body).getDimensions();
		e.style.height=d.height+"px";
		e.style.width=d.width+"px";
		
		e.style.display=st?"block":"none";
	},
	
	endLoading: function(){
		
		var e,l,c,i,n,d;
		var langs=["english","français","German","Spanish"],langs_id=["en","fr","de","es"];
		App.elLeftPanel=$("leftPanel");
		App.elLogin.innerHTML = _("SIGN_"+(user.email?"OUT":"IN"));
		
		//jQuery("body>div").show();
		//new Effect.BlindDown(App.elTabs);
		//new Effect.BlindDown(App.elTabContent);
		/* pagename */
		
		/*
		pageName zone is now removed
		var d = document.getElementById("pageName");
		App.elPageName = d;
		d.appendChild(document.createTextNode(user.page_name));
		*/
		document.title = "Webwag - " + user.page_name;
		//document.body.insertBefore(d, document.body.firstChild);
		//App._clickEditPageName = App.editPageName.bindAsEventListener(d);
		//Event.observe(d, "click", App._clickEditPageName);

		/* /pagename */
		
		e=document.getElementById("preloading");
		e.parentNode.removeChild(e);
		App.createFooter();
		Event.observe(App.elSettingsLink,"click",this.settings.settingsClick.bind(this.settings));
		
		//******* Var to debug disco effect on AddContent
		discoEffect=new Object();
		discoEffect.state="finished";
		
		e = $("addContentButton");
		e.title = _("ADD_CONTENT");
		Event.observe(e,"click",App.addContent.bind(this));
		l = $("addContentLink");
		l.appendChild(_Node("ADD_CONTENT"));
		//Event.observe(l,"click",App.addContent.bind(this));
		
		//App.elSettingsLink.appendChild(_Node("SETTINGS"));


		
/*		if(renderer.toggleWebMobile){
			Event.observe($("webMobileButton"),"click",renderer.toggleWebMobile.bind(renderer));
			if ( getCookie('showWebMobile') == null || getCookie('showWebMobile') == "1") {
				setTimeout(function(){renderer.toggleWebMobile();},1000);
			}
		}
		*/
		
		//add screens
 		new MobileScreen("mobile","webMobileButton");
		if (user.partner && user.partner.name.toLowerCase() == "peugeot") {
			new CarScreen("car","webCarButton");
		}

		e=$("menuLogin");
		c = document.createElement("img");
		c.src = WWG_STATIC+"images/"+user.language+".gif";
		c.className="flag";
		e.appendChild(c);
		d = $(document.createElement("div"));
		d.className=d.id="langSelection";
		d.style.position="absolute";
		d.hide();
		for(n=0;n<langs.length;++n){
		i = document.createElement("a");
		i.lngid=langs_id[n];
		i.appendChild(document.createTextNode(langs[n]));
		
		Event.observe(i,"click",function(){
					var l=this.lngid;
					user.language=l;
					App.setCookie();
					new Ajax.Request("/user/update",{method: 'post',
  					postBody:"language="+l,onComplete:App.reload});
					//App.reload();
					});
		d.appendChild(i);
		}
		e.appendChild(d);
		Event.observe(c,"click",function(){
				var e=$(d),p=(new Elem(c)).position();
				e.style.left=(c.offsetLeft-40)+"px";
				e.style.top=(c.offsetTop+15)+"px";
				e.toggle();
				/*
				if(!App.evLng){
				Event.observe(document.body,"click",function(){
						$("langSelection").toggle();
					});
				App.evLng=1;
				}
				*/
				return false;
			});
		//App.renderSearch();
		
		i=(new Date()).getTime();
		App.loadingTime=i-App.startTime;
		window.status = "Loaded account in "+App.loadingTime+" ms  (all in "+(i-window.startPageTime)+" ms )";
	
	 	if(e=getCookie('addFeed')){
	 		Widget.add('rss/rss.xml',{url:e,feed_name:""});
	 		App.alert(_("FEED_ADDED"));
	 		setCookie('addFeed','');
	 	}
		//feed Creator externe
		if(e=getCookie('rsscreator')){
			e=eval("("+e+")");
			if(e[1] && e[1].length>2){
				Widget.add(e[0],eval("("+e[1]+")"));	
			}else{
				Widget.add(e[0]);
			}
	 		App.alert(_("CUSTOM_FEED_ADDED"));
	 		setCookie('rsscreator','');
	 	}
	 	if(e=getCookie('addWidget')){	
			var w=(window.innerWidth)?window.innerWidth:document.documentElement.clientWidth;
	 		e=eval("("+e+")");
			if(e[1] && e[1].length>2){
				e[1] = "{browserWidth:"+w+","+e[1].substr(1);
				Widget.add(e[0],eval("("+e[1]+")"));
			}else{
				Widget.add(e[0]);
			}
			debugEcho("addWidgetData=",e[1]);
	 		App.alert(_("WIDGET_ADDED"));
	 		setCookie('addWidget','');			 
	 	}	 	
		setCookie('from','');
		
	 	if(this.render_iphone)
			return this.render_iphone();

		App.elTabs.show();
		App.elTabContent.show();
		setTimeout (user.currentTab.setColSizers,2000);
	/*
	if(document.all&&!window.opera){
		document.body.attachEvent("onclick",function(){
			var e,el,ev=window.event;
			el=ev.srcElement;
			while(el.parentNode){
				el = el.parentNode;
				if(el.id && el.id.indexOf("widgetBox")===0 ){
					widget=global.widgets[el.widgetId];
					debugEcho("IEevent: widget.id="+widget.id);
				}
			}
		});
	}//if ie
	*/
	},

	reload:function() {
		var from = getCookie("from");
		
		if (debugMode && !confirm("[DEBUG MODE]\nreload?"))
			return;
	
			//console.trace();
		var path = "http://"+document.domain+"/";
		
		if (from) {
			path += from + "/index.php";
		}
		else {
			path += "portal.php";
		}
		
		document.body.innerHTML="Reloading...";
		
		window.location = path;
		//window.location = document.URL.replace(/(\?.*)+$/g, '');		
		//window.location.reload();
	},
	
	closeSettings: function() {
		App.settings.save();
		$("wwgSettings").hide();
		App.shadowing(0);
	},
								
	showLogin : function (args){
		// if the setting window is already open, we save its settings and close it
		var settingsElem = $("wwgSettings");
		if (settingsElem && settingsElem.visible()) {
			App.closeSettings();
		}

		if(this.popupPassRecovery){
			this.popupPassRecovery.state(0);
		}
		
		if(this.popupLogin){
			this.popupLogin.state(1);
			return;
		}
		App.shadowing(1);
		
		var creationBtn = "";
		if (args == undefined || args == null || args.indexOf("single_btn") < 0) {
			creationBtn = '<input type="button" value="CREATE_ACCOUNT" onclick="App.createAccount()"/>';
		}
	 var win = App.popupLogin = new popupWindow("login","SIGN_IN","<form id='formSignin'><div>"+
'<div style="padding-top:20px;padding-bottom:20px;padding-left:50px;padding-right:50px"><table style="width:100%">\
<tr><td><label for="settingsAccountLoginMail">EMAIL</label></td><td style="padding:5px; width:170px;"><input style="width:100%; font-size:14px;" type="text" id="settingsAccountLoginMail"/></td></tr>\
<tr><td><label for="settingsAccountLoginPassword">PASSWORD</label></td><td style="padding:5px; width:170px;"><input style="width:100%" type="password" id="settingsAccountLoginPassword"/><br/><span onclick="App.showPassRecoveryBox()" class="link">PASSWORD_LOST</span></td></tr>\
</table></div><div style="text-align:center;">'+creationBtn+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="SIGN_IN"/></div>'
+"</div></form>",400,200);	
	App.popupLogin.div.style.height="200px";
	App.translate($('formSignin'));
	this.popupLogin = win;
	 //Event.observe("formSignin","submit",
	 document.getElementById("formSignin").onsubmit = function(){// handling submit event via prototype break the callback return value...
		dataHandler.login(document.getElementById("settingsAccountLoginMail").value, 
		document.getElementById("settingsAccountLoginPassword").value);
		return false;
	 	};
	},

	showPassRecoveryBox : function (){
		if(this.popupLogin){
			this.popupLogin.state(0);
		}
		
		if(this.popupPassRecovery){
			this.popupPassRecovery.state(1);
			return;
		}
		
		App.shadowing(1);
		var content = "";
		content += "<form id='formRecovery'>";
		content += 	"<div>";
		content += 		"<div style=\"padding-top:20px;padding-bottom:20px;padding-left:50px;padding-right:50px\">";
		content += 		"<span>ENTER_EMAIL_FOR_NEW_PASSWORD</span><br/>&nbsp;";
		content += 			"<table style=\"width:100%\">";
		content += 				"<tr>";
		content += 					"<td>";
		content += 						"<label for=\"recoveryEmail\">EMAIL</label>";
		content += 					"</td>";
		content += 					"<td style=\"padding:5px; width:170px;\">";
		content += 						"<input style=\"width:100%\" type=\"text\" id=\"recoveryEmail\"/>";
		content += 					"</td>";
		content += 				"</tr>";
		content += 			"</table>";
		content += 		"</div>";
		content += 		"<div style=\"text-align:center;\">";
		content += 			"<input type=\"button\" value=\"CANCEL\" onclick=\"App.showLogin()\"/>";
		content += 			"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
		content += 			"<input type=\"submit\" value=\"SEND\"/>";
		content += 		"</div>";
		content += 	"</div>";
		content += "</form>";

	 	var win = App.popupPassRecovery = new popupWindow("password_recovery","PASSWORD_RECOVERY",content ,400,200);
		win.div.style.height="200px";
		
		App.translate($('formRecovery'));
	 	this.popupPassRecovery = win;
	
	 	document.getElementById("formRecovery").onsubmit = function() {
			// handling submit event via prototype break the callback return value...
			var email = document.getElementById("recoveryEmail").value;
			dataHandler.requestPasswordRecovery(email);
			return false;
	 	};
	},
	
	closePassRecoveryBox : function () {
		if(this.popupLogin) {
			this.popupLogin.state(0);
		}
		if(this.popupPassRecovery) {
			this.popupPassRecovery.state(0);
			return;
		}
	},
	
	createAccount: function() {
		var e=$("settingsAccountLoginMail");
		if (e.value)
			App.loginMail = e.value;
		e=$("settingsAccountLoginPassword"); 
		if (e.value)
			App.loginPassword = e.value;		
		this.popupLogin.state(0);
		App.settings.settingsClick();
	},
	createAccountSubmit: function(){
		
	},
	loginClick: function() {
		var e=$("loginLink");
		if (!user.email)
			App.showLogin();
		else
			this.logout();
		e.innerHTML = _("SIGN_"+(user.email?"OUT":"IN"));
	},
	settings: {	
		menuItem:0,// menu item selected
		menuItems : ["Account","Mobile","Themes"],

		showItem : function(it) {
			var e;
			var m=document.getElementById("wwgSettings").getElementsByTagName("ol")[0].getElementsByTagName("li");
			for(var i=0;i<App.settings.menuItems.length;i++) {
				if (e=document.getElementById("settings"+App.settings.menuItems[i])) {
					e.style.display="none";
				}
				if (!m[i]) {
					continue;
				}
				if(e=m[i].getElementsByTagName("a")[0]) {
					e.style.fontWeight=  (it==App.settings.menuItems[i])?"bolder":"normal";
					e.style.background=  (it==App.settings.menuItems[i])?"url(styles/"+("grey"||user.profil.theme)+"/images/bg_haut.gif)":"";
				}
			}
			$("settings"+it).show();
		},

		settingsClick: function(numitem) {
			debugEcho("numitem" + numitem);
			if(! typeof numitem == "number")
				numitem=0;
			debugEcho("this               "+typeof numitem);
			debugEcho(this);
			if(typeof numitem == "number"){
				App.settings.menuItem = numitem;
				}	
			if (!this.initialized){
				App.loading(1);
	   			new Ajax.Request("/settings.php",{
		  					method: 'get',
	  						postBody:"",
	  						onComplete:App.settings.settings_cb.bind(this)});
			}
			else{
				$("wwgSettings").show();
				debugEcho("display:  (this.menuItems[this.menuItem])="+(App.settings.menuItems[App.settings.menuItem]) );
				App.settings.showItem(App.settings.menuItems[App.settings.menuItem]);
			}
			App.shadowing(1);
			$(document.body).scrollTo(0,0);
		},

	
	settings_cb : function(xhr) {
		debugEcho(this);
		if (App.settings.Initialized) {
			return false;
		}
			
		var e,d=document.createElement("div");
		d.innerHTML=xhr.responseText;
		document.body.appendChild(d);
		var i,e,setEl=document.getElementById("wwgSettings"),el=setEl.getElementsByTagName("ol")[0].getElementsByTagName("a");
		debugEcho(el);
		for (i=0;i<el.length;i++){
			var n=i;
			e=el[i];
			Event.observe(e,"click",App.settings.clickMenuItem.bindAsEventListener(e));
			debugEcho("i="+i);
		}
		Event.observe("settingsQuitButton","click",function() {	
			App.closeSettings();
		});

		e=$("settingsSaveButton");
		Event.observe(e,"click",function() {
			if(App.settings.save()){
				App.settings.needsReload=true;
				$('wwgSettings').hide();
				App.shadowing(0);
			}
		});
		if(user.email){
			$("settingsMobileSettings").show();
			//$("settingsMobileNeedsSignIn").hide();
		}
		else{
			$("settingsAccountOldPasswordRow").hide();
			$("createOrModifyAccount").innerHTML=_("CREATE_ACCOUNT");	
		}
		Event.observe($("settingsMobileSendSMS"),"click",function(){
			App.sendSMS();
		});
		App.settings.fill();
		new Draggable("wwgSettings",{handle:"wwgSettingsTitle"});
		debugEcho("App.settings.settings_cb: pre end");
		App.settings.showItem(App.settings.menuItems[App.settings.menuItem]);
		App.settings.initialized=true;
		var d=$(document.body).getDimensions();
		var e=setEl;
		e.style.position="absolute";// for khtml
		e.style.left=((d.width-500)>>1)+"px";
/*if (khtml){
	e.style.top="0px";
}*/
		//document.getElementById("mainPage").style.display=1?"block":"none";
		setEl.style.display="block";
		App.loading(0);
		debugEcho("App.settings.settings_cb: END");
	},
/**
 show a menu item of the settings box.
**/
	clickMenuItem : function() {
		var item;
		debugEcho("App.settings.clickMenuItem  this="+this+" "+typeof this);
		item=this.getAttribute("menuitem");
		debugEcho("item="+item);
		App.settings.showItem(item);
	},
/**
 Fill up the settings window
**/
	fill: function(){
		var el,e,s,i,fields = {
		/*settingsAccountFirstname:user.first_name,
		settingsAccountSurname:user.last_name,*/
		settingsAccountEmail:user.email?user.email:(App.loginMail?App.loginMail:""),
		settingsAccountPassword:"",
		settingsAccountPageName:user.page_name,
		//settingsAccountPassword:App.loginPassword?App.loginPassword:"",
		settingsAccountMobileNumber:user.mobile_number},
		pre=document.getElementById("settingsAccountMobilePrefix");
		for(i in fields){
			if (e=document.getElementById(i))
				e.value = fields[i];
		}
	if(user.email) {
		var elem = $("settingsMobileNeedsSignIn");
		if (elem) {
			elem.hide();
		}
	}
	else {
		var elem = $("settingsMobileSettings");
		if (elem) {
			elem.hide();
		}
	}
		
	e=$("settingsMobileHandset");
	for(i=0;i<e.options.length;++i){
		if(e.options[i].value==user.handset_id){
			e.selectedIndex=i;
		}
	}
		//e.selectedIndex=user.handset_id;
	e=$("settingsAccountMobileCountry");
	Event.observe(e,"change",(function(e){
			pre.value="+"+this.options[this.selectedIndex].value;
	}).bindAsEventListener(e));
	if(user.phone_code){
		pre.value="+"+user.phone_code;
		for(i=0;i<e.options.length;++i){
			if(e.options[i].value==user.phone_code)
				e.selectedIndex=i;
		}
	}
	$("settingsTheme").value=user.theme;
	App.translate(document.getElementById("wwgSettings"));
	s=document.getElementById("settingsAccountLanguage");
	for(i=0;i<s.options.length;i++){
	if(s.options[i].value==user.language){
		s.selectedIndex=i;
		break;}
	}
	},
	
	setTheme : function(theme)
	{
	var item;
	var e=document.getElementsByName("theme")[0];
	if (e)
		e.value=theme;
	if (!theme || typeof theme == "undefined" || theme == "undefined"){
		debugEcho("!!! setTheme: setTheme called with an invalid theme value: theme="+theme,theme);
		return;	
	}
	user.theme=theme;
	this.switchCSS(theme);
	App.setCookie();
	},

	switchCSS: function(theme,CSSid){
	debugEcho("switchCSS:   theme="+theme);
	//debugger;
	App.shadowing(0);
	var hack=Prototype.Browser.Gecko || Prototype.Browser.WebKit || document.all;
	hack=0;
	var e=document.getElementById(CSSid?CSSid:"coreCSS");
	if (e&& e.href.indexOf(theme)==-1){
	if (hack){
		document.body.hide();
	}
	document.body.style.visibility="hidden";
	e.href=WWG_STATIC+"styles/"+theme+"/css/core.css";
	debugEcho("switchCSS:   theme="+e.href);
	
		setTimeout(function(){	if (hack){document.body.show();$(document.body).forceRerendering();} document.body.style.visibility="visible";},100);
	}
	App.theme = theme;
	document.body.className=theme;
	},
	register: function(){
		var p="userId="+user.id+"&platform=web&language="+encodeURIComponent($F("settingsAccountLanguage")),i,
		fields={/*firstName:"settingsAccountFirstname",
		lastName:"settingsAccountSurname",*/
		password:"settingsAccountPassword",
		userName:"settingsAccountEmail",
		//handsetId:"settingsMobileHandset",
		mobileNumber:"settingsAccountMobileNumber",
		pageName: "settingsAccountPageName"};
		var em=$F("settingsAccountEmail");
		var pw=$F("settingsAccountPassword");
		var cpw=$F("settingsAccountPasswordConfirm");
		if(em.length<6){
			if(!em)// no email so cancel the regsitration..
				return;
			App.alert(_("WRONG_EMAIL"));
			return false;
		}
		if(pw==""){
			App.alert(_("NO_PASSWORD"));
			return false;
		}
		if( pw != cpw){
			App.alert(_("PASSWORD_MISMATCH"));
			return false;				
		}
		for(i in fields){
			if ((e=document.getElementById(fields[i]))  && (e.value))
				p += "&"+i+"="+encodeURIComponent(e.value); 
		}
	debugEcho("register: SendAjax to "+"/user/register: data="+p);
	new Ajax.Request("/user/register",{
	  				method: 'post',
  					postBody:p,
  					onComplete:App.settings.register_cb});
	return true;
	},


	register_cb:function(xhr){
		var r = eval("("+xhr.responseText+")");
		debugEcho("register_cb: r=",r);
		if(r.error){
			App.alert(_(r.error.toUpperCase()));
			return;
			}
		if(r.status=="logged_in")
			App.reload();
	},

	
	save : function(){
		return App.settings.saveWithCallback(App.settings.updateProfile_cb);
	},
	
	saveWithCallback : function(callback){
		var s,i=0,p="",fields;
		var mustBeUpdated=true;
		fields = {firstName:"settingsAccountFirstname",
		lastName:"settingsAccountSurname",
		password:"settingsAccountPassword",
		oldPassword:"settingsAccountOldPassword",
		email:"settingsAccountEmail",
		handsetId:"settingsMobileHandset",
		mobileNumber:"settingsAccountMobileNumber",
		theme:$F("settingsTheme")};
		var em=$F("settingsAccountEmail");
		var pw=document.getElementById("settingsAccountPassword");
		var cpw=document.getElementById("settingsAccountPasswordConfirm");
		var reg = !user.email && em && pw.value;
		var save=em || pw.value;
		debugEcho("save:  save="+save+"  reg="+reg);
				if(reg){
					return App.settings.register();
				}
		if(save){
		if(em=="" ){
			App.alert(_("NEEDS_EMAIL"));
			return false;
		}
		if (pw.value!=""){
			debugEcho("updateProfile   pw.value="+pw.value);
			if (pw.value!=cpw.value){
				App.alert("The Passwords must match!");
				i++;
				mustBeUpdated=false;
			}
			debugEcho("pw="+pw.value+"   /^[\\da-zA-Z_.@]*$/g.test(pw.value)="+(/^[da-zA-Z_.@]*$/g.test(pw.value)));
			if ( ! (/^[\w_.]*$/.test(pw.value))){
				App.alert("The password contains invalid characters!\n Allowed characters are 0-9 a-z A-Z . _ @");
				i++;
				mustBeUpdated=false;
			}
		}//pw
}
		if(mustBeUpdated){
		for(i in fields){
		//debugEcho(i,fields[i],document.getElementById(fields[i]),document.getElementById(fields[i]).value);
			if ((e=document.getElementById(fields[i]))  && (e.value))
				p += (p?"&":"")+i+"="+encodeURIComponent(e.value); 
		}
			p += "&language="+encodeURIComponent($F("settingsAccountLanguage")) +
					 "&pageName="+encodeURIComponent($F("settingsAccountPageName")) +
				"&theme="+encodeURIComponent($F("settingsTheme"))+
				"&phoneCode="+$F("settingsAccountMobileCountry");
		//debugEcho(p);
		debugEcho("save: SendAjax to "+"/user/update: data="+p);
			new Ajax.Request("/user/update",{
	  				method: 'post',
  					postBody:p+"&sessionId="+user.session_id+"&userId="+user.id,
  					onComplete:callback});
			App.setCookie();
		}
		return mustBeUpdated;
	},

	updateProfile_cb : function(res)
		{
		var cp,d,z;
		try{
		d = eval("("+res.responseText+")");
		}catch(e){
			debugEcho("updateProfile_cb: catch eval'ed data returned=",d);
			//if(debugMode)
				App.alert("ERROR!");
			logger.log("Error on update profil!");
			return;
		}
		debugEcho("updateProfile_cb: d=",d);
			//z = user.tabs
		/* NT: removed 2008/1/1 (is it usefull??)
		if(!user.email){
			App.reload();
			return;
		}*/
		if(d.settings.pass_status && d.settings.pass_status!=""){
			if(d.settings.pass_status=="modified"){
				App.alert(_("PWD_MODIFIED"));
			}
			if(d.settings.pass_status=="wrong"){
				App.alert(_("WRONG_OLD_PWD"));
			}
			d.settings.pass_status="";			
			var pw=document.getElementById("settingsAccountOldPassword");
			pw.value="";
			pw=document.getElementById("settingsAccountPassword");
			pw.value="";
			pw=document.getElementById("settingsAccountPasswordConfirm");
			pw.value="";
		}
		Object.extend(user,d.settings);
			//user = d.settings;
			//user.tabs = z;
		App.setCookie();
		if(user.language != user.bak.language){
			//App.setCookie();
			App.reload();
			}
		//App.shadowDesktop(0);
		//App.settings.switchCSS(user.theme);
		//App.shadowDesktop(1);
	}/* end settings */
	},
// 

	translate:function(elm){
	var i,j,e,t,el=elm.getElementsByTagName("*");
	for(i=0;i<el.length;++i){
		e=el[i];
		for(j=0;j<e.childNodes.length;++j){
			t=e.childNodes[j];
			if (t.nodeType==3)
				t.data = _(t.data);
			else{
			if (t.value)
				t.value = _(t.value);
			} 
		}
	}
	},
	setLang: function(el,t){
	var e= typeof el=="string" ?document.getElementById(el):el,a= $A(arguments);
	if (!e){
		debugEcho("App.setLang: no element found ("+el+")");
		return false;
	}
	a.shift();
	//debugEcho(_Node.apply(this,a));
	if(e.firstChild && e.firstChild.nodeType==3)
		e.removeChild(e.firstChild);
	e.appendChild(_Node.apply(this,a));
	return e;
	},	
	setCookie : function(){
	var c,cp,s=":",z;
			cp = location.pathname.substr(0,location.pathname.lastIndexOf("/")+1);
			z=parseInt(Math.random()*1e10);
			c = user.id+s+z+s+(new Date().getTime())+s+/*md5(z+user.password)*/"xxxx"+s+user.language+s+user.theme+s+
	 		(user.currentTab&&user.currentTab.id?user.currentTab.id:0)+s+user.country;
	 		setCookie("wwgid",c,365*86400,cp);
	 		debugEcho("----------- set wwg cookie "+c);
	 		if (user.isAnonymous())
	 			setCookie("wwganon",c,365*86400,cp);
	 		this.loadCookie();
	},


//235488:4582235506:1198074036595:c25f2986e93b1f3fbaa3c591e84dabcf:fr:blue:8884:undefined
//uid:rnd:timestamp:md5(rnd+pass):lang:theme:tabId:country
	loadCookie : function(){
	var c=getCookie("wwgid");
	if(!c){
	return false;}
	App.cookie = c.split(":");
	return App.cookie;
	},
/*
	this feature doesn't exist no more
 	editPageName : function(){
		var t=(this.firstChild && this.firstChild.data)||"",e=document.createElement("input");
		e.size=e.maxlength=30;
		App.elPageNameInput = e;
		e.value = t;
		this.appendChild(e);
		this.removeChild(this.firstChild);
		e.focus();
		Event.observe(e,"blur",App.QuitEditPageName);
		Event.observe(e,"keypress",function(e){
			var key = window.event ? event.keyCode : e.keyCode;
			debugEcho("keypress:",key,e);
			if(key==Event.KEY_RETURN)
				App.QuitEditPageName();
			});
		Event.stopObserving(App.elPageName,"click",App._clickEditPageName);
	}, */
/*
	this feature doesn't exist no more
	QuitEditPageName : function(){
		var t,p,e=App.elPageNameInput;
		t = String(e.value).substr(0,30);
		p=App.elPageName;
		p.removeChild(e);
		p.appendChild(document.createTextNode(t));
		document.title = user.page_name = t;
		dataHandler.savePageName();
		Event.observe(App.elPageName,"click",App._clickEditPageName);
	},
*/

	menuButtonsOver:function(){
		var e=this.getElementsByTagName("div")[1];
		e.style.display = "";
	},
	menuButtonsOut:function(){
		var e=this.getElementsByTagName("div")[1];
		e.style.display = "none";
	},

		
	renderSearch: function(){
		var d=document.body,e=document.createElement("div");
		e.id="search";
		
		e.innerHTML='<div id="searchBox"><form onsubmit="App.doSearch();return false;"><table><tr><td>\
		<input type="text" value="" id="menuSearchQuery" name="menuSearch_query"/></td><td>'+
		'<div id="runSearchBtn" onmousedown="App.doSearch()">'+_("SEARCH")+'</div></td><td>'+
		'<img onmousedown="App.doSearch()" src="images/yahoo-search.png" id="yahooLogo"/></td></tr></table>\
		</form></div>';
		
		d.insertBefore(e,d.childNodes[1]);
	},
	searchResults:100,
	doSearch: function(query,start,num){
		App.loading(1);
		if(!query)query=App.yahooQuery=$F("menuSearchQuery");
		if (!start)start=0;
		if(!num)num=App.searchResults;
		var q=encodeURIComponent(query),l = user.language;
		var uri,engine="yahoo";
		//if (navigator.langage || navigator.)
		switch(engine){
			case "yahoo":
			var YAHOO_SEARCH_DOMAIN = "api.search.yahoo.com";//"search.yahooapis.com";
			uri = "http://"+YAHOO_SEARCH_DOMAIN+"/WebSearchService/V1/webSearch?appid=WebwagYahooSearch&output=json&callback=App.ySearch_JSONcb&lang="+l+"&query="+
			q+"&results="+num+"&start="+start;
			break;
			case "google":
			break; 
		}
		loadJS(uri);
	},
	
	closeSearch:function(){
		var e;
		App.tabSearch.remove();
		delete App.tabSearch;
	},
	ySearch_JSONcb: function(r){
		var ra,tot,nr,d,t,ti,su,li,a,im,ca,d,z,q=App.yahooQuery,init;
		init='<img onclick="App.closeSearch();" class="clickable" src="images/buttons/close_over.gif" style="float:right" alt="Close"/>';
		if(r.Error) {
			return;
		}
		tot = r.ResultSet.totalResultsAvailable;
		nr = r.ResultSet.totalResultsReturned;
		ra = r.ResultSet.Result;
		debugEcho("ySearch_JSONcb:",r,ra,tot);
		
		var output = "";
		output += "	<div style=\"padding:20px;\">";
		output += "		<div id=\"searchResults\" class=\"searchResults\">";
		output += "			<img onclick=\"App.closeSearch();\" src=\"images/buttons/close_over.gif\" style=\"float:right\" alt=\"Close\"/>";
		
		if(! (d=App.elSearchResults)){
			d = document.createElement("div");
			App.elSearchResults=$(d);
		}
		
		var firstPosition = r.ResultSet.firstResultPosition;
		var lastPosition = firstPosition + r.ResultSet.totalResultsReturned - 1;
		output += "<div id=\"searchResultHeader\"><b>"+_("RESULTS")+"</b>&nbsp;&nbsp;("+firstPosition+" -> "+lastPosition+" / "+tot+")&nbsp;&nbsp;";
		m = (tot>1000?10:tot/App.searchResults);
		for(i=0; i<m; ++i) {
			z = (i*App.searchResults);
			debugEcho("search   " + r.ResultSet.firstResultPosition+"   z="+z);
			if (r.ResultSet.firstResultPosition!=z) {
				output +="<a href=\'javascript:App.doSearch(App.yahooQuery,"+(i*App.searchResults)+")\'>"+(i+1)+"</a> ";
			}
			else {
				output +=" "+(i+1)+" ";
			}
		}
		output += "</div>";
		
		for(i=0; i<nr; ++i) {
			
			t = ra[i];
			
			var title 	= t.Title;
			d=document.createElement("p");// title is double html encoded by yahoo... so we decode it 1 time... 			
			d.innerHTML=title;
			title=d.firstChild.data;
			var summary = t.Summary;
			var url 	= t.Url;
			
			// Highlight keywords.
			var queryPatern  =  new RegExp(App.yahooQuery, "i");
			try {
				title 	= title.gsub(queryPatern, "<b>#{0}</b>");
				summary = summary.gsub(queryPatern, "<b>#{0}</b>");
				url 	= url.gsub(queryPatern, "<b>#{0}</b>");
			}
			catch(e) {
			}
			
			output += "<div class=\"searchResultRow\">";
			output += "	<div class=\"searchTitle\">";
			output += "		<a class=\"searchTitle\" target=\"_blank\" href=\""+t.ClickUrl+"\">";
			output += 			title;
			output += "		</a>";
			output += "	</div>";
			output += "	<div class=\"searchSummary\">";
			output += 		summary;
			output += "	</div>";
			output += "	<div>";
			output += "		<a class=\"searchLink\" target=\"_blank\" href=\""+t.Url+"\">";
			output += 			url;
			output += "		</a>";
			
			z = new Date(t.ModificationDate*1000);
			var nAnnee = z.getYear();
  			if (nAnnee < 100) {
				nAnnee += 2000;
			}
  			else {
  				if (nAnnee < 2000) {
					nAnnee += 1900;
				}
  			}
			
			output += "		- "+(z.getDay()+1)+" "+(_("MONTH_"+z.getMonth()))+" "+nAnnee+" - ";
			if(t.Cache) {
				output += "<a class=\"searchLink\" target=\"_blank\" href=\""+t.Cache.Url+"\"> Cache </a>";
			}	
			output += "	</div>";
			output += "</div>";
		}
		
		if (!App.tabSearch) {
			App.tabSearch=dataHandler.addTab({name:_("SEARCH")},1);
		}
		
		output += "	</div>";
		output += "</div>";
		debugEcho(d,d.innerHTML,typeof d,output);
		d = $(document.createElement("div"));
		d.innerHTML = output;
		
		e = App.tabSearch.elTabZone;
		e.innerHTML="";
		e.insertBefore(d,e.firstChild);
		d.show();
		App.loading(0);
	},

	googleComplete: function(q){
	var uri = "http://www.google.com/complete/search?hl=fr&js=true&qu="+encodeURIComponent(q);
	
	},

	googleComplete_JSONcb: function(q,asug,anres){
		
	},
	
	addContent: function(){
  		App.elAddContent=$("addContent");
  		//App.elAddContent.toggle();
		if (!App.addContentInitialized){
			App.loading(1);
			loadJS(WWG_STATIC+"javascripts/webwag/discovery.js",function(){
	   		new Ajax.Request("/discovery.php",{
	  			method: 'get',
  				onComplete:App.cb_addContent});
  				});
  		return;
  		}
  		if(!document.all && discoEffect.state!="running"){
			discoEffect=new Effect[App.elAddContent.style.display!="none"?"BlindUp":"BlindDown"](App.elAddContent);
  		}else{
  			App.elAddContent.toggle();
		}
	},

	showWindowText: function(file){
		new Ajax.Request(file, {onComplete: function(xhr){
						var c,e,l,p,res=xhr.responseText;
						e=document.createElement("div");
						e.className="windowInfo";
						e.innerHTML=xhr.responseText;
						document.body.appendChild(e);
						}});
	},

	createFooter: function(xhr){
		var l=location.protocol+"//"+location.host+"/",f,i,s="";
		// new,label,link
		/*labels=[0,"WEBWAG_ON_YOUR_MOBILE",l+"mobile/index.php",
		0,"PRODUCTS","http://blog.webwag.com/?page_id=41",
		0,"DEVELOPERS","http://api.webwag.com/",
		0,"DOWNLOAD_TOOLBAR",l+"_tools/toolbar/firefox/webwag.xpi",
		0,"TOS","http://blog.webwag.com/?page_id=98#tos",
		0,"PRIVACY_POLICY","http://blog.webwag.com/?page_id=98#privacy",
		0,"FEEDBACK","http://blog.webwag.com/?page_id=2",
		0,"FORUM","http://forum.webwag.com/",
		0,"ABOUT_US","http://blog.webwag.com/?page_id=98"];*/
		
		var labels= new Array();
		var labelsTitle=new Array();
		
		labelsTitle[0]="COMPANY";
		labels[0]=[0,"PRODUCTS","http://blog.webwag.com/?page_id=41",
		0,"LASTEST_NEWS","http://blog.webwag.com/?page_id=187",
		0,"CONTACT_US","http://blog.webwag.com/?page_id=2",
		0,"CORPORATE_INFO","http://blog.webwag.com/?page_id=98"];
		
		labelsTitle[1]="COMMUNITY";
		labels[1]=[0,"WEBWAG_MOBILE","http://www.webwag.com/mobile",
		0,"WEBWAG_IPHONE","http://app.webwag.com",
		0,"FORUM","http://forum.webwag.com",
		0,"BLOG","http://blog.webwag.com/?page_id=187",
		0,"DOWNLOAD_TOOLBAR","http://www.webwag.com/_tools/toolbar/firefox/webwag.xpi"];
		
		labelsTitle[2]="DEVELOPERS";
		labels[2]=[0,"Alert Machine","http://api.webwag.com/doku.php?id=flowgin_api",
		0,"API_AND_DOC","http://api.webwag.com/",
		0,"FORUM_DEV","http://forum.webwag.com/viewforum.php?f=3",
		0,"30SECONDS","http://www.webwag.com/30seconds/"];	
		
		
		f=$("webwagFooter");
		s='<table cellpadding="0" cellspacing="0" width="100%"><tr valign="top"><td width="20%"></td>';
		for(i=0;i<labels.length;i++){
			if(i>0){
				s+="</td>";
			}
			s+="<td align='left' width='28%'><b>"+_(labelsTitle[i])+"</b><br/>";
			for(j=0;j<labels[i].length;j+=3){
				s+=(labels[i][j]?"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src='images/new.gif'/>":"")+" <a href='"+(labels[i][j+2]?labels[i][j+2]:"#")+"' _target='blank'/>"+_(labels[i][j+1])+"</a><br/>";
			}
		}
		s+='</td></tr></table>';
		f.innerHTML=s;
	},

	///////////////////
	//obsolete call global.screens.[type].addWidget instead
	///////////////////
	mobButton:function(id){
		var w,a,c;
		w = user.getWidgetById(id);
		debugEcho("mobButton: id="+id);
		c=w.getValue("_compatibility");
		if(c.indexOf("mobile")==-1){
			debugEcho("mobButton: widget not mobile compatible!");
			return;		
		}
		a=w.getValue("availability");
		if (a.indexOf("mobile")!=-1){
			App.notice(_("ALREADY_ON_MOBILE"));
			return;
			}
		w.setValue("availability",a+",mobile");
		w.setValue("x",0);
		w.setValue("y",0);
		w.setValue("z",50);
		w.save(true);
		global.screens["mobile"].renderWidget(w);
	},

	alert: function(msg){
		alert(msg);
	},

	notice: function(text){
		var d;
		if(!(d=App.elNotice)){
			App.elNotice=d=$(document.createElement("div"));
			d.className="notice";
			$("notice").appendChild(d);
		}
		d.innerHTML='<img src="'+WWG_STATIC+'images/icons/button_close_over.gif" style="float:right" alt="Close" onclick="App.elNotice.hide()"/>'+text;
		d.show();
	},
	
	shadowing:function(st){
		var e;
		if(!(e=App.elShadow)){
			App.elShadow=e=$(document.createElement("div"));
			e.id="shadowOverlay";
			document.body.appendChild(e);
		}
		e.style.heigth=(Prototype.Browser.IE?document.body.offsetHeight:window.outerHeight)+"px";
		e.style.display=st?"block":"none";
	},

	loadPendings:0,
	loading: function(st){
		var d,e;
		if (!(e=App.elLoading))
			App.elLoading=e=$("loading");
		
		App.loadPendings+= st?1:-1;
		if(App.loadPendings<0) {
			App.loadPendings=0;
		}
		if(App.loadPendings) {
			e.style.zIndex = "9999";
			e.show();
		}
		else {
			e.hide();
		}
		debugEcho("App.loading: state="+st+"     App.loadPendings="+App.loadPendings);
		/*
		if (st){
			if(!App.elLoading){
				App.elLoading=d=$(document.createElement("div"));
				d.style="position: absolute; z-index: 99; left: 597px; top: 259px;";
				d.id="loading-layer";
				d.innerHTML='<div id="loading-layer-shadow" class="shadow-moz" style="width: 242px; height: 58px;">'+
	   			'<div id="loading-layer-inner"><img border="0" alt="Chargement. Veuillez patienter..." src="images/loading_anim.gif"/>'+
				'<span id="loading-layer-text" style="font-weight: bold;">'+_("LOADING")+' ...</span></div></div></div>';
			}
			else
				App.elLoading.show();
		}
		else
			App.elLoading.hide();
			*/
	}
};

//App.settings.prototype.__defineGetter__("menuitem", function() { debugger; });


