//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth;
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src;
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href;
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------


//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth;
	},
	setWidth: function(element,w) {
	   	element = $(element);
    	element.style.width = w +"px";
	},
	setHeight: function(element,h) {
   		element = $(element);
    	element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
    	element.style.top = t +"px";
	},
	setLeft: function(element,l) {
	   	element = $(element);
    	element.style.left = l +"px";
	},
	setSrc: function(element,src) {
    	element = $(element);
    	element.src = src;
	},
	setHref: function(element,href) {
    	element = $(element);
    	element.href = href;
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

var user_id;
var recent_carousel;
var friend_carousel;
var drag_start_section;
var swfu;

//
// addFriend()
// No return value
// Adds the currently loaded profile as a friend of the logged-in user
//
//
function addFriend(user_id, friend_id) {

	new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: {action:'addfriend', user:user_id, friend:friend_id},
				onComplete: function(transport) {
					alert('This member has been added to your friend list.');
					$('toggleFriend').update('<a class="add" href="#" onclick="removeFriendExternally('+user_id+', '+friend_id+');return false;" title="Remove from Friends">Remove from Friends</a>');
					new Effect.Highlight($('toggleFriend'), {duration: 2});
				}
		});
}

// -----------------------------------------------------------------------------------

//
// addIgnore()
// No return value
// Adds the currently loaded profile to the ignore list of the logged-in user
//
//
function addIgnore(user_id, ignore_id) {

	new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: {action:'addignore', user:user_id, ignore:ignore_id},
				onComplete: function(transport) {
					alert('This member has been added to your ignore list.');
					$('toggleIgnore').update('<a class="ignore2" href="#" onclick="removeIgnore('+user_id+', '+ignore_id+');return false;" title="Stop Ignoring">Stop Ignoring</a>');
					new Effect.Highlight($('toggleIgnore'), {duration: 2});
				}
		});
}

// -----------------------------------------------------------------------------------

//
// addModule()
// No return value
// Adds the chosen module to the user's profile page
//
//
function addModule(id, section) {

	new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: {action:'addmodule', user:user_id, mod:id, section:section},
				onComplete: function(transport) {
					module = Element.insert(section, { top: transport.responseText });
					new Effect.Highlight(module.firstDescendant(), {duration: 2});

					// Reset the sortables
					initSortables();

					// Update the positions of the modules in this section
					reorderModules(section);
				}
		});

	Effect.Shrink('browsecontainer', {duration: 0.3});
	Effect.Fade('overlay', {duration:0.4,to:0.0});
}

// -----------------------------------------------------------------------------------

//
// closeBrowse()
// No return value
// Just closes the browse modules window
//
//
function closeBrowse() {
	Effect.Shrink('browsecontainer', {duration: 0.3});
	Effect.Fade('overlay', {duration:0.4,to:0.0});
}

// -----------------------------------------------------------------------------------

//
// closeConfiguration()
// No return value
// Triggers closing animations and submits configuration changes
//
//
function closeConfiguration(umodid, save) {

	save = typeof(save) != 'undefined' ? save : true;

	if (save) {
		eval('$(\'modcontent_'+umodid+'\').update(\'<div class="loading"><img src="/euprofile/images/ajax-loader.gif" width="28" height="28" alt="Loading new content"/></div>\');');

		new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: $('configure_form').serialize(true),
				onComplete: function(transport) {
					eval('$(\'module_'+umodid+'\').update(transport.responseText);');

					// Have to reinitialize the glider
					if ($('friends')) {
						friend_carousel = new Glider('friends', {duration:0.5});
					}

					// When we refresh a module, it recreates the handle, so we have to re-initialize sortables
					initSortables();
				}
			}
		);
	}

	Effect.Shrink('configcontainer', {duration: 0.2});
	Effect.Fade('overlay', {duration:0.5,to:0.0});
}

// -----------------------------------------------------------------------------------

//
// initProfile()
// No return value
// Gets everything set up and ready to go
//
//

function initProfile(user) {
	user_id = user;

	if ($('recent')) { recent_carousel = new Glider('recent', {duration:0}); }

	if ($('friends')) { friend_carousel = new Glider('friends', {duration:0.5}); }

	if (readCookie('wht_member_panel') == '1' && $('member_panel_contents')) { $('member_panel_contents').setStyle({display:'block'}); }
}

// -----------------------------------------------------------------------------------

//
// initProfileOwner()
// No return value
// Gets everything set up and ready to go
//
//
function initProfileOwner(swf) {
	initSortables();
}

// -----------------------------------------------------------------------------------

//
// initProfile()
// No return value
// Gets everything set up and ready to go
//
//

function initSWFUpload(session_id, token) {
	swfu = new SWFUpload({
			// Backend Settings
			upload_url: "/euprofile/AjaxHandler.php",	// Relative to the SWF file
			post_params: {
				"session": session_id+'',
				"user": user_id+'',
				"token": token+'', // Retarded hack to turn the user_id into a string, otherwise it won't get passed in the request
				"action": "upload_business_logo"
			},

			// File Upload Settings
			file_size_limit : "2048",	// 2MB
			file_types : "*.jpg;*.gif;*.png",
			file_types_description : "Web Image Files",
			file_upload_limit : "0",

			// Event Handler Settings - these functions as defined in Handlers.js
			//  The handlers are not part of SWFUpload but are part of my website and control how
			//  my website reacts to the SWFUpload events.
			file_queue_error_handler : fileQueueError,
			file_dialog_complete_handler : fileDialogComplete,
			upload_progress_handler : uploadProgress,
			upload_error_handler : uploadError,
			upload_success_handler : uploadSuccess,
			upload_complete_handler : uploadComplete,

			// Flash Settings
			flash_url : "euprofile/js/swfupload/swfupload_f9.swf",	// Relative to this file

			custom_settings : {
				upload_target : "FileProgressStatus"
			},

			// Debug Settings
			debug: false
		});
}

// -----------------------------------------------------------------------------------

//
// initSortables()
// No return value
// Initializes scriptaculous sortables
//
//
function initSortables() {

	Sortable.create('right_sortable', {
			dropOnEmpty: true,
			containment: ['right_sortable', 'left_sortable'],
			constraint: false,
			handle: 'modheader',
			onStart: function(draggable, event) { drag_start_section = draggable.element.parentNode.id; },
			onUpdate: function() { reorderModules('right_sortable'); },
			onEnd: function(draggable, event) {
				if (drag_start_section != draggable.element.parentNode.id) {
					refreshModule(draggable.element.id.substring(7));
				}
			}
		}
	);

	Sortable.create('left_sortable', {
			dropOnEmpty: true,
			containment: ['left_sortable', 'right_sortable'],
			constraint: false,
			handle: 'modheader',
			onStart: function(draggable, event) { drag_start_section = draggable.element.parentNode.id; },
			onUpdate: function() { reorderModules('left_sortable'); },
			onEnd: function(draggable, event) {
				if (drag_start_section != draggable.element.parentNode.id) {
					refreshModule(draggable.element.id.substring(7));
				}
			}
		}
	);
}

// -----------------------------------------------------------------------------------

//
// initTrash()
// No return value
// Initializes the trash icon for the friends list elements
//
//
function initTrash(id, umodid) {
	var content = '<a href="#" onclick="removeFriend('+id+', '+umodid+');return false;"><img alt="Remove this friend" src="/euprofile/images/remove.png"/></a></div>';
	new Tip('friend_'+id, content, { className: 'trash', effect: 'appear', hook: { tip: 'topRight', target: 'topRight' }, hideAfter: 0.1, hideOn: false });
}

// -----------------------------------------------------------------------------------

//
// openBrowse()
// No return value
// Opens a window for browsing/adding new modules to your profile
//
//
function openBrowse() {

	new Ajax.Updater('browsecontent', '/euprofile/AjaxHandler.php?action=browse', {method:'get', parameters:{user:user_id}});

	var arrayPageSize = getPageSize();
	Element.setWidth('overlay', arrayPageSize[0]);
	Element.setHeight('overlay', arrayPageSize[1]);

	Effect.Appear('overlay', {duration:0.2, from:0.0, to:0.9});
	Effect.Center('browsecontainer');
	Effect.Grow('browsecontainer', {direction:'center'});
}

// -----------------------------------------------------------------------------------

//
// openConfiguration()
// No return value
// Triggers closing animations and submits configuration changes
//
//
function openConfiguration(id, width, height) {


	$('configcontent').update('<div class="loading"><img src="/euprofile/images/ajax-loader.gif" width="28" height="28" alt="Loading new content"/></div>');

	new Ajax.Updater('configcontent', '/euprofile/AjaxHandler.php', {method:'get', parameters:{action:'configure', user:user_id, umod:id}});

	var arrayPageSize = getPageSize();
	Element.setWidth('overlay', arrayPageSize[0]);
	Element.setHeight('overlay', arrayPageSize[1]);

	width = width != '' ? width : 550;
	height = height != '' ? height : 300;

	$('configcontainer').setStyle({
	  width: width+'px',
	  height: height+'px'
	});

	Effect.Appear('overlay', {duration:0.2, from:0.0, to:0.9});
	Effect.Center('configcontainer');
	Effect.Grow('configcontainer', {direction:'center', duration:0.5});
}

// -----------------------------------------------------------------------------------

//
// refreshModule()
// No return value
// Updates the content of the module
//
//
function refreshModule(umodid) {
	eval('$(\'modcontent_'+umodid+'\').update(\'<div class="loading"><img src="/euprofile/images/ajax-loader.gif" width="28" height="28" alt="Loading new content"/></div>\');');

	new Ajax.Updater('module_'+umodid, '/euprofile/AjaxHandler.php', {
		method:'get',
		parameters:{ action:'fetchContent', user:user_id, umod:umodid },
		evalScripts: true,
		onComplete: function() {
			// Have to reinitialize the glider
			if ($('friends')) {
				friend_carousel = new Glider('friends', {duration:0.5});
			}

			// When we refresh a module, it recreates the handle, so we have to re-initialize sortables
			initSortables();
		}
	});
}

// -----------------------------------------------------------------------------------

//
// removeIgnore()
// No return value
// Removes the member from the user's ignore list
//
//
function removeIgnore(user_id, ignore_id) {
	new Ajax.Request('/euprofile/AjaxHandler.php', {
			parameters: {action:'removeignore', user:user_id, ignore:ignore_id},
			onComplete: function(transport) {
				alert('This member has been removed from your ignore list.');
				$('toggleIgnore').update('<a class="ignore2" href="#" onclick="addIgnore('+user_id+', '+ignore_id+');return false;" title="Ignore This Member">Ignore This Member</a>');
				new Effect.Highlight($('toggleIgnore'), {duration: 2});
			}
	});
}

// -----------------------------------------------------------------------------------

//
// removeFriend()
// No return value
// Removes the member from the user's buddy list
//
//
function removeFriend(friend_id, umodid) {
	if (confirm('Click "Ok" to remove this member from your friend list.')) {
		new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: {action:'removefriend', user:user_id, friend:friend_id},
				onComplete: function(transport) {
					refreshModule(umodid);
				}
		});
	}
}

// -----------------------------------------------------------------------------------

//
// removeFriend()
// No return value
// Removes the member from the user's buddy list
//
//
function removeFriendExternally(user_id, friend_id) {
	new Ajax.Request('/euprofile/AjaxHandler.php', {
			parameters: {action:'removefriend', user:user_id, friend:friend_id},
			onComplete: function(transport) {
				alert('This member has been removed from your friend list.');
				$('toggleFriend').update('<a class="add" href="#" onclick="addFriend('+user_id+', '+friend_id+');return false;" title="Add to Friend List">Add to Friend List</a>');
				new Effect.Highlight($('toggleFriend'), {duration: 2});
			}
	});
}

// -----------------------------------------------------------------------------------

//
// removeModule()
// No return value
// Removes the module from the user's profile
//
//
function removeModule(umodid) {

	if (confirm('This module will be removed from your profile layout. You can add it back at any time by clicking the "Add module" button. Click "Ok" to remove this module.')) {

		Effect.BlindUp('module_'+umodid);

		new Ajax.Request('/euprofile/AjaxHandler.php', {
				parameters: {action:'remove', user:user_id, umod:umodid},
				onComplete: function(transport) {
					eval('$(\'module_'+umodid+'\').remove();');
				}
		});
	}
}

// -----------------------------------------------------------------------------------

//
// reorderModules()
// No return value
// Removes the module from the user's profile
//
//
function reorderModules(section) {

	new Ajax.Request('/euprofile/AjaxHandler.php', {
		parameters:{
			action: 'reorder',
			user: user_id,
			data: Sortable.serialize(section)
		}}
	);
}

// -----------------------------------------------------------------------------------

//
// toggleMemberPanel()
// No return value
// Opens/Closes member panel and sets required cookies
//
//
function toggleMemberPanel() {
	if (readCookie('wht_member_panel') == '0') {
		Effect.BlindDown('member_panel_contents', {
			afterFinish: function() {
				createCookie('wht_member_panel', 1, 30);
			}
     });

	} else {
		Effect.BlindUp('member_panel_contents', {
			afterFinish: function() {
				createCookie('wht_member_panel', 0, 30);
			}
     });
	}
}

// -----------------------------------------------------------------------------------


function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}
