// Redirect if #anchor is set
(function() { // Inside closure to avoid conflict 
	if(window.location.hash.length > 0) {
		var as = window.location.hash.substring(1);

		var location = window.location.toString().replace(/#.*/, ''); // Get window.location minus hash param

		window.location = addArg2(location, "as", as);	
	}
})();

/** file: Login.js */

/** add as=person-id field to all forms.
 * TODO remove for urls when as=trueUser? */
function asWho() {
	var as = Creole.user? Creole.user.xid : false;
	if (!as) {
		console.log("NOT repointing forms and links as anyone");
		return;
	}
	console.log("Repointing forms and links at "+as);
	if ( ! as) {
		var asi = $("input[name='as']:first");
		if (asi) {
			as = $(asi).val();
		} else {
			as = getCookie("as");
		}
		if ( ! as) {
			console.log("no as value from "+asi);
			return;
		}
	}
	// add a field to all forms
	$("form").each(function() {		
		var form = $(this);
		// hack: avoid the search form
		if (form.attr("method") && form.attr("method").toLowerCase()=="get") return;
		var fasi = $("input[name='as']:first", form);
		if ( ! fasi || ! fasi.val()) {			
			form.append("<input class='generated' type='hidden' name='as' value='"+as+"'>");
		} else {
			if (fasi.hasClass("generated")) {
				fasi.val(as);
			} else {
				console.log("not changing hard-coded as value", form, fasi.val());
			} 
		}
	});
	// add as to links	
	$("a").each(function() {
		var a = $(this);
		var href = a.attr("href");
		
		if (! href || href.charAt(0) == '#') return;

		// internal only
		if (href.charAt(0) != '/' && ! href.match(/soda.sh/)) return;
		if (href.match(/as=/) && ! href.match(/asgen=1/)) return;
		
		// not for shortened links
		if (href.match(/soda.sh\/x/)) return;
		
		href = addArg2(href, "as", as);
		href = addArg2(href, "asgen", 1);		
		a.attr("href", href);		
	});

	// Repoint profile link in header (Note: Assumes profile is the first link!)
	var profileUrl = $("#header .sf-menu ul li:first a").attr("href");

	profileUrl = addArg2(profileUrl, "xid", as);

	$("#header .sf-menu ul li:first a").attr("href", profileUrl);
};

//if(window.location.hash.indexOf('as=') > -1) {	
//	var loc = window.location.toString();	
//	window.location = addArg2(loc.replace(/#.*/, ''), "as", window.location.hash.replace('#', '').split('&')[0].replace('as=', ''));
//}

ajaxifyFunctions.push(asWho);

/**
 * A client side switch of user
 * @param id DBPerson id
 */
function Login_switch(xid) {
	console.log('login',"Switching to",xid);
	
	var usr = DataLoader.getItem(xid);
	
	if (!usr) usr = {'xid':xid};
	
	Creole.user = usr;
	
	// change all the forms
	asWho();

	// set a cookie
	setCookie("as", xid);
	
	// change the nav icon
	var item = _.find(Creole.puppets, function(puppet) { return puppet.xid == xid; });

	if (!item) item = {};
	if (!item.name) item.name = xid=='su'?'admin' : XId.id(xid);
	if (!item.img) item.img = "/static/images/anon.png";		
	
	$(".IAm").each(function(){
		var iam = $(this);
		iam.fadeOut().fadeIn();
		iam.attr("href", "/profile?xid="+xid+"&as="+xid);
		$("img", iam).attr("src", item.img);
		$("span.name", iam).text(item.name);		
	});
	
	// ping the server
	DataLoader.load("/login.json", {
		'action' : 'switch',
		'as' : xid
	});

	
	// Set the window anchor to this 
	var as = Creole.user? Creole.user.xid : false;

	if(urlVars.as == as) {
		window.location.hash = '';
	} else {
		window.location.hash = /*addArg2(window.location.hash, "xid",*/ as/*)*/;
	}
}

function Login_sudo() {
	// no security needed client side
	Login_switch("su");
}

