// functions related to user login and profile editing
var USER_AUTH_FILE		= "/data/user.auth.php";
var USER_ADD_FILE		= "/data/user.add.php";
var USER_EDIT_FILE		= "/data/user.edit.php";
var USER_LOGGEDIN_FILE	= "/data/user.loggedin.php";
var USER_FORGOT_PASSWORD_FILE = "/data/user.forgotpassword.php";
var USER_PROFILE_FILE	= "/secure/profile.php";

var selectNodes = {
	employees : {
		"1-50"		: "1-50",
		"51-100"	: "51-100",
		"101-500"	: "101-500",
		"501-1000"	: "501-1000",
		"1000+"		: "1000+"
	},
	country : { /* set up via ajax below */ },
	founded : { /* set up below */ }
};

$(document).bind("COUNTRIES_LOADED", getCurrentUser);
// set up countries list
$.get(
	"/data/countries.list.php",
	function( response ) {
		if( response.errorcode != ERROR_OK ) { return; }
		selectNodes.country = response.countryList;
		$(document).trigger("COUNTRIES_LOADED");
	},
	"json"
);
// set up founded list
for( var _i=2011; _i>1800; _i-- ) { selectNodes.founded[_i] = _i; }

// required fields setup
var users = {
	login : {
		required : [
			{ id:"email",		label:"Email",		handler:Tools.validEmail },
			{ id:"password",	label:"Password",	handler:Tools.validString }
		]
	},
	register : {
		required : [
			{ id:"email",		label:"Email",		handler:Tools.validEmail },
			{ id:"password",	label:"Password",	handler:Tools.validString }
		]
	},
	forgotpassword : {
		required : [
			{ id:"email",		label:"Email",		handler:Tools.validEmail }
		]
	}
};

function login()
{
	var formId = (arguments[0]) ? arguments[0] : null;
	if( !formId ) { return; }
	if( !validateRequiredFields(users.login.required) ) { alert(_errors.join(", ")); return; }
	
	var postdata = serialize(formId);
	$.post(
		USER_AUTH_FILE,
		postdata,
		function( response ) {
			if( response.errorcode != ERROR_OK )
			{
				alert("Your details do not match our records. Please check and try again.");
				return;
			}
			
			// swap the header bar html
			$.get(
				"/signed-in.html",
				function( html ){
					html = html.replace(/{NAME}/g, response.name);
					$("#formattop").html(html);
				},
				"html"
			)
		},
		"json"
	);
}

function forgotPassword()
{
	var formId = (arguments[0]) ? arguments[0] : null;
	if( !formId ) { return; }
	if( !validateRequiredFields(users.forgotpassword.required) ) { alert(_errors.join(", ")); return; }
	
	var postdata = serialize(formId);
	$.post(
		USER_FORGOT_PASSWORD_FILE,
		postdata,
		function( response ) { $("#formattop").load("/sign-in.html"); },
		"json"
	);
}

function logout() { location.href = "/secure/logout.php"; }

function registerUser()
{
	var formId = (arguments[0]) ? arguments[0] : null;
	if( !formId ) { return; }
	if( !validateRequiredFields(users.register.required) ) { alert(_errors.join(", ")); return; }
	
	var postdata = serialize(formId);
	$.post(
		USER_ADD_FILE,
		postdata,
		function( response ) {
			alert("("+response.errorcode+") "+response.message);
			if( response.errorcode == ERROR_OK ) { resetForm(formId); }
		},
		"json"
	);
}

function editProfile()
{
	var field = (arguments[0]) ? arguments[0] : null;
	var value = (arguments[1]) ? arguments[1] : null;
	if( !field ) { return; }
	var postdata = {};
		postdata[field] = value;
	
	//console.log("updating "+field+": "+value);
	$.post(
		USER_EDIT_FILE,
		postdata,
		function( response ) {
			//console.log("("+response.errorcode+") "+response.message);
		},
		"json"
	);
}

function getCurrentUser()
{
	$(document).unbind("COUNTRIES_LOADED", getCurrentUser);
	
	$.get(
		USER_LOGGEDIN_FILE,
		function( response ) {
			if( response.errorcode != ERROR_OK ) { return; }
			
			for( var n in response.user )
			{
				if( !response.user[n] ) { response.user[n] = "--"; }
				switch( n )
				{
					case "pin":
						var pin = $("img[src$='"+response.user[n]+"']");
							pin.attr("src", pin.attr("src").replace(/small/, "large"));
							pin.parent().addClass("activepin");
					break;
					
					case "country":
						$("#"+n).html(selectNodes.country[response.user[n]]);
						$("#"+n).attr("countryCode", response.user[n]);
					break;
					
					case "password":
						$("#"+n).html("********");
					break;
					
					case "logo":
						(response.user[n] && (response.user[n].length > 0))
							? $("#"+n).html("<img src=\""+response.user[n]+"?_"+Math.ceil(Math.random()*1000000)+"\" />")
							: $("#"+n).html("No logo on file.");
					break;
					
					default:
						$("#"+n).html(Tools.nl2br(response.user[n]));
					break;
				}
			}
		},
		"json"
	);
}

function divToText()
{
	var id			= $(this).attr("id");
	var divText		= $(this).html();
		divText		= Tools.br2nl(divText);
	var textField	= $("<input />")
						.attr("id", id)
						.val(divText)
						.addClass("inputNode")
						.bind("keyup", function(e) {
							var keyCode = e.keyCode || e.which;
							// blur on enter key press (aka. save)
							if( keyCode == 13 ) { $(this).blur(); }
							// blur on esc key press and keep previous content (aka. cancel)
							if( keyCode == 27 ) { $(this).val(divText).blur(); }
						});

	$(this).replaceWith(textField);
	textField.focus().blur(backToDiv);
	if( $.browser.msie ) { textField.focus(); }
	textField.select();
}

function divToPassword()
{
	var id			= $(this).attr("id");
	var textField	= $("<input />")
						.attr("id", id)
						.attr("type", "password")
						.val("")
						.addClass("passwordNode")
						.bind("keyup", function(e) {
							var keyCode = e.keyCode || e.which;
							// blur on enter key press (aka. save)
							if( keyCode == 13 ) { $(this).blur(); }
							// blur on esc key press and keep previous content (aka. cancel)
							if( keyCode == 27 ) { $(this).val("").blur(); }
						});

	$(this).replaceWith(textField);
	textField.focus().blur(backToDiv);
	if( $.browser.msie ) { textField.focus(); }
	textField.select();
}

function divToArea()
{
	var id			= $(this).attr("id");
	var divText		= $(this).html();
		divText		= Tools.br2nl(divText);
	var textField	= $("<textarea />")
						.attr("id", id)
						.val(divText)
						.addClass("areaNode")
						.bind("keyup", function(e) {
							var keyCode = e.keyCode || e.which;
							// blur on esc key press and keep previous content (aka. cancel)
							if( keyCode == 27 ) { $(this).val(divText).blur(); }
						});
						
	$(this).replaceWith(textField);
	textField.focus().blur(backToDiv);
	if( $.browser.msie ) { textField.focus(); }
}

function divToList()
{
	var id			= $(this).attr("id");
	var divText		= $(this).html();
	var listField	= $("<select />");
	var selected	= "";
	$.each(selectNodes[id], function(k,v){
		if( selectNodes[id][k] == divText ) { selected = k; }
		listField.append($("<option>", {value:k}).text(v));
	});
		listField.attr("id", id)
				 .val(selected)
				 .addClass("selectNode")
				 .bind("keyup", function(e) {
					var keyCode = e.keyCode || e.which;
					// blur on esc key press and keep previous content (aka. cancel)
					if( keyCode == 27 ) { $(this).val(divText).blur(); }
				});

	$(this).replaceWith(listField);
		listField.focus()
				 .change(backToDiv)
				 .blur(backToDiv);

	if( $.browser.msie ) { listField.focus(); }
}

function backToDiv()
{
	var type;
	if( $(this).hasClass("selectNode") ) { type = "selectNode"; }
	if( $(this).hasClass("inputNode") ) { type = "inputNode"; }
	if( $(this).hasClass("passwordNode") ) { type = "passwordNode"; }
	if( $(this).hasClass("areaNode") ) { type = "areaNode"; }

	var id	 = $(this).attr("id");
	var text = $(this).val();
		text = (type=="passwordNode") ? "********" : text;
		text = Tools.nl2br(text);
	var div	 = $("<div>")
				.attr("id", id)
				.html((type == "selectNode") ? selectNodes[id][$(this).val()] : text)
				.addClass(type);
	if( id == "country" ) { div.attr("countryCode", $(this).val()); }
		
	// update the profile!
	if( (type != "passwordNode") || ($(this).val().length > 0) )
	{
		editProfile(id, Tools.br2nl($(this).val()));
	}

	var clickFunc;
	switch( type )
	{
		case "selectNode":	clickFunc = divToList;	break;
		case "inputNode":	clickFunc = divToText;	break;
		case "passwordNode":clickFunc = divToPassword; break;
		case "areaNode":	clickFunc = divToArea;	break;
	}
	$(this).replaceWith(div);
		$(div).click(clickFunc);
}

var currentlogopath = null;
function toggleUploader()
{
	var logopath = (arguments[0] && (typeof(arguments[0])=="string")) ? arguments[0] : currentlogopath;
	
	($("#logo").hasClass("logoNode"))
		? $("#logo").removeClass("logoNode").addClass("hide")
		: $("#logo").removeClass("hide").addClass("logoNode").html("");
	if( logopath) { $("#logo").html("<img src=\""+logopath+"?cachebuster="+Math.random()+"\" />"); }
		
	($("#swfuploadControl").hasClass("logoNode"))
		? $("#swfuploadControl").removeClass("logoNode").addClass("hide")
		: $("#swfuploadControl").removeClass("hide").addClass("logoNode");
		
	if( $("#swfuploadControl").hasClass("logoNode") )
	{
		currentlogopath = $("#logo").find("img").attr("src");
	}
}
function divToUploader()
{
	$(this).addClass("hide");
	$("#swfuploadControl").removeClass("hide");
}
function uploaderToDiv()
{
	$("#swfuploadControl").addClass("hide");
	$("#logo").removeClass("hide");
}

function selectGlobePin()
{
	var oldpin = $("span.activepin").find("img");
		oldpin.attr("src", oldpin.attr("src").replace(/large/, "small"));
	$("span.activepin").removeClass("activepin");
	
	var newpin = $(this).find("img");
	editProfile("pin", newpin.attr("src"));
	
	newpin.attr("src", newpin.attr("src").replace(/small/, "large"));
	$(this).addClass("activepin");
}
