/*

	Copyright 2007 - Artlogic Media Limited - http://www.artlogic.net/
	All rights reserved.

*/



/*	CURRENT USER (session/login/favourites) */


user_id = -1; // the current user

var current_user = {

	// an object in which to store current user details
	// and methods specific to the current user
	
	logged_in: false,
	data: {},
	session_id: null,
	
	update_page: function(is_logout) {
		
		debug('current_user.update_page')
		
		//	update page for current user
			if (this.data) {
				this.full_name = this.data.first_name + ' ' + this.data.last_name;
			} else {
				this.full_name = '';
			}
			
			debug(
				'logged_in:', this.logged_in,
				'full_name:', this.full_name,
				'data:', this.data
				);
		
		//	toggle login buttons
			if (this.logged_in) {
				sessions.show_logout({full_name: this.full_name, is_alumni: this.data.is_alumni});
                if (this.data.is_alumni) {
                    $('remove_account_link').hide();
                    $('help_link').show();
                } else {
                    $('remove_account_link').show();
                    $('help_link').hide();
                }
			} else {
				sessions.show_login();
			}
		
		//	load favourites
			
			if (!favourites.loaded && user_id > 0) {
				debug('Getting favourites for user_id', user_id)
				favourites.get_favourites(user_id);
			} else {
				debug(
					'Did not meet conditions to get favourites:',
					'!favourites.loaded:', !favourites.loaded,
					'user_id:', user_id
					)
			}
		
		
		//	show/hide edit button
		
			if (user_id == profile_id) {
				
				if (edit.editor_active) {
					hide('editProfileBtnContainer');
					show('closeEditorBtnContainer');
				} else {
					show('editProfileBtnContainer');
					hide('closeEditorBtnContainer');
				}
				
				hide('reportProfile');
                debug('calling edit.load_editor_html()');
                if (!is_logout) {
                    edit.load_editor_html();
                }
				
			} else {
			
				hide('editProfileBtnContainer');
				hide('closeEditorBtnContainer');
				show('reportProfile');
			
			}
		
	},
	
	load_data: function() {
		if (this.data.is_alumni) {
			data.get_user(this.data.id);
		}
	}

}


var sessions = {

	// session calls

	path: "/session",
	
	first_run: true, // flag - switches to false after the first run
	
	session_arg: function(first) {
		return ''
		// this is now obsolete...
		
		// IE Win is not sending the cookie with ajax requests, so
		// we need to send it in the URL. This function constructions
		// a search string session_id=abcdef from the session cookie,
		// if it exists, or an empty string if not
		var session_id = get_cookie('session_id');
		var sep = (first) ? '?' : '&';
		return (session_id) ? sep + 'session_id=' + session_id : '';
	},
	
	refresh_session: function() {
		
		debug('sessions.refresh_session')

		var url = this.path + '/refresh_session';
		new Ajax.Request(url, {
			method: 'post',
			postBody: this.session_arg(true),
			asynchronous: true,
			onComplete: function(req) {
				var response = decodeJSON(req.responseText);
				if (sessions.first_run || current_user.logged_in != response.logged_in) {
					// change detected
					current_user.logged_in = response.logged_in;
					current_user.session_id = response.session_id;
					current_user.error = response.error;
					current_user.data = response.user_data;
					user_id = response.user_id;
					current_user.update_page();
					sessions.first_run = false;
				}
			}
		});
	},
	
	show_login: function() {
		addClass($('logout'), 'hidden')
		removeClass($('login'), 'hidden')
		$('ufield').value = 'E-mail';
		$('pfield').value = 'Password';
	},
	
	show_logout: function(data) {
		addClass($('login'), 'hidden')
		removeClass($('logout'), 'hidden')
        if (data.is_alumni) {
            $('loginName').innerHTML = '<a id="currentUserName" href="javascript: current_user.load_data()">' + 
                                       'My Profile<span style="font-weight:normal;"></span></a>';
        } else {
            $('loginName').innerHTML = '';
        }
	},
	
	login: function() {
		var url = this.path + '/login';
		new Ajax.Request(url, {
			method: 'post',
			postBody:  Form.serialize("login_form") + this.session_arg(),
			asynchronous: true,
			onComplete: function(req) {
				var response = decodeJSON(req.responseText);
                if (response.error != "No error") {

                    var box_width = '160px';
                    if (response.error.match(/password/) || response.error.match(/This account has not been confirmed/)) {
                        box_width = '220px';
                    } 

                    ['', '2'].each(function(suffix) {
                        var containerName = 'loginErrorContainer' + suffix;
                        if ($(containerName)) {
                            $(containerName).style.width = box_width;
                            show(containerName);
                            window.setTimeout(
                                function() {
                                    hide(containerName); 
                                    $('login_error' + suffix).innerHTML = ''
                                }, 3000);
                            $('login_error' + suffix).innerHTML = response.error;
                        }
                    });

					user_id = -1;
				} else {
					$('ufield').value = '';
					$('pfield').value = '';
					current_user.logged_in = response.logged_in;
					current_user.error = response.error;
					current_user.data = response.user_data;
                    debug('is_alumni = ' + current_user.data.is_alumni);
					user_id = response.user_id;
					current_user.update_page();
                    data.get_user(profile_id);
                    if (current_user.data.is_alumni) {
                        current_user.load_data();
                    } else {
                        pages.home();
                    }
				}
			}
		});
},
	
	logout: function(do_not_go_to_homepage) {
		var url = this.path + '/logout' + this.session_arg(true);
		new Ajax.Request(url, {
			method: 'get',
			asynchronous: true,
			onComplete: function(req) {
				var response = decodeJSON(req.responseText);
				current_user.logged_in = response.logged_in;
				current_user.session_id = response.session_id;
				current_user.error = response.error;
				current_user.data = response.user_data;
				user_id = -1;
                current_user.update_page(true);
				favourites.clear();
                data.get_user(profile_id);
                if(! do_not_go_to_homepage) {
                    pages.search_and_close_editor();
                }
                $('remove_account_link').hide();
			}
		});
	},
	
	register: function() {
		in_development();
	}


};




/*	FAVOURITES MECHANISM */


var favourites = {

	// data calls

	path: "/data",
	
	loaded: false,
	
	ids: [],
	
	get_favourites: function(user_id) {
		if (current_user.logged_in) {
			var url = this.path + '/get_favourites?user_id=' + user_id;
			new Ajax.Request(url, {
				method: 'get',
				asynchronous: true,
				evalScripts: false,
				onComplete: function(req) {
					var response = decodeJSON(req.responseText);
					try {
						favourites.write({
							total: response.total,
							objects: response.objects
						});
					} catch(e) {
						debug('Error in favourites.write:', e)
					}
					profile.set_favourites_btn(profile_id);
				},
				onFailure: function(req) {
					debug('Failure in favourites.get_favourires', req.response.Text)
				}
			});
		}
	},
	
	noImageURL: function() {
		return '/images/no_photo_30x30.gif';
	},
	
	write: function(params) {
        var t = '';
        var favourites_item;
        var ids = [];
        for (var i = 0; i < params.objects.length; i ++) {
            favourites_item = params.objects[i];
            t += this.write_row(favourites_item);
            ids[ids.length] = favourites_item.id
        }
        this.ids = ids;
		if (params.objects.length == 0) {
			$('favourites_list').innerHTML = '';
		} else {
			$('favourites_list').innerHTML = t;
		}
		this.loaded = true;
	},
	
	write_row: function(data) {
		if (data.has_photo && data.image_uid) {
			var img = "/usr/images/profile_images/" + data.institution_id + '/' + data.image_uid + "/30x30.jpg?" + Math.random(); // Math.random prevents cacheing
		} else {
			var img = "/images/no_photo_30x30.gif";
		}
		return '<li onclick="data.get_user(' + data.id + ')">\
			<img src="' + img + '" alt="" />\
			<span>' + data.full_name + '</span>\
		</li>';
	},
	
	clear: function() {
		// clear the favourites list
		$('favourites_list').innerHTML = constants.empty_favourites_list;
	},
	
	contains: function(id) {
		// do the favourites contain the specified id? For example:
		// favourites.contains(1119) -> true/false
		for (var i= 0; i < this.ids.length; i ++) {
			if (id == this.ids[i]) return true;
		}
		return false;
	},
	
	add: function() {
		if (current_user.logged_in) {
			var url = this.path + '/add_favourite?user_id=' + user_id + '&alumni_id=' + profile_id;
			new Ajax.Request(url, {
				method: 'get',
				asynchronous: true,
				evalScripts: true,
				onComplete: function(req) {
					var response = decodeJSON(req.responseText);
					if (response.success) {
						favourites.get_favourites(response.user_id);
					} else {
						debug(response.error);
					}
				}
			});
		} else {
			alert("You must be logged in to use this feature.");
		}
	},
	
	remove: function() {
		if (current_user.logged_in) {
			var url = this.path + '/remove_favourite?user_id=' + user_id + '&alumni_id=' + profile_id;
			new Ajax.Request(url, {
				method: 'get',
				asynchronous: true,
				evalScripts: true,
				onComplete: function(req) {
					var response = decodeJSON(req.responseText);
					if (response.success) {
						favourites.get_favourites(response.user_id);
					} else {
						debug(response.error);
					}
				}
			});
		} else {
			alert("You must be logged in to use this feature.");
		}
	}
	
};
