

FamclubProfiles = {
	SCRIPTS_PATH: 'scripts/',
	get: {},
	actions: [],
		
	init: function() {
		FamclubProfiles.getParams();
		
		
		for(var i = 0, len = FamclubProfiles.actions.length; i < len; ++i) {
			var action = FamclubProfiles.actions[i];
			switch(action.name) {
				
				//load up or highligh a module:
				case 1:
					Modules.addToPage(parseInt(action.value));
					break;
				
			}
		}
	},
	
	addAction: function(name, value) {
		var action = {name:name, value:value};
		FamclubProfiles.actions.push(action);
	},
	
	getParams: function() {
		var str = new String(window.location);
		var q = str.substring(str.indexOf('?') + 1);
		params = q.split('&');
		finalParams = {};
		params.each(
			function(s) {
				var pair = s.split('=');
				finalParams[pair[0]] = pair[1];
			}
		);
		FamclubProfiles.get = finalParams;
	},
	
	getIntParam: function(param) {
		return parseInt(FamclubProfiles.getParam[param]);
	},
	
	getParam: function(param) {
		return FamclubProfiles.get[param];
	},
	
	hasParam: function(param) {
		var val = FamclubProfiles.getParam(param);
		return (val != undefined && val != null);
	}
}


var Popup = {
	isOpen: false,
	content: '',
	yPos: 0,
	width:200,
	theme: 'aquaTheme',
	align: 'center',
	onComplete: null,
	onClose:null,
	
	init: function(options) {
		if(this.isOpen) return;
		
		/*if(options['yPos']) this.yPos = options['yPos'];
		if(options['content']) this.content = options['content'];
		if(options['width']) this.width = options['width'];
		if(options['theme']) this.theme = options['theme'];
		if(options['align']) this.align = options['align'];
		if(options['onComplete']) this.onComplete = options['onComplete'];*/
		
		this.yPos = (options['yPos'])? options['yPos'] : 0;
		this.content = (options['content'])? options['content'] : '';
		this.width = (options['width'])? options['width'] : 200;
		this.theme = (options['theme'])? options['theme'] : 'aquaTheme';
		this.align = (options['align'])? options['align'] : 'center';
		this.onComplete = (options['onComplete'])? options['onComplete'] : null;
		this.onClose = (options['onClose'])? options['onClose'] : null;
		if(options['position'] == 'auto') {
			this.yPos = document.viewport.getScrollOffsets()[1] - 200;
			if(this.yPos < 0) this.yPos = 0;
		}
	},

	show: function() {
		if(this.isOpen) return;
		
		var theme = ' ' + this.theme;
		var width = (this.width == 'auto')? this.width : this.width + 'px';
		
		var top = '<div class="popupContainer" id="popupContainer" align="'+this.align+'" style="top:'+this.yPos+'px; display:none;"><table cellpadding="0" cellspacing="0" border="0"><tr height="7"><td height="7" width="7" class="popupTopLeft"></td><td height="7" class="popupTop"></td><td height="7" width="7" class="popupTopRight"></td></tr><tr><td width="7" class="popupLeft"></td><td style="background-color:#ffffff;"><div class="popupPadding"><div class="popupClose"><a href="javascript:void(null);" onclick="Popup.close(); return false;"><img src="/images/spacer.gif" /></a></div><div class="scalableModule'+theme+'" style="width:'+this.width+'px;"><div class="moduleShadow"></div><div class="moduleContainer"><div class="moduleContent"><div style="padding:8px;">';
		
		var bottom = '</div></div></div></div></div></td><td width="7" class="popupRight"></td></tr><tr height="7"><td height="7" width="7" class="popupBottomLeft"></td><td height="7" class="popupBottom"></td><td height="7" width="7" class="popupBottomRight"></td></tr></table></div>';
								
		Element.insert('contentContainer', top + this.content + bottom);
		new Effect.Appear('popupContainer', {duration:0.3, afterFinish:this.onComplete});
		this.isOpen = true;
		this.setKeylistener();
	}, 
	
	close: function() {			
		var pc = $('popupContainer');
		if(pc) pc.remove();
		this.isOpen = false;
		Event.stopObserving(document, 'keypress', this.cachedListener);
		if(this.onClose) this.onClose();
	},
	
	setKeylistener: function() {
		this.cachedListener = this.listener.bindAsEventListener(this);
		Event.observe(document, 'keypress', this.cachedListener);
	},
	
	listener: function(event) {
		if(event.keyCode == 27) {
			Popup.close();
		}
	}
};

Scroller.prototype.animateSpeed = 10;
Scroller.prototype.grow = 20;
Scroller.prototype.int = null;
Scroller.prototype.width = 0;
Scroller.prototype.limit = 0;

function Scroller(element, options) {
	this.elementParent = element;
	var tmp = $$('#'+element+' .moveableContent');
	this.element = tmp[0];
	this.init();
	return this;
}

Scroller.prototype.moveLeft = function() {
	this.init();
	var position = this.element.positionedOffset();
	var curLeft = position[0];
	curLeft += 20;
	if(curLeft > 0) return;
	this.element.setStyle({left:curLeft});
	this.int = setTimeout(this.moveLeft.bind(this), 10);
}
	
Scroller.prototype.moveRight = function() {
	this.init();
	var position = this.element.positionedOffset();
	var curLeft = position[0];
	curLeft -= 20;
	var offset = curLeft*-1;
	if(this.width < this.limit || offset > (this.width - this.limit)) return;		
	this.element.setStyle({left:curLeft});
	this.int = setTimeout(this.moveRight.bind(this), 10);
}

Scroller.prototype.stopMove = function() {
	clearInterval(this.int);
}

Scroller.prototype.init = function() {
	if(this.width == 0 || this.limit == 0) {
		this.width = this.element.getWidth();
		var limit = $$('#'+this.elementParent+' .moveableLimits');
		this.limit = limit[0].getWidth();
	}
}

Scroller.prototype.destroy = function() {
	this.element = null;
	this.stopMove();
	this.int = null;
}


//-------------------------------------------------------------

//used when loading images on the fly:
var imgs = new Array();

var Modules = {
	
	modules: [],
	styles: [],
	
	addToPage: function(id, track) {
		
		if(Modules.getModule(id) == null) return;
		
		if(Preferences.isModuleActive(id)) {
			Effect.ScrollTo("" + id);
			return;
		}

		//figure out which column has least number of modules:
		var cols = new Array(0,0,0);
		var len = Preferences.modules.length;
		for(var i = 0; i < len; i++) {
			if(Preferences.modules[i] == null) continue;
			cols[Preferences.modules[i]['column']]++;
		}
		
		var col = 2;
		var colName = 'rightModuleColumn';
		if((cols[0] <= cols[1]) && (cols[0] <= cols[2])) col = 0;
		else if((cols[1] <= cols[0]) && (cols[1] <= cols[2])) col = 1;
		
		if(col == 0) colName = 'leftModuleColumn';
		else if(col == 1) colName = 'centerModuleColumn';
		else colName = 'rightModuleColumn';
	
		//load up the module:
		createModule(colName, id);
		
		//record the module in the user's preferences:
		Preferences.addModule(id, 0, col, cols[col], false);
		
		//close the customize popup:
		Popup.close();
		
		//track if necessary:
		var newModule = this.getModule(id);
		if(newModule.track && track !== false) trackPageActivity('Modules: ' + newModule.title);
	},
	
	getModule: function(id) {
		var index = Modules.getModuleIndex(id);
		if(index >= 0)
			return Modules.modules[index];
		else
			return null;
	},
	
	getModuleIndex: function(id) {
		for(var i = 0, len = Modules.modules.length; i < len; ++i) {
			if(Modules.modules[i].id == id) 
				return i;
		}
		return -1;
	},
	
	getStyle: function(id) {
		var index = Modules.getStyleIndex(id);
		if(index >= 0)
			return Modules.styles[index];
		else
			return null;
	},
	
	getStyleIndex: function(id) {
		for(var i = 0, len = Modules.styles.length; i < len; ++i) {
			if(Modules.styles[i].id == id) 
				return i;
		}
		return -1;
	}
};

var ColumnBackgrounds = {
	
	backgrounds: [],
	
	change: function() {
	
	}	
};

var FrameBackgrounds = {
	
	backgrounds: [],
	
	change: function(id, track) {
		var newBackground = this.get(id);
		
		if(newBackground.track && track !== false) trackPageActivity('Frame Background: ' + newBackground.title);
		
		if(isIE6) return this.changeIE6(id);
	
		var oldID = Preferences.getFrameBackground();
		$('pageContainer').className = newBackground.style;
		Preferences.setFrameBackground(newBackground.id);
		switchHighlighted('frame', oldID, newBackground.id);
	}, 
	
	changeIE6: function(id) {
		var oldID = Preferences.getFrameBackground();
		var newBackground = this.get(id);
		Preferences.setFrameBackground(newBackground.id);
		switchHighlighted('frame', oldID, newBackground.id);
		var obj = $('pageContainer');
		obj.className = newBackground.style;
		var main = $('contentContainer');
		var mainBG = main.getStyle('backgroundImage');
		var header = $('headerContainer');
		var headerBG = header.getStyle('backgroundImage');
		obj.className = (this.get(oldID)).style;
		
		//get background for main area:					
		mainBG = mainBG.replace('")', '');
		mainBG = mainBG.replace('url("http://'+document.domain, '');
		mainBG = mainBG.replace(')', '');
		bmainBGg = mainBG.replace('url(http://'+document.domain, '');
		imgs[1] = new Image();
		imgs[1].onload = function() {			
			obj.className = (FrameBackgrounds.get(id)).style;
		};
		imgs[1].src = mainBG;
		
		//get background for header:
		headerBG = headerBG.replace('")', '');
		headerBG = headerBG.replace('url("http://'+document.domain, '');
		headerBG = headerBG.replace(')', '');
		headerBG = headerBG.replace('url(http://'+document.domain, '');
		imgs[2] = new Image();
		imgs[2].onload = function() {			
			obj.className = (FrameBackgrounds.get(id)).style;
		};
		imgs[2].src = headerBG;
	},
	
	get: function(id) {
		var index = FrameBackgrounds.getIndex(id);
		if(index >= 0)
			return FrameBackgrounds.backgrounds[index];
		else
			return null;
	},
	
	
	getIndex: function(id) {
		for(var i = 0, len = FrameBackgrounds.backgrounds.length; i < len; ++i) {
			if(FrameBackgrounds.backgrounds[i].id == id) 
				return i;
		}
		return -1;
	}
};

var PageBackgrounds = {
	
	backgrounds: [],
	
	change: function(id, track) {
		var newBackground = this.get(id);
		
		if(newBackground.track && track !== false) trackPageActivity('Page Background: ' + newBackground.title);
		
		if(isIE6) return this.changeIE6(id);
	
		var oldID = Preferences.getPageBackground();
		document.body.className = newBackground.style;
		Preferences.setPageBackground(newBackground.id);
		switchHighlighted('page', oldID, newBackground.id);
	},
	
	changeIE6: function(id) {
		var oldID = Preferences.getPageBackground();
		var newBackground = this.get(id);
		Preferences.setPageBackground(newBackground.id);
		switchHighlighted('page', oldID, newBackground.id);
		var b = $A($$('body'))[0];
		var tempDiv = $('tempDiv');
		tempDiv.className = newBackground.style;
		var bg = tempDiv.getStyle('backgroundImage');
		bg = bg.replace('")', '');
		bg = bg.replace('url("http://'+document.domain, '');
		bg = bg.replace(')', '');
		bg = bg.replace('url(http://'+document.domain, '');
		 
		imgs[0] = new Image();
		imgs[0].onload = function() {
			b.className = (PageBackgrounds.get(id)).style;
		};
		imgs[0].src = bg;
	},
	
	get: function(id) {
		var index = PageBackgrounds.getIndex(id);
		if(index >= 0)
			return PageBackgrounds.backgrounds[index];
		else
			return null;
	},
	
	
	getIndex: function(id) {
		for(var i = 0, len = PageBackgrounds.backgrounds.length; i < len; ++i) {
			if(PageBackgrounds.backgrounds[i].id == id) 
				return i;
		}
		return -1;
	}
	
	
};



var SiteWideStyles = {
	
	styles: [],
	
	change: function(id) {
		//get our styles:
		var entry = this.get(id);
		var styles = entry.styles;
		
		//track if necessary:
		if(entry.track) trackPageActivity('Famclub Styles: ' + entry.title);
	
		//we need to do many things when selecting a site wide style:
		//1.  change page background:
		PageBackgrounds.change(styles[0], false);
		
		//2.  change frame background:
		FrameBackgrounds.change(styles[1], false);
		
		//3.  change each module's theme:
		changeGlobalTheme(styles[2], false);
		
		//4.  Change the column backgrounds:
		//... again, do something here...
		
		
	},
	
	get: function(id) {
		var index = SiteWideStyles.getIndex(id);
		if(index >= 0)
			return SiteWideStyles.styles[index];
		else
			return null;
	},
	
	
	getIndex: function(id) {
		for(var i = 0, len = SiteWideStyles.styles.length; i < len; ++i) {
			if(SiteWideStyles.styles[i].id == id) 
				return i;
		}
		return -1;
	}
	
};




function displayCustomizeScreen() {
	var content = $('hiddenPopupContent').innerHTML;
	Popup.init({yPos:20, 
		content:content, 
		width:'auto', 
		onComplete:displayContent, 
		theme:'aquaTheme', 
		align:'center'
	});
	Popup.show();
}
			
function displayContent() {
	modulesScoller = null;
	siteWideStylesScoller = null;
	columnBackgroundScoller = null;
	pageBackgroundScroller = null;
	var i = 0;
	var row;
	var selctedItem = '';
	
	// display the modules:
	var table = $A($$('#customizeModulesList .moveableContent table tr'))[0];
	for(i = 0; i < Modules.modules.length; i++) {
		if(Preferences.isModuleActive(Modules.modules[i]['id'])
			|| !Modules.modules[i].canAdd) continue;
		row = '<td valign="top"><div class="itemContainer" align="center" id="modulesItemContainer_'
				+ Modules.modules[i].id +'">'
				+ '<div class="imageContainer">'
				+ '<a href="javascript:void(null);" onclick="Modules.addToPage('+
				+ Modules.modules[i].id
				+ '); return false;"><img src="'+Modules.modules[i].image+'" /></a>'
				+ '</div>'
				+ '<a href="javascript:void(null);" onclick="Modules.addToPage('+
				+ Modules.modules[i].id
				+'); return false;">'+Modules.modules[i].title+'</a>'
				+ '</div></td>';
		Element.insert(table, row);
	}
	modulesScoller = new Scroller('customizeModulesList');
					
	//display the frame backgrounds:
	table = $A($$('#customizeFrameBackgroundsList .moveableContent table tr'))[0];		
	for(i = 0; i < FrameBackgrounds.backgrounds.length; i++) {
		if(FrameBackgrounds.backgrounds[i]['style'] == '') continue;
		
		if(FrameBackgrounds.backgrounds[i]['id'] == Preferences.getFrameBackground()) selectedItem = ' selectedItem ';
		else selectedItem = '';
		row = '<td valign="top"><div class="itemContainer'+selectedItem+'" align="center" id="frameItemContainer_'
				+ FrameBackgrounds.backgrounds[i]['id']+ '">'
				+ '<div class="imageContainer">'
				+ '<a href="javascript:void(null);" onclick="FrameBackgrounds.change('
				+ FrameBackgrounds.backgrounds[i]['id']
				+ '); return false;"><img src="'+FrameBackgrounds.backgrounds[i]['image']+'" /></a>'
				+ '</div>'
				+ '<a href="javascript:void(null);" onclick="FrameBackgrounds.change('
				+ FrameBackgrounds.backgrounds[i]['id']
				+'); return false;">'+FrameBackgrounds.backgrounds[i]['title']+'</a>'
				+ '</div></td>';
		Element.insert(table, row);
	}
	frameBackgroundScroller = new Scroller('customizeFrameBackgroundsList');
	
	//display the page backgrounds:
	table = $A($$('#customizePageBackgroundsList .moveableContent table tr'))[0];
	for(i = 0; i < PageBackgrounds.backgrounds.length; i++) {
		if(PageBackgrounds.backgrounds[i]['style'] == '') continue;
		
		if(PageBackgrounds.backgrounds[i]['id'] == Preferences.getPageBackground()) selectedItem = ' selectedItem ';
		else selectedItem = '';
		row = '<td valign="top"><div class="itemContainer'+selectedItem+'" align="center" id="pageItemContainer_'+
				+ PageBackgrounds.backgrounds[i]['id'] +'">'
				+ '<div class="imageContainer">'
				+ '<a href="javascript:void(null);" onclick="PageBackgrounds.change('+
				+ PageBackgrounds.backgrounds[i]['id']
				+ '); return false;"><img src="'+PageBackgrounds.backgrounds[i]['image']+'" /></a>'
				+ '</div>'
				+ '<a href="javascript:void(null);" onclick="PageBackgrounds.change('
				+ PageBackgrounds.backgrounds[i]['id']
				+ '); return false;">'+PageBackgrounds.backgrounds[i]['title']+'</a>'
				+ '</div></td>';
		Element.insert(table, row);
	}
	pageBackgroundScroller = new Scroller('customizePageBackgroundsList');
	
	//display the site wide styles:
	table = $A($$('#customizeSiteWideStylesList .moveableContent table tr'))[0];		
	for(i = 0; i < SiteWideStyles.styles.length; i++) {
		if(SiteWideStyles.styles[i]['active'] == 'no') continue;
		
		row = '<td valign="top"><div class="itemContainer" align="center" id="frameItemContainer_'
				+ SiteWideStyles.styles[i]['id']+ '">'
				+ '<div class="imageContainer">'
				+ '<a href="javascript:void(null);" onclick="SiteWideStyles.change('
				+ SiteWideStyles.styles[i]['id']
				+ '); return false;"><img src="'+SiteWideStyles.styles[i]['image']+'" /></a>'
				+ '</div>'
				+ '<a href="javascript:void(null);" onclick="SiteWideStyles.change('
				+ SiteWideStyles.styles[i]['id']
				+'); return false;">'+SiteWideStyles.styles[i]['title']+'</a>'
				+ '</div></td>';
		Element.insert(table, row);
	}
	siteWideStylesScoller = new Scroller('customizeSiteWideStylesList');	

	//display the column backgrounds:		
	//table = $A($$('#customizeColumnBackgroundsList .moveableContent table tr'))[0];
//		for(i = 0; i < ColumnBackgrounds.backgrounds.length; i++) {
//			if(ColumnBackgrounds.backgrounds[i]['id'] == Preferences.getColumnBackground()) selectedItem = ' selectedItem ';
//			else selectedItem = '';
//			row = '<td valign="top"><div class="itemContainer'+selectedItem+'" align="center">'
//					+ '<div class="imageContainer">'
//					+ '<a href="javascript:void(null);"><img src="'+ColumnBackgrounds.backgrounds[i]['image']+'" /></a>'
//					+ '</div>'
//					+ '<a href="">'+ColumnBackgrounds.backgrounds[i]['title']+'</a>'
//					+ '</div></td>';
//			Element.insert(table, row);
//		}
//		columnBackgroundScoller = new Scroller('customizeColumnBackgroundsList');
}

function switchHighlighted(module, newID, oldID) {
	var oldItem = $(module + 'ItemContainer_' + oldID);
	var newItem = $(module + 'ItemContainer_' + newID);
	
	if(oldItem) oldItem.toggleClassName('selectedItem');
	if(newItem) newItem.toggleClassName('selectedItem');
}


var Preferences = {
	
	modules: [],
	pageBackground: 0,
	frameBackground: 0,
	columnBackground: 0,
	updateTimeout:null,
	modified: false,
	
	addModule: function(id, style, column, position, minimized) {
		//var m = new Array();
		var m = new Object();
		m.id = id;
		m.style = style;
		m.column = column;
		m.position = position;
		m.minimized = minimized;
		this.modules[id] = m;
		this.setModified(true);
	},
	
	updateModulePositions: function() {		
		var column = 0;
		var leftModules = $A($$('#leftModuleColumn .module'));
		for(var i = 0; i < leftModules.length; i++) {
			var id = leftModules[i].id;
			this.changeModulePosition(id, column, i);
		}
		
		column = 1;
		var centerModules = $A($$('#centerModuleColumn .module'));
		for(i = 0; i < centerModules.length; i++) {
			var id = centerModules[i].id;
			this.changeModulePosition(id, column, i);
		}
		
		column = 2;
		var rightModules = $A($$('#rightModuleColumn .module'));
		for(i = 0; i < rightModules.length; i++) {
			var id = rightModules[i].id;
			this.changeModulePosition(id, column, i);
		}
	},
	
	removeModule: function(id) {
		this.modules[id] = null;
		this.setModified(true);
	},
	
	isModuleActive: function(id) {
		return (this.modules[id] != null);
		this.setModified(true);
	},
	
	changeModuleStyle: function(id, style) {
		this.modules[id]['style'] = style;
		this.setModified(true);
	},
	
	changeModuleMinMax: function(id, minimized) {
		this.modules[id]['minimized'] = minimized;
		this.setModified(true);
	},
	
	getModuleMinMax: function(id) {
		return this.modules[id]['minimized'];
	},
	
	changeModulePosition: function(id, column, position) {
		this.modules[id]['column'] = column;
		this.modules[id]['position'] = position;
		this.setModified(true);
	},
	
	setPageBackground: function(id) {
		this.pageBackground = id;
		this.setModified(true);
	},
	
	setFrameBackground: function(id) {
		this.frameBackground = id;
		this.setModified(true);
	},
	
	setColumnBackground: function(id) {
		this.columnBackground = id;
		this.setModified(true);
	},
	
	getPageBackground: function() {
		return this.pageBackground;
	},
	
	getFrameBackground: function() {
		return this.frameBackground;
	},
	
	getColumnBackground: function() {
		return this.columnBackground;
	}, 
	
	save: function(lastMinute, onComplete) {
		if(!this.isModified()) return;
	
		var asynchronous = (lastMinute)? true : false;
	
		//update the positioning of the modules:
		this.updateModulePositions();
	
		//make some JSON out of this object:
		var jsonString = Object.toJSON(this);
		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'savePreferences.php', {
			method:'post',
			asynchronous:asynchronous,
			parameters: {preferences: jsonString},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					if(onComplete != null) onComplete(json);
					Preferences.setModified(false);
				} else {
					alert('Sorry, we could not save your page at this time.  Please try again.');
				}
			},
			onFailure: function(){ 
				alert('Sorry, we could not save your page at this time.  Please try again.');
			}
		});
	},
			
	setUpdate: function() {
		this.timeout = setInterval(this.update.bind(this), '1200000');	
		//this.timeout = setInterval(this.update.bind(this), '3000');
	},
	
	update: function() {
		if(this.isModified()) {
			this.save(false);
		} else {
			new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'update.php', {
				method:'post',
				parameters: {action:'update'},
				onComplete: function(transport){
					//nothing
				}
			});
		}
	},
	
	isModified: function() {
		return this.modified;
	},
	
	setModified: function(b) {
		this.modified = b;
	}
};

/*
function unloadFunction(){
	Preferences.save(true);
}

window.onbeforeunload = unloadFunction;
*/

function unloadFunction(){
	if(!Preferences.isModified()) {
		return;
	} else {
		return 'You have not saved your settings.';
	}
}

function startUnload() {
	window.onbeforeunload = unloadFunction;
}

function stopUnload() {
	window.onbeforeunload = null;
}
startUnload();



////// Creating Modules and controls////////
var themeSelector = new Array;
var themeSelectorMod = new Array;
//var currentModules = new Array;

function createModule(position, moduleID) {
	//currentModules.push(moduleID);
	moduleSetUp = $(position).innerHTML;
	new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + "createModule.php?moduleID=" + moduleID + "&position="+ position + "&r=" + Math.random(), { 
		method: 'get',
		onSuccess : function(resp) { 
			newModule = resp.responseText; 
			//$(position).innerHTML = moduleSetUp + newModule;
			$(position).insert(newModule);
			init();
			Effect.ScrollTo("" + moduleID);
		}
	});
}

function minModule(moduleID) {	

	content = $(moduleID+'Content');

	if(!isIE) {
		if ($(content).style.display == "none") {
			Effect.SlideDown(content,{duration: 0.4});
			$('minModule'+moduleID).src = "/images/community/btn_min.gif";
		} else {
			Effect.SlideUp(moduleID+'Content',{duration: 0.4});
			$('minModule'+moduleID).src = "/images/community/btn_max.gif";
		}
	} else {
		if(content.getStyle('display') == 'none') {
			content.style.display = 'block';
			$('minModule'+moduleID).src = "/images/community/btn_min.gif";
		} else {
			content.style.display = 'none';
			$('minModule'+moduleID).src = "/images/community/btn_max.gif";
		}
	}
		

	
	Preferences.changeModuleMinMax(moduleID, !Preferences.getModuleMinMax(moduleID));
}

function editModule(moduleID) {
	id = moduleID+'Edit';
	Effect.toggle(id, 'slide', {duration:0.5});
}

/*
function selectTheme(theme, moduleID) {
	selector = Modules.styles[theme]['style'] + moduleID;
	if (themeSelectorMod[moduleID] == moduleID) {
		oldSelector = Modules.styles[themeSelector[moduleID]]['style'] + moduleID;
		$(oldSelector).style.borderColor = "#FFFFFF";
	}
	$(selector).style.border = "1px";
	$(selector).style.borderStyle = "solid";
	$(selector).style.borderColor = "#aeaea6";
	themeSelector[moduleID] = theme;
	themeSelectorMod[moduleID] = moduleID;
	
	/// Change theme
	if (themeSelector[moduleID]) { 
		var mod = $(moduleID);
		if(mod.hasClassName('module'))
			mod.className = "module "+ Modules.styles[themeSelector[moduleID]]['style'];
		else
			mod.className = "notMovableModule "+ Modules.styles[themeSelector[moduleID]]['style'];
		
		Preferences.changeModuleStyle(moduleID, Modules.styles[themeSelector[moduleID]]['id']);
	} 
	
}
*/
function selectTheme(theme, moduleID) { 
	selector = (Modules.getStyle(theme)).style + moduleID;
	if (themeSelectorMod[moduleID] == moduleID) {
		oldSelector = (Modules.getStyle(themeSelector[moduleID])).style + moduleID;
		$(oldSelector).style.borderColor = "#FFFFFF";
	}
	$(selector).style.border = "1px";
	$(selector).style.borderStyle = "solid";
	$(selector).style.borderColor = "#aeaea6";
	themeSelector[moduleID] = theme;
	themeSelectorMod[moduleID] = moduleID;
	
	/// Change theme
	if (themeSelector[moduleID]) { 
	
		var mod = $(moduleID);
		var finalClassName = (Modules.getStyle(themeSelector[moduleID])).style;
		
		if(isIE6) {
			var tempDiv = $('tempModule');
			tempDiv.className = "module " + finalClassName;
			var bgDiv = tempDiv.down('.moduleContent');
			var bg = bgDiv.getStyle('backgroundImage');
			bg = bg.replace('")', '');
			bg = bg.replace('url("http://'+document.domain, '');
			bg = bg.replace(')', '');
			bg = bg.replace('url(http://'+document.domain, '');
			if(bg == 'none') {
				if(mod.hasClassName('module'))
					mod.className = "module "+ finalClassName;
				else
					mod.className = "notMovableModule "+ finalClassName;	
			} else {
				imgs[3] = new Image();
				imgs[3].onload = function() {
					if(mod.hasClassName('module'))
						mod.className = "module "+ finalClassName;
					else
						mod.className = "notMovableModule "+ finalClassName;
				};
				imgs[3].src = bg;
			}
		} else {
			if(mod.hasClassName('module'))
				mod.className = "module "+ finalClassName;
			else
				mod.className = "notMovableModule "+ finalClassName;	
		}
			
		Preferences.changeModuleStyle(moduleID, (Modules.getStyle(themeSelector[moduleID])).id);
	}
}

function applyTheme(moduleID) {
	if (themeSelector[moduleID]) { 
		var mod = $(moduleID);
		if(mod.hasClassName('module'))
			mod.className = "module "+ (Modules.getStyle(themeSelector[moduleID])).style;
		else
			mod.className = "notMovableModule "+ (Modules.getStyle(themeSelector[moduleID])).style;
		
		Preferences.changeModuleStyle(moduleID, (Modules.styles(themeSelector[moduleID])).id);
	} 
}

function removeModule(moduleID) {
	var module = $(moduleID + '');
	var column = module.parentNode;
	column.removeChild(module);
	Preferences.removeModule(moduleID);
	Popup.close();
	if (moduleID == 0 || moduleID == 1 || moduleID == 4){ 
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + "removeAllContent.php?module="+ moduleID, {method: 'get'});
	}
}

function removeWarning(col, moduleID) {
	var content = '<center><strong>Are you sure you would like to close this module?'
				+ '<br><br>You will lose all saved information.<br><br>'
				+ '<a href="javascript:void(null);" onclick="removeModule('+moduleID+'); return false;">Yes</a>'
				+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(null);" onclick="Popup.close(); return false;">No</a></strong></center>';
	
	//get the originating module's style:
	var theme = (Modules.getStyle(Preferences.modules[moduleID]['style'])).style;
	
	//get the originating module's column:
	var align = 'center';
	var column = Preferences.modules[moduleID]['column'];
	if(column == 0) align = 'left';
	else if(column == 2) align = 'right';
	
	//get the originating module's Y position:
	var offset = $(moduleID).positionedOffset();
	
	Popup.close();
	Popup.init({yPos:100 + offset.top, content:content, align:align, theme:theme, width:250});
	Popup.show();
}

function manualSave() {
	var complete = function() {
		var content = '<center><strong>Your settings have been saved!<br><br>'
				+ '<a href="javascript:void(null);" onclick="Popup.close(); return false;">OK</a></strong></center>';
		
		Popup.close();
		Popup.init({yPos:50, 
			content:content, 
			width:'400',
			theme:'aquaTheme', 
			align:'center'
		});
		Popup.show();
	}

	if(!Preferences.isModified()) {
		complete();
	} else {
		Preferences.save(false, complete);
	}
}

function deleteFavsWarning(favID, module) {

	//get the row element:
	var row = $(module+"Row"+favID);
	
	//get the id of the module holding this row:
	var moduleID = row.up('.module').id;
	
	var content = '<center><strong>Are you sure you would like to delete this item?<br><br>'
				+ '<a href="javascript:void(null);" onclick="deleteFavs('+favID+', \''+module+'\'); Popup.close(); return false;">Yes</a>'
				+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(null);" onclick="Popup.close(); return false;">No</a></strong></center>';
	
	//get the originating module's style:
	var theme = (Modules.getStyle(Preferences.modules[moduleID]['style'])).style;
	
	//get the originating module's column:
	var align = 'center';
	var column = Preferences.modules[moduleID]['column'];
	if(column == 0) align = 'left';
	else if(column == 2) align = 'right';
	
	//get the originating module's Y position:
	var offset = $(moduleID).positionedOffset();
	
	//get the rows offset from the module: 
	var rowOffset = row.positionedOffset();
	
	Popup.close();
	Popup.init({yPos:100 + offset.top + rowOffset.top, content:content, align:align, theme:theme, width:250});
	Popup.show();
}

function changeGlobalTheme(theme) {
	for(var i = 0; i < Preferences.modules.length; i++) {
		if(Preferences.modules[i]) {
			var id = Preferences.modules[i].id;
			var mod = $('' + id);
			if(mod.hasClassName('module')) {
				mod.className = "module "+ (Modules.getStyle(theme)).style; 
			} else {
				mod.className = "notMovableModule "+ (Modules.getStyle(theme)).style; 
			}
			Preferences.changeModuleStyle(id, (Modules.getStyle(theme)).id);
		}
	}
}
	
/////Module Content //////
function deleteFavs(favID,module) {
	 new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + "removeContent.php?favID=" + favID + "&module="+ module, { 
		 method: 'get'}	);
				id = module+"Row"+favID;
				id2 = module+"Row2"+favID;
				tablebody = module+"List";
				tbody = $(tablebody);
				contentRow = $(id);
				contentRow2 = $(id2);
				tbody.removeChild(contentRow);
				tbody.removeChild(contentRow2);
	}
bdayID = "a";	
function toggleBirthdays(id) {
	$(bdayID).style.display = "none";
	$(id).style.display = "block";
	bdayID = id;
}

var HotOrNot = {
	currentID: 0,
	currentItem: "",
	currentHot: 0,
	currentNot: 0,
	interval: null,
	
	vote: function(vote) {
		var voteText = '';
		if(vote) {
			voteText = 'hot';
			this.currentHot++;
		} else {
			voteText = 'not';
			this.currentNot++;
		}

		//now display the results:			
		var hotPercent = Math.ceil((this.currentHot/(this.currentHot + this.currentNot))*100);
		var notPercent = 100 - hotPercent;
		
		$A($$('#hotOrNotPostVote .hot .votes'))[0].innerHTML = hotPercent + '%';
		$A($$('#hotOrNotPostVote .not .votes'))[0].innerHTML = notPercent + '%';
		
		var hot = $A($$('#hotOrNotPostVote .hot'))[0];
		var not = $A($$('#hotOrNotPostVote .not'))[0];
		
		hot.setStyle({display:'none'});
		not.setStyle({display:'none'});

		$('hotOrNotPostVote').toggle();
		$('hotOrNotPreVote').toggle();
		
		var complete = function() {
			not.appear({duration:0.5});
		};
		hot.appear({duration:0.5, afterFinish:complete});
	
		//record the results:
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'saveHotOrNot.php', {
			method:'post',
			parameters: {id:this.currentID, vote:voteText},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					//$('hotOrNotItem').innerHTML = json.next['item'];
					HotOrNot.currentItem = json.next['item'];
					HotOrNot.currentHot = parseInt(json.next['hot']);
					HotOrNot.currentNot = parseInt(json.next['not']);
					HotOrNot.currentID = parseInt(json.next['id']);
					HotOrNot.interval = setTimeout('HotOrNot.showNext();', 5000);
				} else {
					alert('Sorry, we could not load the next Hot or Not.');
				}
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the next Hot or Not.');
			}
		});
	},
	showNext: function() {
		var title = this.currentItem;
		var complete = function() {
			$('hotOrNotPreVote').appear({duration:0.5});
			$('hotOrNotItem').innerHTML = title;
		};
		$('hotOrNotPostVote').fade({duration:0.5, afterFinish:complete});
	}
};

var Horoscopes = {
	horoscopes: [],
	
	
	load: function(onComplete) {
		
		var obj = this;
	
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'loadHoroscopes.php', {
			method:'get',
			parameters: {},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					obj.horoscopes = json.horoscopes;
					onComplete(obj);
				} else {
					alert('Sorry, we could not load the Horoscopes.');
				}
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the Horoscopes.');
			}
		});
	},
	
	showAll: function() {
		var complete = function(obj) {
			var content = '<table cellspacing="0" cellpadding="0" border="0">';
			content += '<tr>';
			for(var i = 0; i < 3; i++) content += obj.createBox(obj.horoscopes[i]);
			content += '</tr>';
			
			content += '<tr>';
			for(var i = 3; i < 6; i++) content += obj.createBox(obj.horoscopes[i]);
			content += '</tr>';
			
			content += '<tr>';
			for(var i = 6; i < 9; i++)content += obj.createBox(obj.horoscopes[i]);
			content += '</tr>';
			
			content += '<tr>';
			for(var i = 9; i < 12; i++) content += obj.createBox(obj.horoscopes[i]);
			content += '</tr>';
			content += '</table>';
			
			//get the y-position of the module:
			var offset = $('2').positionedOffset();
			//offset.top
			var popupOffset = 0;
			if(offset.top > 400) popupOffset = offset.top - 400;

			var theme = (Modules.getStyle(Preferences.modules[2]['style'])).style;
			Popup.init({yPos:20 + popupOffset, content:content, width:'auto', theme:theme});
			Popup.show();
		}
		this.load(complete);
	},
	
	createBox: function(obj) {
		content = '<td><div style="height:100%;" class="innerBoxContainer"><div class="innerBox"><div class="horoscopesContent" style="height:245px;">'
		+ '<div class="titleBox">'
		+	'<img src="/images/community/modules/horoscopes/'+obj.image+'" />'
		+	'<div class="title" align="left">'+obj.title+'</div>'
		+ '</div>'
		+ '<div class="dateRange" align="center">'+obj.date+'</div>'
		+ '<div class="description" align="center">'+obj.details+'</div>'
		+ '</div></div></div></td>';
		return content;
	}
};

var News = {
	
	currentPage: 1,
	
	nextPage: function() {
		this.getPage(++this.currentPage);
	},
	
	prevPage: function() {
		if(this.currentPage > 1) this.getPage(--this.currentPage);
	},
	
	getPage: function(page) {		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'loadNews.php', {
			method:'get',
			parameters: {page:page},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					var content = '';
					var len = json.news.length;
					for(var i = 0; i < len; i++) {
						content += '<li><a href="'+json.news[i].url+'">'+json.news[i].content+'</a></li>';
					}
					
					var newsContent = $A($$('.newsContent ul'))[0];
					var complete = function() {
						newsContent.innerHTML = content;
						new Effect.Opacity(newsContent, {from:0, to:1, duration:0.5});
					};
					new Effect.Opacity(newsContent, {from:1, to:0, duration:0.5, afterFinish:complete});
					
					//$A($$('.newsContent ul'))[0].innerHTML = content;
					
					if(json.more) $('nextNews').setStyle({display:'block'});
					else $('nextNews').setStyle({display:'none'});
					if(page > 1) $('prevNews').setStyle({display:'block'});
					else $('prevNews').setStyle({display:'none'});
					
				} else {
					alert('Sorry, we could not load the News.');
				}
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the News.');
			}
		});
	}
	
};


var FAQ =  {	
	open: function() {
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'faq.php', {
			method:'get',
			parameters: {},
			onSuccess: function(transport){	
				Popup.close();
				Popup.init({yPos:20, 
					content:transport.responseText, 
					width:'690',
					theme:'aquaTheme', 
					align:'center',
					position:'auto'
				});
				Popup.show();
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the FAQ.');
			}
		});
	},
	
	close: function() {
		Popup.close();
	}
};

var SafetyTips = {
	open: function() {
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'faq.php', {
			method:'get',
			parameters: {},
			onSuccess: function(transport){	
				Popup.close();
				Popup.init({yPos:20, 
					content:transport.responseText, 
					width:'690',
					theme:'aquaTheme', 
					align:'center',
					position:'auto'
				});
				Popup.show();
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the FAQ.');
			}
		});
	},
	
	close: function() {
		Popup.close();	
	}
};

var SmallBox = {
	
	smallboxes: [],
	currentBox: -1,
	
	load: function() {
		new Ajax.Request('xml/smallbox.xml', {
			method:'get',
			parameters: {},
			onSuccess: function(transport){	
				var doc = transport.responseXML.documentElement; 
				
				var images = doc.getElementsByTagName('image');
				var urls = doc.getElementsByTagName('url');
				var targets = doc.getElementsByTagName('window');
				for(var i = 0, len = images.length; i < len; ++i) {
					var obj = {};
					obj.image = images[i].firstChild.data;
					obj.url = urls[i].firstChild.data;
					obj.target = (targets[i].firstChild.data == 0)? '_self' : '_blank';
					SmallBox.smallboxes.push(obj);
				}
				SmallBox.start();
			},
			onFailure: function(){ 
				//
			}
		});
	},
	
	start: function() {
		SmallBox.display();
		new PeriodicalExecuter(function(pe) {
			SmallBox.display();
		}, 5);
	},

	display: function() {
		var obj = SmallBox.getNext();
		var content = '<img src="'+obj.image+'" />';
		if(obj.url) {
			content = '<a href="'+obj.url+'" target="'+obj.target+'">' + content + '</a>';
		}
		$('smallboxContent').innerHTML = content;
	},
	
	getNext: function() {
		++SmallBox.currentBox;
		if(SmallBox.currentBox >= SmallBox.smallboxes.length) SmallBox.currentBox = 0;
		return SmallBox.smallboxes[SmallBox.currentBox];
	}
	
};

var Friends = {

	invite: function() {
		var name = $F('friendRequestName');
		var email = $F('friendRequestEmail');
		
		if(name == '' || email == '') {
			Friends.setMessage('You must provide a name and email!');
			return;
		}
		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'inviteFriend.php', {
			method:'post',
			parameters: {name:name, email:email},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				//if(json.message == 'success') {
					Friends.setMessage('Your invite has been sent!');
					setTimeout(Friends.reset, 5000);
				//} else {
				//	Friends.setMessage('Sorry, we could not send your invite.');
				//}
			},
			onFailure: function(){ 
				Friends.setMessage('Sorry, we could not send your invite.');
			}
		});
	},
	
	setMessage: function(msg) {
		$('friendRequestMessage').update(msg);
	},
	
	reset: function() {
		$('friendRequestName').value = '';
		$('friendRequestEmail').value = '';
		Friends.setMessage('');
	},
	
	remove: function(id) {		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'removeFriend.php', {
			method:'post',
			parameters: {friendID:id},
			onSuccess: function(transport){
				if(transport.responseText == 'success') {
					Popup.close();
					$('friendsListRow' + id).remove();
				}
			},
			onFailure: function() { 
			
			}
		});
	},
	
	removeWarning: function(id, moduleID) {
		var content = '<center><strong>Are you sure you want to remove this Famfriend from your list?<br><br>'
				+ '<a href="javascript:void(null);" onclick="Friends.remove('+id+'); return false;">Yes</a>'
				+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(null);" onclick="Popup.close(); return false;">No</a></strong></center>';		
		
		//get the originating module's style:
		var theme = (Modules.getStyle(Preferences.modules[moduleID]['style'])).style;
		
		//get the originating module's column:
		var align = 'center';
		var column = Preferences.modules[moduleID]['column'];
		if(column == 0) align = 'left';
		else if(column == 2) align = 'right';
		
		//get the originating module's Y position:
		var offset = $(moduleID + "").positionedOffset();
		
		//get the rows offset from the module: 
		var rowOffset = $('friendsListRow'+id).positionedOffset();
		
		Popup.close();
		Popup.init({yPos:offset.top + rowOffset.top + 100, content:content, align:align, theme:theme, width:250});
		Popup.show();
	},
	
	setHeight: function() {
		var count = $$('#friendsList .friendsListRow').length;
		if(count < 8 & count > 0) {
			$('friendsList').setStyle({height:30*count});
		} else if(count == 0 && $('friendsList') != null) {
			$('friendsList').setStyle({height:50});
		}
	},
	
	setupTooltip: function() {
		var fList = $('friendsList');
		if(fList != null) {
			Event.observe(fList, 'mouseover', Friends.tooltipMouseover);
			Event.observe(fList, 'mouseout', Friends.tooltipMouseout);
		}
	},
	
	tooltipMouseover: function(e) {
		var ele = e.element();
		
		if(ele.nodeName.toLowerCase() == 'a') {
			var par = e.element().up('div.friendsListRow');
			var fromTop = par.positionedOffset()[1];
			$('friendsTooltipContent').update("View " + ele.innerHTML + "'s page");
			$('friendsTooltip').setStyle({top:fromTop - par.getHeight()}).show();
		}
	},
	
	tooltipMouseout: function(e) {
		var ele = e.element();
		
		if(ele.nodeName.toLowerCase() == 'a') {
			$('friendsTooltip').hide();
		}
	},
	
	init: function() {
		Event.observe(window, 'load', function() {
			Friends.setHeight();
			Friends.setupTooltip();
		});
	}
};
Friends.init();

var Messages = {
		
	currentPage: 1,
		
	send: function() {
		var friendID = $F('sendMessageFriend');
		var messageID = $F('choosenMessageID');
		
		if(friendID == '' || messageID == '' || friendID < 0 || messageID < 0) {
			Messages.setMessage('You must select a Friend and a message!');
			return;
		}
		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'sendMessage.php', {
			method:'post',
			parameters: {f:friendID, m:messageID},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				//if(json.message == 'success') {
					Messages.setMessage('Your message has been sent!');		
					setTimeout(Messages.reset, 5000);
				//} else {
				//	Messages.setMessage('Sorry, we could not send your message.');
				//}
			},
			onFailure: function(){ 
				Messages.setMessage('Sorry, we could not send your message.');
			}
		});
	},
	
	setMessage: function(msg) {
		$('sendMessageResult').update(msg);
	},
	
	reset: function() {
		$('sendMessageFriend').selectedIndex = 0;
		$('choosenMessageID').value = -1;
		$('choosenMessage').update('Click to choose');
		Messages.setMessage('Send a message to your Famfriend!');
	},

	selectMessage: function(index, messageID) {
		$('choosenMessage').update($$('#messageListContainer p a')[index].innerHTML);
		$('choosenMessageID').value = messageID;
		Popup.close();
	},
	
	openMessagesPopup: function(moduleID) {
		//get the originating module's style:
		var theme = (Modules.getStyle(Preferences.modules[moduleID]['style'])).style;
		
		//get the originating module's column:
		var align = 'center';
		var column = Preferences.modules[moduleID]['column'];
		if(column == 0) align = 'left';
		else if(column == 2) align = 'right';
		
		//get the originating module's Y position:
		var offset = $(moduleID).positionedOffset();
		
		//get how far from the top of the module:
		var offsetFromTop = $(moduleID).getHeight() - 190;
		
		Popup.close();
		Popup.init({yPos:100 + offset.top + offsetFromTop, content:$('messageListContainer').innerHTML, align:align, theme:theme, width:250});
		Popup.show();
	},
	
	selectFriend: function(index, friendID) {
		var links = $$('#messagesSelectFriend .collapsibleSelectContent .collapsibleSelectOption');
		$('messagesSelectFriend').down('input.collapsibleSelectValue').value = friendID;
		$('messagesSelectFriend').down('.collapsibleSelectButton').update(links[index].innerHTML);
	},
	
	remove: function(id) {		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'removeMessage.php', {
			method:'post',
			parameters: {messageID:id},
			onSuccess: function(transport){
				if(transport.responseText == 'success') {
					Popup.close();
					$('messagesListRow' + id).remove();
				}
			},
			onFailure: function() { 
			
			}
		});
	},
	
	removeWarning: function(id, moduleID) {
		var content = '<center><strong>Are you sure you want to delete this message?<br><br>'
				+ '<a href="javascript:void(null);" onclick="Messages.remove('+id+'); return false;">Yes</a>'
				+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(null);" onclick="Popup.close(); return false;">No</a></strong></center>';		
		
		//get the originating module's style:
		var theme = (Modules.getStyle(Preferences.modules[moduleID]['style'])).style;
		
		//get the originating module's column:
		var align = 'center';
		var column = Preferences.modules[moduleID]['column'];
		if(column == 0) align = 'left';
		else if(column == 2) align = 'right';
		
		//get the originating module's Y position:
		var offset = $(moduleID + "").positionedOffset();
		
		//get the rows offset from the module: 
		var rowOffset = $('messagesListRow'+id).positionedOffset();
		
		Popup.close();
		Popup.init({yPos:offset.top + rowOffset.top + 100, content:content, align:align, theme:theme, width:250});
		Popup.show();
	},
	
	nextPage: function() {
		this.getPage(++this.currentPage);
	},
	
	prevPage: function() {
		if(this.currentPage > 1) this.getPage(--this.currentPage);
	},
	
	getPage: function(page) {		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'loadMessages.php', {
			method:'get',
			parameters: {page:page},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					var content = '';
					var len = json.messages.length;
					for(var i = 0; i < len; i++) {
						content += '<div class="messagesListRow contentListBorder" id="messagesListRow'+json.messages[i].id+'">'+json.messages[i].message+'<div>- <a href="f.php?f='+json.messages[i].fromUserID+'">'+json.messages[i].fromUsername+'</a></div><div class="deleteButton"><a href="javascript:void(null);"><img src="/images/community/delete.gif" onclick="Messages.removeWarning('+json.messages[i].id+', '+json.moduleID+');" /></a></div></div>';

					}
					$('messagesList').update(content);
					
					if(json.more) $('nextMessages').setStyle({display:'block'});
					else $('nextMessages').setStyle({display:'none'});
					if(page > 1) $('prevMessages').setStyle({display:'block'});
					else $('prevMessages').setStyle({display:'none'});
					
				} else {
					alert('Sorry, we could not load the News.');
				}
				
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the News.');
			}
		});
	}
	
};

var KicksStandings = {
	points: [],
	highestPoints: 1,
	init: function(blue, green, red, yellow) {
		KicksStandings.points[0] = blue;
		KicksStandings.updateHighestPoints(blue);
		KicksStandings.points[1] = green;
		KicksStandings.updateHighestPoints(green);
		KicksStandings.points[2] = red;
		KicksStandings.updateHighestPoints(red);
		KicksStandings.points[3] = yellow;
		KicksStandings.updateHighestPoints(yellow);
	},
	
	updateHighestPoints: function(total) {
		if(total > KicksStandings.highestPoints) KicksStandings.highestPoints = total;
	},
	
	animate: function() {
		for(var i = 0, total = KicksStandings.points.length; i < total; ++i) {
			KicksStandings.animateRow(i);
		}
	},
	
	animateRow: function(id) {
		var row = $$(".standingsContent #team"+(id + 1)+"Row .standingsRibbon")[0];
		var width = parseInt((KicksStandings.points[id]/KicksStandings.highestPoints)*80);
		var oldWidth = parseInt(row.getStyle('width'));
		var newWidth = oldWidth + width;
		row.morph('width:'+newWidth+';');
		$$(".standingsContent #team"+(id + 1)+"Row .standingsPoints")[0].update(KicksStandings.points[id] + ' points');
	}
};


var KicksMiniGame = {
	
	userID:0,
	gameID:0,
	scriptURL:'',
	updateFunction:'',
	score:0,
	
	updateFlashVars: function(score) {
		if(score) {
			KicksMiniGame.score = score;
		}
		if(!isIE) {
			var flashvars = "updateFunction="+KicksMiniGame.updateFunction
				+"&scriptURL="+KicksMiniGame.scriptURL+"&userID="+KicksMiniGame.userID
				+"&gameID="+KicksMiniGame.gameID+"&score=" + KicksMiniGame.score;
			$("fkGame").setAttribute("flashvars", flashvars);
		}

	}
	
}


var Mood = {
	
	hasChangedMood: false,
	futureMoodChange: null,
	
	open: function() {
		$('moodSelector').show();
		$('moodSelector2').show();
		//new Effect.SlideDown('moodSelectorContainer', {duration:1});
	},
	
	close: function() {
		$('moodSelector').hide();
		$('moodSelector2').hide();
		//new Effect.SlideUp('moodSelectorContainer', {duration:1});
	},
	
	toggle: function() {
		if($('moodSelector').getStyle('display') == 'none') Mood.open();
		else Mood.close();
	},
	
	select: function(e) {
		var ele = $(Event.element(e));
		if(ele.tagName.toLowerCase() == 'span') {
			ele = ele.up('li');
		} else if(ele.tagName.toLowerCase() == 'img') {
			ele = ele.up('li');
		}
		
		var id = ele.readAttribute('id').replace('mood-', '');
		var content = ele.down('span').innerHTML;
		$('moodimage').src = '/images/community/moods/large/'+id+'.gif';
		$('moodtext').update(content);
		Mood.save(id);
		Mood.close();
	},
	
	init: function() {
		Event.observe(window, 'load', function(e) {
			$('moodSelector').observe('click', Mood.select);
			$('moodSelector2').observe('click', Mood.select);
		});
	}, 
	
	save: function(moodID) {
		if(Mood.hasChangedMood) {
			clearTimeout(Mood.futureMoodChange);
			Mood.futureMoodChange = setTimeout(function() {
				Mood.sendToServer(moodID);
			}, 3000);
		} else {
			Mood.sendToServer(moodID);
			Mood.hasChangedMood = true;
		}
	},
	
	sendToServer: function(moodID) {
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'updateMood.php', {
			method:'post',
			parameters: {moodID:moodID}
		});
	}
};
Mood.init();


var Activity = {
	
	currentPage: 1,
	
	nextPage: function() {
		this.getPage(++this.currentPage);
	},
	
	prevPage: function() {
		if(this.currentPage > 1) this.getPage(--this.currentPage);
	},
	
	getPage: function(page) {		
		new Ajax.Request(FamclubProfiles.SCRIPTS_PATH + 'loadActivities.php', {
			method:'get',
			parameters: {page:page},
			onSuccess: function(transport){
				var json = transport.responseText.evalJSON(true);
				
				if(json.message == 'success') {
					var content = '';
					var len = json.activities.length;
					for(var i = 0; i < len; i++) {
						content += '<div class="contentListBorder"><a href="' + json.activities[i].url + '">' + json.activities[i].string + '</a></div>';
					}
					$('activityList').update(content);
					
					if(json.more) $('nextActivities').setStyle({display:'block'});
					else $('nextActivities').setStyle({display:'none'});
					if(page > 1) $('previousActivities').setStyle({display:'block'});
					else $('previousActivities').setStyle({display:'none'});
					
				} else {
					alert('Sorry, we could not load the next activities.');
				}
				
			},
			onFailure: function(){ 
				alert('Sorry, we could not load the next activities.');
			}
		});
	}
};


function trackPageActivity(description) {
	var s=s_gi('astralfamilyca' ); 
	s.tl(this,'o','Famclub Profiles: ' + description);
}

		