/* global static vars */
var infoEditForm,htmlContainer,currHometownName;

function displayTab(tab,canEdit,onPageLoad) {
	var callback = false,defTab = 'activityfeed';
	switch(tab) {
		case 'info':
		case 'editinfo':
			if (tab=='editinfo' && canEdit) callback = function(){clickEdit()};
			tab = 'info';
			break;
		case 'changepic':
			tab = canEdit ? 'changepic' : defTab;
			break;
		case 'changeavatar':
			tab = canEdit ? 'changeavatar' : defTab;
			break;
		default:
			callback = function(){activityFeedLoad()};
			tab = defTab;
	}
	loadTab(tab,callback,onPageLoad);
	return false;
}
function loadTab(tab,callback,onPageLoad) {
	if (!onPageLoad) location.hash = tab;
	// switch tab
	$('#menu li').removeClass('selected');
	$('#' + tab + 'Tab').addClass('selected');
	// reload ad
	$('#' + profileMpuId).attr( 'src', $('#' + profileMpuId).attr('src') );
	// check if already loaded
	if ($('#' + tab).length) {
		$('#contentPane .tab').hide();
		if (onPageLoad) $('#contentPane').show();
		$('#' + tab).show();
		if (callback) callback();
		return false;
	}
	// load data
	$.ajax({
			type: 'GET',
			url: urlProfile,
			data: {'tab': tab},
			complete: function() { 
				// run callback funct if defined
				if (callback) callback();
				loading(false); 
			},
			error: function(a,b,c) {},
			success: function(msg) {
				// create new element
				$('#contentPane .tab').hide();
				$('#contentPane').append('<div id="' + tab + '" class="tab">' + msg + '</div>');
				// edit profile specific stuff
				if (tab=='info') {
					infoEditForm = $('#infoEdit').html();
				}
			} });
	// show loading
	if (!onPageLoad) loading(true);
}
function loading(bool) {
	if (bool) {
		$('#contentPane').hide();
		$('#loading').show();
	} else {
		$('#contentPane').show();
		$('#loading').hide();
	}
}
/* activity feed */
function activityFeedLoad() {
	resizeImgTimer = setTimeout( function() {
		$('#activityfeed .feed img').each( function(){
			if ( $(this).width() == 0 ) {
				activityFeedLoad();
			} else if ( $(this).width() > 0 ) {
				resizeImage($(this),maxWidth);
			}
		});
	}, 100);
}
/* edit profile */
function clickEdit(action) {
	if (action!='cancel') {
		$('#infoEdit').html(infoEditForm);
		initCitySearch();
		initInterestSearch();
		$('#infoView').fadeOut('fast', function () {
			$('#infoEdit').fadeIn('fast');
		});
	} else {
		$('#location').unautocomplete();
		$('#infoEdit').fadeOut('fast', function () {
			$('#infoView').fadeIn('fast');
		});
	}
	return false;
}
function initCitySearch() {
	currHometownName = $.trim($('#location').val());
	var fillInHometownText = 'Please enter and select your hometown above.';
	$('#location').autocomplete(urlCitySearch, {
			minChars:2,
			delay:170,
			notFoundText:'No city found',
			matchSubset:false,
			autoFill:false,
			matchContains:true,
			scroll:false,
			formatItem:function(row, i, max) {
				return row[0] + '<br /><small>' + row[2] + ', ' + row[3] + '</small>';
			},
			onKeyPress:function() {
				if ( $.trim($('#location').val()) != currHometownName && $('#countryLabel').html() != fillInHometownText) {
					$('#countryLabel').addClass('inputCountryText').html(fillInHometownText);
					$('#cityId').val('');
				}
			}
		});
	$('#location').result(function(event, data, formatted) {
		if (data) {
			$('#countryLabel').removeClass('inputCountryText').html(data[3]);
			currHometownName = $.trim($('#location').val());
			$('#cityId').val(data[1]);
		}
	});
}
function initInterestSearch() {
	$('#interests').autocomplete(urlInterestSearch, {
			minChars:2,
			delay:100,
			hideNotFound:true,
			matchSubset:false,
			autoFill:false,
			matchContains:true,
			scroll:false,
			formatItem:function(row, i, max) {
				return row[0] + '<br />';
			},
			mustMatch: false,
			selectFirst: false,
			multiple: true,
			multipleSeparator: ", ",
			// TODO: make this optional in autocomplete
			onKeyPress:function() {}
		});
}
function addOnlineIdRow(prefix) {
	// number of elements at the moment
	var numEls = $('#editFormContact .' + prefix).length;
	if ( $('#' + prefix + '_ExtraRow:visible').length ) {
		// add another
		$('#' + prefix + '_Add').before('<tr class="' + prefix + '">' + $('#' + prefix + '_ExtraRow').html() + '</tr>');
		// clear any inputs
		$('.' + prefix + ':last input').val('');
		$('.' + prefix + ':last select option:selected').removeAttr('selected');
		// hide link
		if (numEls==3) $('#' + prefix + '_Add').hide();
	} else {
		$('#' + prefix + '_ExtraRow').show();
	}
	return false;
}
function uploadImage(template) {
	if (template == 'changepic') {
		var type = 'picture', statusElement = '.profilePicStatus';
	} else {
		var type = 'image', statusElement = '.avatarStatus';
	}
	// hide any previous error messages
	$('.statusMessage:visible', top.document).hide();

	if ( !$('#userfile').val() ) {
		updateStatus('<strong>No ' + type + ' selected</strong><br />Please select a ' + type + ' on your computer by clicking the \'browse...\' button below.',top.document,statusElement)
		return false;
	}
	// get file extension of selected file
	var fileExt = getExt(getFileFromPath( $('#userfile').val().toLowerCase() ));
	var validExt = ['jpg','jpeg','gif','png'];
	if ($.inArray(fileExt+'',validExt) != -1) {
		$('#uploadForm').submit();
		htmlContainer = $('#uploadContainer').html();
		$('#uploadContainer').html( $('#loadingBarContainer').html() );
		return true;
	} else {
		updateStatus('<strong>Invalid ' + type + ' type</strong><br />Only JPEG, GIF, and PNG is accepted. Please select a valid ' + type + '.',top.document,statusElement)
		return false;
	}
}
function cancelUpload(template,hideImageElement) {
	removeCropBox();
	$('#' + template + ' .imageCropper').hide();
	if (hideImageElement) hidePreview();
	$('#' + template + ' .imageUpload').show();
	$('#' + template + ' .imageUpload iframe').contents().find('#uploadFormContainer').show();
	return false;
}
function removeImage(template,defaultImg,doRemove) {
	if (template == 'changepic') {
		var type = 'Profile Picture', element = 'profilePic';
	} else {
		var type = 'Avatar', element = 'avatar';
	}
	if ( !doRemove ) {
		confirmDialog('Confirm Remove ' + type,
					  'Are you sure you want to remove your ' + type.toLowerCase() + '?', 
					  'Remove ' + type, 
					  function () { removeImage(template,defaultImg,true); closeDialog(); return false; } );
	} else {
		$.get(urlProfile + '&tab=' + template + '&edit=1&submitaction=remove');
		$('#' + element).fadeOut(750, function () {
			$('#' + element).attr('src',defaultImg).fadeIn(750);
		});
		$('#' + template + ' .removeImage').fadeOut(750);
	}
	return false;
}
function cropImage(template,target) {
	var sel = $('#' + template + ' .imgareaselect-selection');
	$.ajax({
		type: 'POST',
		url: urlProfile + '&tab=' + template + '&edit=1&submitaction=crop',
		data: {'src': $('#' + template + ' .cropContainer img').attr('src'),
			   'w': sel.css('width'),
			   'h': sel.css('height'),
			   'x': sel.css('top'),
			   'y': sel.css('left') },
		error: function(a,b,c) { alert(b); },
		complete: function() { $('#' + template + ' .loadingBarContainer').hide(); },
		success: function(msg) {
			$('#profileAvatar').fadeOut(750);
			$(target).fadeOut(750, function () {
				$(target).attr('src',msg).fadeIn(750);
			});
			$('#' + template + ' .imageUpload iframe').contents().find('#uploadFormContainer').show();
			$('#' + template + ' .imageUpload').show();
			$('#' + template + ' .removeImage').fadeIn(750);
		} });
	$('#' + template + ' .imageCropper').hide();
	$('#' + template + ' .loadingBarContainer').show();
	return false;
}
function swapImage(template,src) {
	var element = (template == 'changepic') ? 'profilePic' : 'avatar';	
	$('#' + element,top.document).fadeOut(750, function () {
		$('#' + element,top.document).attr('src',src).fadeIn(750);
	});
	$('#' + template + ' .removeImage',top.document).fadeIn(750);
}
function loadAvatarCategory(page) {
	$.ajax({
		type: 'GET',
		url: urlProfile + '&tab=changeavatar&avatarcatid=' + $('#avatarCategoryId').val() + '&avatarpage=' + page,
		ajaxStart: timedLoading('#avatarLoading','#avatarSelection',true),
		error: function(a,b,c) {},
		success: function(msg) {
			timedLoading('#avatarLoading','#avatarSelection');
			$('#avatarSelection').html(msg);
		} });
	return false;
}
function timedLoading(loadingEl,contentEl,start) {
	if (start) {
		ajaxTimer = setTimeout( function() {
				$(contentEl).hide();
				$(loadingEl).show();
			}, 950);
	} else {
		$(loadingEl).hide();
		$(contentEl).show();
		clearTimeout(ajaxTimer);
	}
}
function setAvatar(avatarId,type) {
	var loadingEl,barcontentEl,submitaction;
	if (type == 'xboxlive') {
		loadingEl = '#xblAvatarLoading';
		contentEl = '#xblAvatarSelection';
		submitaction = 'usexbl';
	} else {
		loadingEl = '#avatarLoading';
		contentEl = '#avatarSelection';
		submitaction = 'usepreselected';
	}
	$(loadingEl + ' strong').html('Setting your avatar...');
	$.ajax({
		type: 'POST',
		url: urlProfile + '&tab=changeavatar&edit=1&submitaction=' + submitaction, 
		data: {'avatarid': avatarId },
		error: function(a,b,c) { alert(b); },
		success: function(msg) {
			$(loadingEl + ' strong').html('Done!');
			setTimeout( function() {
				swapImage('changeavatar',msg);
				$(loadingEl).fadeOut(750, function () {
					$(contentEl).fadeIn(750);
				});
			}, 500);
		} });
	$(contentEl).hide();
	$(loadingEl).show();
	return false;
}