dojo.require("dojo.cookie"); 

var	TMW_APPLICATION_URL="/beta/t1149/tmw.html",
	lang=navigator.language?navigator.language:navigator.userLanguage,
	currLang=dojo.cookie("jfcookie[lang]"), noautostart=false
;
if (lang) lang=lang.toLowerCase().substr(0,2);
else lang="";

var stage0=function(){
	var	tmwlangs=["it"], prefix="/site/", 
		path=window.location.pathname+window.location.search+window.location.hash
	;

	//if (path.match(/\/site\/(..\/|..\.)|lang=/)){
	// / , /site and /site/index.html will trigger language selection
	if (!path.match( /^\/(site(\/?$|(\/index.php$)))?$/ ) ){
		var redirurl=dojo.cookie("redirurl"), redircnt=dojo.cookie("redircnt") || 0; 
		if (!__my.g && redirurl && redircnt<2
			/* window.location.search.substr(1).match(/tmwresource/)*/
		){
			path={redir: true, path: redirurl, isappurl: true};
		} else {
			path={redir: false, path: path};
		}
	} else {
		path={redir: false, path: prefix+"en.html"};
		for(var n=0;n<tmwlangs.length;n++){
			if(lang==tmwlangs[n]){
				path={	redir:true, path: prefix+lang+".html" };
				break;
			}
		}
	}
	if ( path.redir && !(path.isappurl && window.location.hash.substr(1)=="autofb") ){
		noautostart=true;
		// if the url is an application url, we perform redirection
		// only when #autofb is not explicitly requested
		if (path.isappurl){
			dojo.cookie("autostart",1,{path:"/"});
		}
		if (window.location.replace) window.location.replace(path.path);
		else window.location.href=path.path;
	}
	delete stage0;
}

var init=function(){
	var nofacebook=false;
	try{
		// presets the registration form with some values.
		// locks for some time the submit button.
		var regform=dojo.byId("cbcheckedadminForm");
		if (regform){
			if (regform.cb_referrer){
				try { 
					dojo.style(regform.cb_referrer.parentNode.parentNode,
						"display","none");
				}catch(err){}
			}
			var preset=window.location.hash.substr(1), savedPreset=false;
			if (!preset){
				preset=dojo.cookie("cbRegSavedPreset");
				if (preset) savedPreset=true;
			}
			if (preset){
				try {
					preset=dojo.fromJson(unescape(preset));
				}catch(err){ preset=false; }
			}
			if (preset){
				if (preset.user) regform.username.value=preset.user;
				if (preset.pass) regform.password.value=preset.pass;
				if (preset.mail) regform.email.value=preset.mail;
				if (preset.ref && regform.cb_referrer){
					regform.cb_referrer.value=preset.ref;
				}
				if (preset.bonus && regform.cb_certificate){
					regform.cb_certificate.value=preset.bonus;
				}
				if (preset.save && !savedPreset){
					dojo.cookie("cbRegSavedPreset",
						window.location.hash.substr(1),
						{expires:10, path:"/"}
					);
				}
				nofacebook=true;
			}
			var bt=regform.elements[regform.elements.length-1];
			if (bt){
				var	alink=dojo.query("#cbfr_termsc a",regform),
					unlock_bt=function(){ bt.disabled=false; },
					AUTO_UNLOCK_TIMEOUT=preset?5000:10000
				;
				bt.disabled=true;
				if (alink && alink[0]){
					alink[0].onclick=unlock_bt;
				}
				setTimeout(unlock_bt,AUTO_UNLOCK_TIMEOUT);
				delete alink;
			}
		}
	}catch(err){}

	try {
		if (nofacebook) throw new Error();
		var ln, LOCALIZED_STRINGS={
			en:{
				FBCONN_DIALOG_TITLE: "Tracemyworld is more fun with Facebook Connect",
				FBCONN_DIALOG_CONTENT: "Connect your Facebook account to Tracemyworld, it's just as simple as 1,2,3, just click the blue button. <img onclick='FB.Connect.requireSession(fb_login_button_click2,null,true);' src='/beta/t/images/fbconn.png' /><br/><br/>If you don't have an account on Tracemyworld, exploit the faster and easier registration with Facebook Connect.<br/><br/>Already registered? We'll use Facebook Connect to automagically log you into our systems without asking for your username and password and, if you'll be willing to, we'll post some of your Tracemyworld activities on your Wall.<br/>"
			},
			it:{
				FBCONN_DIALOG_TITLE: "Tracemyworld è più divertente con Facebook Connect",
				FBCONN_DIALOG_CONTENT: "Connetti Tracemyworld a Facebook, è semplicissimo, basta cliccare sul bottone blu. <img onclick='FB.Connect.requireSession(fb_login_button_click2,null,true);' src='/beta/t/images/fbconn.png' /><br/><br/>Non hai un account su Tracemyworld? La registrazione è più semplice con Facebook Connect.<br/><br/>Sei già registrato? Useremo Facebook Connect per autenticarti sul nostro portale senza obbligarti a scrivere tutte le volte le tue credenziali e, se vorrai, per postare sul tuo Wall le attività che compi su Tracemyworld.<br/>"
			}
		};
		ln=(LOCALIZED_STRINGS[lang])?lang:"en";
		// simulates a click on the facebook connect button
		if (window.location.hash.substr(1)=="autofb"){
			FB.ensureInit(function(){
				FB.Connect.requireSession(fb_login_button_click2,null,true);
			});
		} else if (__my.g && window.location.hash.indexOf("nofb=1")!=-1){
			// this url is invoked when the user logs out from the application
			dojo.cookie("FBConnAsked","1",{path:"/"});
		} else if ( 	(!__my.g && !dojo.cookie("FBConnOk")) ||
				(__my.g && dojo.cookie("FBConnAsked")!=1)
		){
			FB.ensureInit(function(){
				FB.Connect.get_status().waitUntilReady(function(status){
					switch(status) {
						case FB.ConnectState.connected:
							noautostart=true;
							dojo.cookie("FBConnOk","1",{expires:9, path:"/"});
							dojo.cookie("FBConnAsked",null,{expires:-1, path:"/"});
							if (!__my.g) break;
							//login only if we're not already logged in, but try
							// just one time during this session, unless we can
							// successfully log in later (this is absolutely needed
							// to prevent problems during registration, when
							// we may be facebook-connected but still not 
							// registered and logged in!)
							FB.Connect.requireSession(function(){
								dojo.cookie("FBConnAsked","1",{path:"/"});
								fb_login_button_click2.apply(this,arguments);
							},null,true);
							break;
						case FB.ConnectState.appNotAuthorized:
							noautostart=true;
							if (__my.g){
								dojo.cookie("FBConnAsked","1",
									{expires:9, path:"/"});
							}
							dojo.require("dijit.Dialog");
							dojo.toggleClass(dojo.body(),"tundra",true);
                                                        var headID = document.getElementsByTagName("head")[0];
                                                        var cssNode = document.createElement('link');
                                                        cssNode.type = 'text/css';
                                                        cssNode.rel = 'stylesheet';
                                                        cssNode.href = '/beta/dijit/themes/tundra/tundra.css';
                                                        cssNode.media = 'screen';
							try {
								headID.appendChild(cssNode);
								var dlg=new dijit.Dialog({
									style: "width: 500px",
									title: LOCALIZED_STRINGS[ln]
										.FBCONN_DIALOG_TITLE,
									content: LOCALIZED_STRINGS[ln]
										.FBCONN_DIALOG_CONTENT
								});
								dlg.show();
							}catch(err){}
							if (!__my.g){
								dojo.cookie("FBConnOk","2",
									{expires:9, path:"/"});
							}
						break;
					}
				});
			});
		} else if (!__my.g && dojo.cookie("FBConnAsked") && dojo.cookie("FBConnOk")==1){
			// if we're finally logged in we can remove this cookie so that if our session
			//   expires, the system will be able to automatically log us in again
			dojo.cookie("FBConnAsked",null,{expires:-1, path:"/"});
		}
	}catch(err){}

	try {
		var msg, ASKAUTOSTART_LOCALIZED={
			"en": "Do you want to enter the TraceMyWorld world?",
			"it": "Vuoi entrare nel mondo TraceMyWorld?"
		};
		msg=ASKAUTOSTART_LOCALIZED[lang]?ASKAUTOSTART_LOCALIZED[lang]:ASKAUTOSTART_LOCALIZED["en"];
		if (__my.g){
			dojo.cookie("autostart",null,{expires:-1, path:"/"});
		} else if (!noautostart && dojo.cookie("autostart")!=1){
			dojo.cookie("autostart",1,{path:"/"});
			if (confirm(msg)){
				window.location.href=TMW_APPLICATION_URL;
			}
		}
	}catch(err){}

	try {
		// presets the login form with an username.
		// Used when the user fails the authentication from the guest login form within the app.
		var autouser=dojo.cookie("autologinuser");
		if (autouser){
			dojo.cookie("autologinuser","",{expires:-1, path:"/"});
			var lf=dojo.byId("form-login");
			if (lf){
				lf["username"].value=autouser;
				lf["remember"].value=true;
			}
		}
	}catch(err){}

	try {
		// makes the shop link blink for a while
		var tlink=dojo.query("#sidebar .item28 a");
		if (tlink[0]){
			tlink[0]._blinkcnt=0;
			tlink[0]._blinkInterval=setInterval(dojo.hitch(tlink[0],blinkLink),900);
		}
	}catch(err){}

	try{
		// generates a localized start button, which is also different when the user
		//  is logged in or not.
		var startbt=dojo.byId("startappLink"), satellitediv=dojo.byId("satregister"), btlocalized={it: "jfit"};
		startbt.innerHTML="Enter tracemyworld";
		if (startbt){
			if (__my.g){
				dojo.toggleClass(startbt,"tmwcantstartapp",true);
				if (satellitediv) dojo.toggleClass(satellitediv,"satregisterOff",true);
				startbt.onclick=function(){
					window.location.href="/site/component/comprofiler/registers.html";
				}
			} else {
				// makes the startApp button blink for a while
				startbt._blinkcnt=0;
				startbt._blinkInterval=setInterval(dojo.hitch(startbt,blinkButton),1000);
				dojo.toggleClass(startbt,"tmwstartapp",true);
				if (satellitediv) dojo.toggleClass(satellitediv,"satregisterOn",true);
				startbt.onclick=function(){
					/*setTimeout(function(){
						if (window._stoprotators)
							_stoprotators();
						_tmwswitchApp();
					},250);*/
					window.location.href=TMW_APPLICATION_URL;
				}
			}
			if (currLang in btlocalized){
				dojo.toggleClass(startbt,btlocalized[currLang],true);
			}
			startbt.innerHTML="";
		}
	}catch(err){}

	try{
		if (window.location.href.match(/invitefbfriend\.html/)){
			setTimeout(function(){
				var jfbcinvite=dojo.byId("jfbcinvite");
				if (jfbcinvite) dojo.style(jfbcinvite,"width","600px");
			},6000);
		}
	}catch(err){}
	delete init;
}

function apply_customStyles(){
	// applies some custom styles we use to change the website appearance.
	var stylesheet, cssrules=false;
	try {
		if(parent && parent._JOOMLA_COMPONENT_ONLY){
			if (parent._JOOMLA_COMPONENT_ONLY.hasOwnProperty("inject_css")){
				cssrules=parent._JOOMLA_COMPONENT_ONLY.inject_css;
			} else {
				cssrules="#sidebar,#header,#footer{\ndisplay:none !important;\n}\n#content{\nwidth:100% !important;}\n";
			}
		}
	} catch(err){}
	if (!cssrules && 
		(	location.href.indexOf("tmwforum")!=-1 ||
			location.href.indexOf("option=com_agora")!=-1 )
	){
		cssrules="#header{\ndisplay:none !important;\n}\n#sidebar{\ndisplay:none !important;\n}\n#wrap{\nwidth:95% !important;\n}\n#content{\nwidth:100% !important;}\n";
	}
	if(!cssrules) return;
	stylesheet=dojo.doc.createElement("style");
	stylesheet.setAttribute("type","text/css");
	if (stylesheet.styleSheet) stylesheet.styleSheet.cssText=cssrules;
	else stylesheet.appendChild(dojo.doc.createTextNode(cssrules));
	dojo.doc.getElementsByTagName("head")[0].appendChild(stylesheet);
}


function blinkLink(){
	this._blinkcnt++;
	if (this._blinkhide){
		this._blinkhide=false;
		dojo.toggleClass(this,"linkBlinkRed",true);
	} else {
		this._blinkhide=true;
		dojo.toggleClass(this,"linkBlinkRed",false);
		if (this._blinkcnt>25){
			try {
				clearInterval(this._blinkInterval); 
				delete this._blinkInterval;
				delete this._blinkhide;
				delete this._blinkcnt;
			} catch(e){}
		}
	}
}

function blinkButton(){
	this._blinkcnt++;
	if (this._blinkhide){
		this._blinkhide=false;
		dojo.toggleClass(this,"borderBlinkRed",true);
	} else {
		this._blinkhide=true;
		dojo.toggleClass(this,"borderBlinkRed",false);
		/*if (this._blinkcnt>25){
			try {
				clearInterval(this._blinkInterval); 
				delete this._blinkInterval;
				delete this._blinkhide;
				delete this._blinkcnt;
			} catch(e){}
		}*/
	}
}

/* main */
dojo.addOnLoad(init);
stage0();
apply_customStyles();

