var teamJson = {
	dataType:"json",
	minChars: 1,
	width: 310,
	max: 30,
	selectFirst: true,
	cacheLength: 0,
	highlightItem: true,
	mustMatch: false,
	formatItem: function( row, i, max, term, e ){
		if( row.id == -1 )
			return 'No matches found';
		else
            return row.name;
	},
	parse: function( data ) {
		var acd = new Array();
		for(var i=0;i<data.length;i++){
			acd[acd.length] = {data:data[i], value:data[i].achternaam, result:data[i].achternaam};
		}
        if (data.length > 0)
            $('#mospace_teamDoesntExists').hide();
        else
            $('#mospace_teamDoesntExists').show();
		return acd;
	}
};

var locJson = {
	dataType:"json",
	minChars: 3,
	width: 310,
	max: 30,
	selectFirst: true,
	cacheLength: 0,
	highlightItem: true,
	mustMatch: false,
	formatItem: function( row, i, max, term, e ){
		if( row.id == -1 )
			return 'No matches found';
		else
			return row.suburb+ ", " + row.postcode + ", " + row.state;
	},
	parse: function( data ) {
		var acd = new Array();
		for(var i=0;i<data.length;i++){
			acd[acd.length] = {data:data[i], value:data[i].achternaam, result:data[i].achternaam};
		}
		return acd;
	}
};

var ajaxPostImage = {};

function ac_delLocResponse(e, row) {
	if ( row.id != -1 )
	{
		$('#mospace_delLocationInput').hide();
		$('#mospace_delLocationData').text(row.suburb + ', ' + row.postcode + ', ' + row.state);
        $('#mospace_delLocationData').show();
		$('#mospace_delLocationChange').show();
		$('#mospace_delLocationID').text(row.id);
	}
	return false;
}

function ac_locLocResponse(e, row) {
	if ( row.id != -1 )
	{
		$('#mospace_locLocationInput').hide();
		$('#mospace_locLocationData').text(row.suburb + ', ' + row.postcode + ', ' + row.state);
		$('#mospace_locLocationData').show();
		$('#mospace_locLocationChange').show();
		$('#mospace_locLocationID').text(row.id);
	}
	return false;
}

function ac_teamNameResponse(e, row) {
	if ( row.id != -1 )
	{
		$('#mospace_teamNameACDiv').hide();
		$('#mospace_teamNameData').text(row.name);
		$('#mospace_teamNameData').parent().show();
		$('#mospace_joinATeamButton, #mospace_joinATeamButtonOr').show();
		$('#mospace_teamNameID').text(row.id);
	}
	return false;
}

function mospace_hideMoSays()
{
	$.getJSON(baseUrl+'mospace/index/hide-mo-says/',
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
					$('.mospace_tips').remove();
			}
		}
	);
}

function mospace_showMorePost(pub, id, controller)
{
	if (pub == undefined )
		pub = false;
	if (id == undefined )
		id = false;
	var lastId = $P.str_replace('mospace_postItemBlock','',$('.mospace_postForm:last').attr('id'));
	$('#mospace_showmore_post').hide();
	$.getJSON(baseUrl+'mospace/'+controller+'/show-more-posts',
		{
			lastId	: lastId,
			pub		: pub,
			id		: id
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
                    if ($('.mospace_postForm:last').parent().hasClass('mospace_postItem'))
                        $('.mospace_postForm:last').parent().after(jsonObj.html);
                    else
                        $('.mospace_postForm:last').after(jsonObj.html);
					if ( jsonObj.show_more )
						$('#mospace_showmore_post').show();
				}
			}
		}
	);
}

function mospace_donationToggle(id,hide)
{
	$.getJSON(baseUrl+'mospace/your-donation-page/donation-toggle',
		{
			id: id,
			hide: hide
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					if (hide == 'true')
					{
						$('#mospace_donation'+id+' .mospace_hide').hide();
						$('#mospace_donation'+id+' .mospace_show').show();
					}
					else
					{
						$('#mospace_donation'+id+' .mospace_hide').show();
						$('#mospace_donation'+id+' .mospace_show').hide();
					}
				}
			}
		}
	);
}

function mospace_showNewsType(type)
{
	$('.mospace_newstype_selected').removeClass('mospace_newstype_selected').addClass('mospace_newstype');
	$('#mospace_newstype_'+type).removeClass('mospace_newstype').addClass('mospace_newstype_selected');
	$.getJSON(baseUrl+'mospace/index/show-minifeed',
		{
			type: type
		},
		mospace_minifeedResponseHandler
	);
}

function mospace_minifeedResponseHandler(jsonObj)
{
	if( jsonObj )
	{
		if ( jsonObj.result )
		{
			if ( jsonObj.clear )
				$('.mospace_newsItem').remove();
			$('#mospace_showmore_minifeed').before(jsonObj.html);
			if ( jsonObj.show_more )
				$('#mospace_showmore_minifeed').show();

			activateSamurai();
		}
	}
}

function activateSamurai()
{
	if ( typeof SamuraiCms != 'undefined' )
	{
		$( ".sm-js-cmsitem_editable" ).samurize();
	}
}

function mospace_showMoreNews()
{
	var lastMinifeedID = $P.str_replace('mospace_newsItem','',$('.mospace_newsItem:last').attr('id'));
	$('#mospace_showmore_minifeed').hide();
	$.getJSON(baseUrl+'mospace/index/show-minifeed',
		{
			last_minifeed_id: lastMinifeedID,
			type: newstype
		},
		mospace_minifeedResponseHandler
	);
}

function mospace_startATeam()
{
    $.watermark.hideAll();
    $('.mospace_error').hide();

    if( ($('#mospace_txtbxTeamName').val().length !== 0 ) ) {
	$.getJSON(baseUrl+'mospace/edit-details/start-a-team/teamName/' + $P.urlencode($('#mospace_txtbxTeamName').val()),
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					$('#mospace_teamName').text($('#mospace_txtbxTeamName').val());
					$( '#mospace_startATeamForm' ).remove();
					$( '#mospace_teamNameRow' ).show();
					location.reload(true);
					Samurai.loadText( 'mospace-edit-details-participation-team-captain','participation-value');
				}
				else
				{
					$( '#mospace_teamExists' ).show();
				}
			}
		}
	);
    } else {
        $( '#mospace_teamFieldEmpty' ).show();
    }
    $.watermark.showAll();
}

function mospace_joinATeam(refresh)
{
    var teamID = "";
    
    if ( $('#mospace_teamNameID').text()!="" ) {
        teamID = $('#mospace_teamNameID').text();
    } else {
        teamID = $('#mospace_txtbxTeamNameAC').val();
    }
    
    
    $.watermark.hideAll();
	$.postJSON(baseUrl+'mospace/edit-details/join-a-team/',
                {
                    teamID: teamID
		},
		function(jsonObj){
                    if( jsonObj )
                    {
                        if ( jsonObj.result )
                        {
                            $('#mospace_teamName').text($('#mospace_teamNameData').text());
                            $( '#mospace_joinATeamForm' ).remove();
                            $( '#mospace_teamNameRow' ).show();
                            Samurai.loadText( 'mospace-edit-details-participation-team-member','participation-value', function( result ) {
                                setTimeout( location.reload(true) );
                            });
                        } else {
                            // Problem, do nothing at this stage.
                        }
                    }
		}
	);
    $.watermark.showAll();
}

function mospace_editDetails(id)
{
	$('#'+id).hide();
	$('#'+id+'-data').hide();
	$('#'+id+'-form').show();
	return false;
}

function mospace_cancelForm(id)
{
	$('#'+id).show();
	$('#'+id+'-data').show();
	$('#'+id+'-form').hide();
	return false;
}

function mospace_postItemDeleteConfirm(id,controller)
{
	var postItem = $('#mospace_post' + id);
	if ( postItem.length <= 0 )
	{
		// This might be a new post item, in which case, it might have a different id prefix
		var postItem = $('#mospace_postItemBlock' + id);
	}

	if ( postItem.length > 0)
	{
		$.getJSON(baseUrl+'mospace/'+controller+'/delete-post',
			{
				id: id
			},
			function(jsonObj){
				if( jsonObj )
				{
					if ( jsonObj.result )
					{
						$(postItem).remove();
					}
				}
			}
		);
	}
}

/**
 * This will set the "hide" field on the given comment, and update links/classes
 * accordingly
 */
function mospace_postItemHideConfirm(hide, id,controller)
{
	var postItem = $('#mospace_post' + id);
	if ( postItem.length <= 0 )
	{
		// This might be a new post item, in which case, it might have a different id prefix
		var postItem = $('#mospace_postItemBlock' + id);
	}
    
	if ( postItem.length > 0)
	{
		$.getJSON(baseUrl+'mospace/'+controller+'/hide-post',
			{
				id: id,
                hide: hide
			},
			function(jsonObj){
				if( jsonObj )
				{
					if ( jsonObj.result )
					{
                        if( jsonObj.hide == "1" )
                        {
                            $("#mospace_postItemHide_"+id).hide();
                            $("#mospace_postItemShow_"+id).show();
                            if( !$("#mospace_postItemBlock"+id).hasClass("mospace_postItemBlockHidden") )
                                $("#mospace_postItemBlock"+id).addClass("mospace_postItemBlockHidden");                            
                        }
                        else
                        {
                            $("#mospace_postItemHide_"+id).show();
                            $("#mospace_postItemShow_"+id).hide();
                            if( $("#mospace_postItemBlock"+id).hasClass("mospace_postItemBlockHidden") )
                                $("#mospace_postItemBlock"+id).removeClass("mospace_postItemBlockHidden");                            
                        }
					}
				}
			}
		);
	}
}

function mospace_saveGalaForm()
{
	$.postJSON(baseUrl+'mospace/edit-details/save-gala',
		{
			gala: $('#edit-gala-form input:radio:checked').val(),
			galaLoc: $('#mospace_txtbxGalaLocation').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				var gala = $('#edit-gala-form input:radio:checked').val();
				if ( jsonObj.result )
				{
					if ( gala == 'yes' )
					{
						$('#mospace_galaLocData').show();
						$('#mospace_galaLocData').html($('.mospace_galaLocInfo:not(:hidden)').html());
						Samurai.loadText( 'mospace-edit-details-gala-party-attending','mospace_GalaLabel');
					}
					else
					{
						$('#mospace_galaLocData').hide();
						Samurai.loadText( 'mospace-edit-details-gala-party-not-attending','mospace_GalaLabel');
					}
					mospace_cancelForm('edit-gala');
				}
			}
		}
	);
}

/**
 * This will take the requested Personalised URL from the edit page and make an ajax
 * call to validate it.
 * If successful, the SAVE button should be shown allowing it to be changed permanently.
 * If not validated, the error message will be shown and the user can try again
 */
function mospace_checkPersonalUrlForm( id, uid )
{
    var elmId = id || 'mospace_txtbxPersonalUrl',
        requestedUrl = $('#'+elmId).val();

    if (requestedUrl.length == 0) {
        $('#'+elmId).addClass('error');
        return false;
    }

    $('#edit-personalurl-message-available').hide();
    $('#edit-personalurl-message-notavailable').hide();                        
    $('#edit-personalurl-message-notvalid').hide();                        
    $('#'+elmId).siblings('.form_element_errors').hide();

	$.getJSON(baseUrl+'mospace/edit-details/validate-personal-url',
		{
			personalurl: $('#' + elmId).val(),
            elm        : elmId
		},
		function(jsonObj){
			if( jsonObj )
			{
                var message = null,
                    targetElm = null;
                $('#edit-personalurl-form .error').hide();
				if ( jsonObj.result == 1 )
				{
                    // If all valid so far, swap the Check button for the Save button
                    // and update messaging
                    $('#edit-personalurl-button-save').show();
                    $('#edit-personalurl-button-validate').hide();
                    
                    targetElm = $('#edit-personalurl-message-available span').length > 0 ? $('#edit-personalurl-message-available span') : $('#edit-personalurl-message-available') ;
                    if (!samuraiTemplate.edit_personalurl_message_available) samuraiTemplate.edit_personalurl_message_available = targetElm.html();

                    message = samuraiTemplate.edit_personalurl_message_available.replace(/::personalurl::/g, $('#' + elmId).val());
                    targetElm.html(message);
                    $('#edit-personalurl-message-available').show();
				}
                else
                {
                    // If not valid, show the error message and ensure that the Check
                    // button is given instead of the Save button
                    mospace_invalidatePersonalUrlForm();
                    //hide any already displayed errors
                    $('#'+elmId).siblings('.form_element_errors').hide();

                    if ( jsonObj.result == 0 )  // url is invalid
                    {
                        targetElm = $('#edit-personalurl-message-notvalid span').length > 0 ? $('#edit-personalurl-message-notvalid span') : $('#edit-personalurl-message-notvalid');
                        if (!samuraiTemplate.edit_personalurl_message_notvalid) samuraiTemplate.edit_personalurl_message_notvalid = targetElm.html();
                        message = samuraiTemplate.edit_personalurl_message_notvalid.replace(/::personalurl::/g, $('#' + elmId).val());
                        targetElm.html(message);
                        $('#edit-personalurl-message-notvalid').show();
                        
                    } else if ( jsonObj.result == -1 )  // url is unavailable
                    {
                        targetElm = $('#edit-personalurl-message-notavailable span').length ? $('#edit-personalurl-message-notavailable span') : $('#edit-personalurl-message-notavailable');
                        if (!samuraiTemplate.edit_personalurl_message_notavailable) samuraiTemplate.edit_personalurl_message_notavailable = targetElm.html();
                        message = samuraiTemplate.edit_personalurl_message_notavailable.replace(/::personalurl::/g, $('#' + elmId).val());
                        targetElm.html(message);
                        $('#edit-personalurl-message-notavailable').show();                        
                    }


                }
			}
		}
	);
}

/**
 * This will attempt to save the requested Personalised URL against the current member
 * If successful, will update the standard Your Details section.
 * If not successful, error message should be shown and the user can try again
 */
function mospace_savePersonalUrlForm()
{
	$.postJSON(baseUrl+'mospace/edit-details/save-personal-url',
		{
			personalurl: $('#mospace_txtbxPersonalUrl').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
                    // Update the static version of the member's Personalised URL
                    // with the newly saved version
					var personalurl = $('#mospace_txtbxPersonalUrl').val();
					if ( $P.trim(personalurl) == 0 )
						Samurai.loadText( 'mospace-edit-details-na','edit-personalurl-data');
					else
						$('#edit-personalurl-data-url').text(personalurl);

					mospace_cancelForm('edit-personalurl');
				}
                else
                {
                    mospace_invalidatePersonalUrlForm();
                    mospace_displayFormErrors(jsonObj.errors);
                }
			}
		}
	);
}

/**
 * Change member profile privacy status
 */
function mospace_changePrivacy()
{
    if ($('input[name=privacy]:checked').val())
    {
        $.postJSON(baseUrl+'mospace/edit-details/change-privacy',
                    {
                            privacy: $('input[name=privacy]:checked').val()
                    },
                    function(jsonObj){
                            if( jsonObj )
                            {
                                    if ( jsonObj.result )
                                    {
                                        Samurai.loadText( 'member-profile-' + jsonObj.privacy, $('#edit-privacy-data .info') );
                                        mospace_cancelForm('edit-privacy');
                                    }
                            }
                    }
            );
    }
}

/**
 * Change member location privacy
 */
function mospace_changeLocationPrivacy()
{
    if ($('input[name=location-privacy]:checked').val())
    {
        $.postJSON(baseUrl+'mospace/edit-details/change-location-privacy',
                    {
                            privacy: $('input[name=location-privacy]:checked').val()
                    },
                    function(jsonObj){
                            if( jsonObj )
                            {
                                    if ( jsonObj.result )
                                    {
                                        Samurai.loadText( 'member-location-' + jsonObj.privacy, $('#edit-location-privacy-data .info') );
                                        mospace_cancelForm('edit-location-privacy');
                                    }
                            }
                    }
            );
    }
}

/**
 * Mospace Personal Url editing happens it two stages. First the member should check
 * that their new URL is valid, and only then save it.
 * This function will update the UI to reflect the first state (ie. ready for validation only)
 */
function mospace_invalidatePersonalUrlForm()
{
    $('#edit-personalurl-button-save').hide();
    $('#edit-personalurl-button-validate').show();
    $('#edit-personalurl-message-available').hide();
}

/**
 * If the user hits 'cancel' we need to put the UI back to invalidated mode and then do the
 * usual mospace cancel (reset) call
 */
function mospace_cancelPersonalUrlForm()
{
    mospace_invalidatePersonalUrlForm();

    mospace_cancelForm('edit-personalurl');
}

function mospace_savePhoneForm()
{
	$.postJSON(baseUrl+'mospace/edit-details/save-phone',
		{
			phone: $('#mospace_txtbxPhone').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					var phone = $('#mospace_txtbxPhone').val();
					if ( $P.trim(phone) == 0 )
						Samurai.loadText( 'mospace-edit-details-na','edit-phone-data');
					else
						$('#edit-phone-data').text(phone);
					mospace_cancelForm('edit-phone');
				}
                else
                {
                    mospace_displayFormErrors(jsonObj.errors);
                }
			}
		}
	);
}

function mospace_displayFormErrors(errors)
{
    for (var i in errors)
    {
        $('#'+i).parent().find('.mospace_error').remove();
        $('#'+i).after('<div class="mospace_error" style="display:block">'+errors[i]+'</div>');
    }
}

function mospace_createPostFormResponseHandler(response, controller, entity_id)
{
	if ( response.id )
		id = response.id;
	else
		id = '';
	$('#mospace_postAction'+id+', #mospace_videoError'+id+', #mospace_postError'+id).hide();
    $('#mospace_postForm, #mospace_postForm'+id).show();
	//console.log('#mospace_postAction'+id+', #mospace_videoError'+id+', #mospace_postError'+id);
	if ( response.result )
	{
		if ( $('#mospace_txtbxPostContent'+id).length == 0)
		{
			mospace_removeAttachPostImage('',controller,entity_id);
			mospace_cancelForm('edit-video');
			$('#mospace_txtbxPostContent, #mospace_txtbxVideo').val('');
		}
		else
		{
			mospace_removeAttachPostImage(id, controller,entity_id);
			mospace_cancelForm('edit-video'+id);
		}

        $('#cancelPostForm').hide();

		if (response.newItem)
		{
			$('#mospace_postAction, #mospace_videoError, #mospace_postError').hide();
			//display the new post
			$.getJSON(baseUrl+'mospace/'+controller+'/load-post',
				{
					id			: id,
					entity_id	: entity_id,
					rand		: true
				},
				function(jsonObj){
					if( jsonObj ){
						if ( jsonObj.result )
						{
							$('#mospace_post').prepend(jsonObj.html);
							init_postImageUpload(id,controller,entity_id);
						}
					}
				}
			);
		}
		else
		{
			//replace the existing post content
			$.getJSON(baseUrl+'mospace/'+controller+'/load-post',
				{
					id			: id,
					entity_id	: entity_id,
					rand		: true
				},
				function(jsonObj){
					if( jsonObj ){
						if ( jsonObj.result )
						{
							$('#mospace_postItemBlock'+id).replaceWith(jsonObj.html);
							init_postImageUpload(id,controller,entity_id);
						}
					}
				}
			);
		}
	}
	else
	{
		switch (response.error)
		{
			case 'youtube':
				$('#mospace_videoError'+id).show();
				Samurai.loadText( 'mospace-invalid-youtube','mospace_videoError'+id);
				break;
			case 'incomplete':
				$('#mospace_postError'+id).show();
				Samurai.loadText( 'mospace-updates-incomplete','mospace_postError'+id);
				break;
            case 'file-too-large':
				$('#mospace_postError'+id).show();
                mospace_removeAttachPostImage(id,controller,entity_id);
				Samurai.loadText( 'mospace-updates-file-too-large','mospace_postError'+id);
				break;
		}
	}
}

function mospace_createPostForm(elm, id, controller, entity_id)
{
    if($(elm).hasClass('in-progress')) return false;

    $(elm).addClass('in-progress');
    $.watermark.hideAll();
	if ( id == undefined || id == null)
		id = '';

	if ( ajaxPostImage['postPhotoReady'+id] )
	{
		ajaxPostImage['postPhoto'+id].setData({
			content		: $('#mospace_txtbxPostContent'+id).val(),
			id			: id,
			entity_id	: entity_id
		});
		ajaxPostImage['postPhoto'+id].submit();
        
        // Not sure where to put an "after submission" check, so re-allowing
        // the submit button here
        $(elm).removeClass('in-progress');
	}
	else
	{
		var video,deleteImage = false;
		if ($( '#mospace_postAttachment'+id).css('display') == 'none' )
			deleteImage = true;

		if ($( '#edit-video'+id+'-form').css('display') == 'none' )
			video = '';
		else
			video = $('#mospace_txtbxVideo'+id).val();

        $.getJSON(baseUrl+'mospace/'+controller+'/create-post',
            {
                id			: id,
                video		: video,
                entity_id	: entity_id,
                deleteImage	: deleteImage,
                content		: $('#mospace_txtbxPostContent'+id).val()
            },
            function(response){
                $(elm).removeClass('in-progress');
                mospace_createPostFormResponseHandler(response, controller, entity_id);
            }
        );
	}

    $.watermark.showAll();
}

function mospace_createCommentForm(id, type)
{
    $.watermark.hideAll();
	if (type == 'mospace')
	{
		view1 = 'index';
		view2 = 'your-donation-page';
	}
	else
	{
		view1 = 'network';
		view2 = 'network';
	}

	var content = $('#mospace_txtbxCommentContent').val();
	$('#mospace_txtbxCommentContent').val('');
	$('#submit').before(loadingImage);
	$('#submit').css('visibility','hidden');
	$.getJSON(baseUrl+'mospace/'+view1+'/create-comment',
		{
			content: content,
			id: id
		},
		function(jsonObj){
			if( jsonObj )
			{
                mospace_createCommentResponse( jsonObj, type )
			}
			//else
			//	window.location.reload();
		}
	);
    $.watermark.showAll();
}

function mospace_createCommentResponse( jsonObj, type )
{

	if ( jsonObj.result )
	{
		if (type == 'network')
			controller = type;
		else
			controller = 'your-donation-page';

//		console.log(jsonObj.id);
		//display the new comment
        $('#mospace_commentError:not(hidden)').hide();
		$.getJSON(baseUrl+'mospace/'+controller+'/load-post',
			{
				id: jsonObj.id,
				entity_id: $('#entity_id').val(),
				pub: true
			},
			function(jsonObj){
				if( jsonObj ){
					if ( jsonObj.result )
						$('#mospace_post').prepend(jsonObj.html);
					else
					{
						switch (jsonObj.error)
						{
							case 'incomplete':
								$('#form_element_comment .form_element_errors').show();
								Samurai.loadText( 'mospace-comment-incomplete','mospace_commentError');
								break;
						}
					}
				}
				$('#submit').css('visibility','visible');
				$('#form_element_submit img, #mospace_commentForm img').remove();
			}
		);
	}
	else {
        //there is not form element wraper around textarea and submit button
        //showFormErrors(jsonObj.errors, 'mospace_commentForm');
        Samurai.loadText( 'mospace-comment-error','mospace_commentError');
        $('#mospace_commentError:not(visible)').show();
    	$('#submit').css('visibility','visible');
        $('#form_element_submit img, #mospace_commentForm img').remove();
    }

	//else
	//	window.location.reload();

	//replace token
	$('#token_formcomment').val(jsonObj.token);

	unhideSubmit('formcomment', 'submit');
}

function showFormErrors(errors, formId)
{
	for( var i in errors)
	{
		e = $('#'+formId + ' #form_element_'+i+' .form_element_errors');
		if ($(e).length > 0)
		{
			html = '';
			for ( var j in errors[i])
				html += errors[i][j] + '<br />';
			e.html(html);
		}
	}
}

function clearFormErrors(formId)
{
	$('#'+formId + ' .form_element_errors').text('');
}

function mospace_createNetworkCommentForm()
{
	mospace_createCommentForm($('#entity_id').val() , 'donation');
}

function mospace_createMospaceCommentForm(id)
{
	mospace_createCommentForm(id , 'mospace');
}

function init_postImageUpload(id, controller, entity_id)
{
	//new post form
	ajaxPostImage['postPhotoReady'+id] = false;
	ajaxPostImage['postPhoto'+id] = new AjaxUpload($('#mospace_postPhoto'+id),{
		action		: baseUrl+'mospace/'+controller+'/create-post/',
		name		: 'image',
		autoSubmit	: false,
		data		:{
			id			: id,
			deleteImage	: false,
			entity_id	: entity_id
		},
		responseType: 'json',
		onChange: function(file,ext){
			if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
			{
				$('#mospace_postError'+id).show();
				Samurai.loadText( 'mospace-team-photo-invalid-ext','mospace_postError'+id);
				ajaxPostImage['postPhotoReady'+id] = false;
				return false;
			}
			else
			{
				ajaxPostImage['postPhotoReady'+id] = true;
				$('#mospace_postError'+id).hide();
				$('#edit-video'+id).hide();
				$('#edit-video'+id+'-form').hide();
				$('#mospace_postAttachment'+id).show();
				$('#mospace_postAttachmentFile'+id).text(file);
			}
		},
		onSubmit : function(file, ext){
			this.disable();
			$('#mospace_postAction'+id).show();
			$('#mospace_postAttachment'+id+',#mospace_postForm'+id).hide();
			$('#mospace_postAction'+id).html(loadingImage+loadingText);
		},
		onComplete: function(file, response){
			mospace_createPostFormResponseHandler(response, controller, entity_id);
			this.enable();
		}
	});

	if (id == '')
	{
		//create ajax upload object for existing post items
		$('.mospace_postUpdates .mospace_postItemBlock').each(function(e){
			var id = $P.str_replace('mospace_postItemBlock','',$(this).attr('id'));
			ajaxPostImage['postPhotoReady'+id] = false;
			ajaxPostImage['postPhoto'+id] = new AjaxUpload($('#mospace_postPhoto'+id),{
				action: baseUrl+'mospace/'+controller+'/create-post/',
				name: 'image',
				data:{
					id			: id,
					deleteImage	: false,
					entity_id	: entity_id
				},
				autoSubmit: false,
				responseType: 'json',
				onChange: function(file,ext){
					if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
					{
						$('#mospace_postError'+id).show();
						Samurai.loadText( 'mospace-team-photo-invalid-ext','mospace_postError'+id);
						ajaxPostImage['postPhotoReady'+id] = false;
						return false;
					}
					else
					{
						ajaxPostImage['postPhotoReady'+id] = true;
						$('#mospace_postError'+id).hide();
						$('#edit-video'+id).hide();
						$('#edit-video'+id+'-form').hide();
						$('#mospace_postAttachment'+id).show();
						$('#mospace_postAttachmentFile'+id).text(file);
					}
				},
				onSubmit : function(file, ext){
					this.disable();
					$('#mospace_postAction'+id).show();
					$('#mospace_postAttachment'+id+',#mospace_postForm'+id).hide();
					$( '#mospace_postAction'+id).html(loadingImage+loadingText);
				},
				onComplete: function(file, response){
					mospace_createPostFormResponseHandler(response, controller, entity_id);
					this.enable();
				}
			});
		});
	}
}

function mospace_removeAttachPostImage(id,controller,entity_id)
{
	if ( $('#mospace_postItemBlock'+id).length == 0 )
		id = '';
	delete ajaxPostImage['postPhoto'+id];
	init_postImageUpload(id,controller,entity_id);
	$('#mospace_postAttachment'+id).hide();
	$('#edit-video'+id).show();
}

function mospace_saveMotivationForm()
{
	$.getJSON(baseUrl+'mospace/your-donation-page/save-motivation',
		{
			motivation: $('#mospace_txtbxMotivation').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					if ($P.strlen($('#mospace_txtbxMotivation').val())>0)
						$('#edit-motivation-data').text('"'+$('#mospace_txtbxMotivation').val()+'"');
					else
					{
						Samurai.loadText( 'mospace-default-motivation','edit-motivation-data-wq');
					}
					mospace_cancelForm('edit-motivation');
				}
			}
		}
	);
}

function mospace_saveNetworkDescriptionForm(id)
{
	$.getJSON(baseUrl+'mospace/network/save-description',
	{
		description : $('#mospace_txtbxNetworkDescription').val(),
		networkId : id
	},
	function(jsonObj){
		if( jsonObj )
		{
			if ( jsonObj.result )
			{
				if ($P.strlen($('#mospace_txtbxNetworkDescription').val())>0)
					$('#edit-network-description-data').text('"'+$('#mospace_txtbxNetworkDescription').val()+'"');
				else
				{
					Samurai.loadText( 'mospace-default-network-description','edit-network-description-data-wq');
				}
				mospace_cancelForm('edit-network-description');
			}
		}
	}
);
}

function mospace_saveTipsOption()
{
	$('#mospace_YourDonationTips').hide();
	$.getJSON(baseUrl+'mospace/your-donation-page/save-tips',
		{
			tips: 0
		}
	);
}

function mospace_saveLocationForm()
{
    $('#mospace_locationError').hide();
	var data = {
		street1: $('#mospace_txtbxLocStreet1').val(),
		street2: $('#mospace_txtbxLocStreet2').val(),
		suburb: $('#mospace_txtbxLocSuburb').val(),
		state: $('#mospace_locState').val(),
		postcode: $('#mospace_txtbxLocPostcode').val(),
        locationPrivacy: $('input[name=location-privacy]:checked').val()
	}
	if ( $('#mospace_txtbxLocCountry').length > 0 )
		data = $.extend( data, {country_code: $('#mospace_txtbxLocCountry').val()});

    var error = false;
    // validation
    // NOTE: Bug was reported that only postcode should be mandatory, and even then only
    // if shown. See Jira ticket MOV2120-766
//    if ($('#mospace_txtbxLocStreet1').val() == ''){
//        error = true;
//        $('#mospace_txtbxLocStreet1').addClass('error');
//        $('#mospace_txtbxLocStreet1').parent().find('.mospace-error').remove();
//        $('#mospace_txtbxLocStreet1').parent().append('<div class="form_element_errors"><ul><li>Please fill in address1</li></ul></div>');
//    }
//
//    if ($('#mospace_txtbxLocSuburb').val() == ''){
//        error = true;
//        $('#mospace_txtbxLocSuburb').addClass('error');
//        $('#mospace_txtbxLocSuburb').parent().find('.mospace-error').remove();
//        $('#mospace_txtbxLocSuburb').parent().append('<div class="form_element_errors"><ul><li>Please enter city</li></ul></div>');
//    }
//
//    if ($('#mospace_locState').val() == 0){
//        error = true;
//        $('#mospace_locState').addClass('error');
//        $('#mospace_locState').parent().find('.mospace-error').remove();
//        $('#mospace_locState').parent().append('<div class="form_element_errors"><ul><li>Please select state</li></ul></div>');
//    }
    if ($('#mospace_txtbxLocPostcode') && $('#mospace_txtbxLocPostcode').val() == '' && country != 'nz'){
        error = true;
        $('#mospace_txtbxLocPostcode').addClass('error');
        $('#mospace_txtbxLocPostcode').parent().find('.mospace-error').remove();                    
        $('#mospace_txtbxLocPostcode').parent().append('<div class="form_element_errors"><ul><li id="mospace-postcode-error"></li></ul></div>');
        Samurai.loadText( 'mospace-error-postcode-error','mospace-postcode-error');
    }
    
    if ( error ) return false;


	$.getJSON(baseUrl+'mospace/edit-details/save-location',
		data,
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
                                    $('#edit-location-data .address').html(jsonObj.address);
                                    Samurai.loadText( 'member-location-' + jsonObj.privacy, $('#edit-location-privacy .info') );
                                    if (jsonObj.updateDelivery)
                                            $('#edit-delivery-data').html(jsonObj.address);
                                    mospace_cancelForm('edit-location');
				}
				else
				{
					switch(jsonObj.error)
					{
						case 'incomplete':
							samuraiID = 'mospace-edit-details-location-incomplete-err';
							break;
						case 'invalidLocation':
							samuraiID = 'mospace-edit-details-location-invalid-err';
							break;
					}
					Samurai.loadText( samuraiID,'mospace_locationError');
                    $('#mospace_locationError').show();
				}
			}
		}
	);
}

function mospace_saveDeliveryForm()
{
    $('#mospace_deliveryError').hide();
	var sameAsAbove;
	if ( $('#mospace_chkbxSameAsLoc:checked').length > 0 )
		sameAsAbove = true;
	else
		sameAsAbove = false;

	var data = {
		street1: $('#mospace_txtbxDelStreet1').val(),
		street2: $('#mospace_txtbxDelStreet2').val(),
		suburb: $('#mospace_txtbxDelSuburb').val(),
		state: $('#mospace_delState').val(),
		postcode: $('#mospace_txtbxDelPostcode').val(),
		sameAsAbove: sameAsAbove
	}
	if ( $('#mospace_txtbxDelCountry').length > 0 )
		data = $.extend( data, {country_code: $('#mospace_txtbxDelCountry').val()});

    var error = false;
    // validation
    if ($('#mospace_txtbxDelStreet1').val() == ''){
        error = true;
        $('#mospace_txtbxDelStreet1').addClass('error');
        $('#mospace_txtbxDelStreet1').parent().find('.mospace-error').remove();
        $('#mospace_txtbxDelStreet1').parent().append('<div class="form_element_errors"><ul><li>Please fill in address1</li></ul></div>');
    }

    if ($('#mospace_txtbxDelSuburb').val() == ''){
        error = true;
        $('#mospace_txtbxDelSuburb').addClass('error');
        $('#mospace_txtbxDelSuburb').parent().find('.mospace-error').remove();
        $('#mospace_txtbxDelSuburb').parent().append('<div class="form_element_errors"><ul><li>Please enter city</li></ul></div>');
    }

    if ($('#mospace_delState').val() == 0 && country != 'nz'){
        error = true;
        $('#mospace_delState').addClass('error');
        $('#mospace_delState').parent().find('.mospace-error').remove();
        $('#mospace_delState').parent().append('<div class="form_element_errors"><ul><li>Please select state</li></ul></div>');
    }
    
    if ( !sameAsAbove && error ) return false;

	$.getJSON(baseUrl+'mospace/edit-details/save-delivery',
		data,
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					$('#edit-delivery-data').html(jsonObj.address);
					$('#mospace_confirmDelivery').show();
                    
					mospace_cancelForm('edit-delivery');
				}
				else
				{
					switch(jsonObj.error)
					{
						case 'incomplete':
							samuraiID = 'mospace-edit-details-delivery-incomplete-err';
							break;
						case 'invalidLocation':
							samuraiID = 'mospace-edit-details-delivery-invalid-err';
							break;
					}
					Samurai.loadText( samuraiID,'mospace_deliveryError');
                    $('#mospace_deliveryError').show();
				}
			}
		}
	);
}

function validateUrl(url) {
    var regex = new RegExp("^(http:\/\/www.|https:\/\/www.|ftp:\/\/www.|www.){1}[0-9A-Za-z\.\-]*\.[0-9A-Za-z\.\-]*$");
    if (regex.test(url))
    {
       return true;
    } else {
       return false;
    }
}

function validateEmail( email ) {
	var regex = new RegExp("^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$");
	if (regex.test(email)){
		return true;
	} else {
		return false;
	}
}

function mospace_saveCompanyForm()
{
    var scope = $('#edit-company-form');
    
    $('.form_element_errors', scope).hide();
    
    if (!$('input:radio[name=occupation]', scope).is(':checked')){
        $('.occupation-wrapper', scope).find('.form_element_errors').show();
        return false;
    } else if ($('input:radio[name=occupation]:checked', scope).val() == 'professional' || $('input:radio[name=occupation]:checked', scope).val() == 'student' ) {
        if ($('#mospace_txtbxCompany', scope).val().length == 0) {
            $('#mospace_txtbxCompany', scope).addClass('error');
            $('.occupation-input').siblings('.form_element_errors').show();
            return false;
        }
    }
    
	data = {
        occupation: $('input:radio[name=occupation]:checked').val(),
        company: $('#mospace_txtbxCompany').val()
    };

	$.postJSON(baseUrl+'mospace/edit-details/save-company',
		data,
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					var occupation = $('input[name=occupation]:checked').val(),
                        company = $('#mospace_txtbxCompany').val().replace(/(<([^>]+)>)/ig,""),
                        url = $('#mospace_txtbxCompanyURL').val().replace(/(<([^>]+)>)/ig,"");

                    occupation = occupation.charAt(0).toUpperCase() + occupation.slice(1);

					if ( $P.trim(occupation) == 0 )
						Samurai.loadText( 'mospace-edit-details-na','edit-company-data');
					else
					{
						var company_data = occupation + '<br />' + company;
						if ( $P.trim(url) != 0 )
							url = '<br />'+ url;
						if ( $('#mospace_txtbxCompanyURL').length > 0 && $('#mospace_txtbxCompanyURL').parent().css('display') != 'none' )
							company_data += url;
						$('#edit-company-data').html(company_data);
					}
					mospace_cancelForm('edit-company');
                    $('#mospace_txtbxCompany', scope).removeClass('error');
				}
			}
		}
	);
}

function mospace_saveLocaleForm()
{
	data = {locale: $('#mospace_txtbxLocale').val()};

	$.getJSON(baseUrl+'mospace/edit-details/save-locale',
		data,
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					var locale = $('#mospace_txtbxLocale').val();
					$('#edit-locale-data').html(jsonObj.language);
					mospace_cancelForm('edit-locale');

                    var href = baseUrl;
//                    if ($P.substr($('#mospace_txtbxLocale').val(),0,2) != 'en')
//                        href += $P.substr($('#mospace_txtbxLocale').val(),0,2) + '/';
                    href += 'mospace/edit-details'

                    if( jsonObj.redirect )
                        location.href = jsonObj.redirect;
                    else
                        location.href = href;
				}
			}
		}
	);
}

function mospace_saveSpokespersonForm()
{
	$.getJSON(baseUrl+'mospace/edit-details/save-spokesperson',
		{
			spokesperson: $('#mospace_chkbxSpokesperson:checked').length,
			story: $('#spokesperson_story').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					var spokesperson = $('#mospace_chkbxSpokesperson:checked').length;
					if ( spokesperson > 0 )
						Samurai.loadText( 'mospace-edit-details-media-spokesperson-opted-in','edit-spokesperson-data');
					else
						Samurai.loadText( 'mospace-edit-details-media-spokesperson-opted-out','edit-spokesperson-data');
                    $('#mospace-edit-details-error').hide();
					mospace_cancelForm('edit-spokesperson');
				}
                else
                {
                    Samurai.loadText( 'mospace-edit-details-media-spokesperson-error','mospace-edit-details-error');
                    $('#mospace-edit-details-error').show();
                }
			}
		}
	);
}


//	initAjaxImageUpload('#mospace_changeTeamProfilePic',
//						'#mospace_teamProfilePic',
//						'#mospace_teamProfilePicError',
//						'#mospace_teamProfilePicLoader',
//						'mospace/team/update-photo/',
//						{});
//
//function initAjaxImageUpload(editContainer, successContainer, errorContainer, loaderContainer, url, data, redirect)

$(function(){
    var url = 'mospace/team/update-photo/';
    var resultImageId = '#mospace_teamProfilePic';
    var linkContainer = '#mospace_changeTeamProfilePic';
    var errorContainer = '#mospace_teamProfilePicError';
    var loaderContainer = "#mospace_teamProfilePicLoader";
    var extraData = {};
    initProfilePicUpload( linkContainer, resultImageId, errorContainer, loaderContainer, url, extraData );
    
    url = 'mospace/network/upload-profile-pic/';
    resultImageId = '#mospace_networkProfilePic';
    linkContainer = '#mospace_changeNetworkProfilePic';
    errorContainer = '#mospace_networProfilePicError';
    loaderContainer = "#mospace_networkProfilePicLoader";
    if ( typeof networkId != "undefined" )
        extraData = { 'networkId' : networkId };
    
    initProfilePicUpload( linkContainer, resultImageId, errorContainer, loaderContainer, url, extraData );
});

function initProfilePicUpload( linkContainer, resultImageId, errorContainer, loaderContainer, url, extraData )
{   
    if ( $(linkContainer).length ==0 ) return;
    
    new AjaxUpload($(linkContainer),{
        action: baseUrl+url,
        name: 'image',
        data: extraData,
        autoSubmit: true,
        responseType: 'json',
        onSubmit : function(file, ext){
            if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
            {
                $(errorContainer+' div.invalidExt').show();
                $(errorContainer).show();
                return false;
            }
            else
            {
                this.disable();
                $(errorContainer).hide();
                $(loaderContainer).html(loadingImage);
                $(loaderContainer).show();
            }
        },
        onComplete: function(file, response){
            $(loaderContainer).hide();
            if (response.result )
            {
                if( $(resultImageId).length )
                {
                    $(resultImageId).show();
   					$(resultImageId).attr('src',baseUrl+$P.urldecode(response.url)+'?timestamp='+$P.time());
                }
            }
            else
            {
                $(errorContainer+' div.invalidSize').show();
                $(errorContainer).show();
            }
            this.enable();
        }
    });
}

function mospace_saveTeamName()
{
    if (!$('#mospace_txtName').length) return;
    
    var name = $('#mospace_txtName').val();

    $.postJSON(baseUrl+'mospace/edit-details/save-team-details',
		{
                    name : name
		},
		function(jsonObj){
                    if( jsonObj )
                    {
                        if ( jsonObj.result )
                        {
                            mospace_cancelForm('edit-teamName');

                            // Clear existing errors
                            $('.mospace_error').html('');

                            $('#edit-teamDetails-name').html( name );
                            $('.js_team-title').html( name );
                            $('#mospace_teamName').html( name );
                        }
                        else
                        {
                            mospace_displayFormErrors(jsonObj.errors);
                        }
                    }
		});
}

function mospace_saveTeamStatus()
{
    var status = 1;

    if( $('#mospace_chkTeamPublic').is(':checked') )
        status = 0;

	$.postJSON(baseUrl+'mospace/edit-details/save-teamstatus',
		{
			teamstatus: status
		},
		function(jsonObj){
			if( jsonObj )
			{
                            if ( jsonObj.result )
                            {
                                var teamstatus = jsonObj.result;
                                if ( teamstatus == 1 )
                                {
                                    $('#mospace_teamStatus').html('PRIVATE');
                                }
                                else if (teamstatus == 0 )
                                {
                                    $('#mospace_teamStatus').html('PUBLIC');
                                }
                                mospace_cancelForm('edit-team');
                            }
                        }
		});
}

/**
 * This is used to send an ajax request to update Team Name & Private Status
 *
 */
function mospace_saveTeamDetails()
{
    var name = $('#mospace_txtName').val() || null;
    var isprivate = 1;

    if( $('#mospace_chkTeamPublic').is(':checked') )
        isprivate = 0;

	$.getJSON(baseUrl+'mospace/edit-details/save-team-details',
		{
                    name : name,
                    isprivate : isprivate
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					mospace_cancelForm('edit-team');
					mospace_cancelForm('edit-teamDetails');

                    if( isprivate )
                    {
                        $('#team-status-private').show();
                        $('#team-status-public').hide();
                    }
                    else
                    {
                        $('#team-status-private').hide();
                        $('#team-status-public').show();
                    }

                    // Clear existing errors
                    $('.mospace_error').html('');

                    $('#edit-teamDetails-name').html( name );
				}
                else
                {
                    mospace_displayFormErrors(jsonObj.errors);
                    
                    // And manually populate a given error div if exists (ie. mospace->team)
                    $('#mospace_teamDetailsError').show();
                    for( var i in jsonObj.errors )
                        Samurai.loadText( jsonObj.errors[i],'mospace_teamDetailsError');
                }
			}
		});
}

function mospace_saveYourDetails()
{
    var firstname = $('#mospace_txtFname').val();
    var lastname = $('#mospace_txtLname').val();
    var email = $('#mospace_txtEmail').val();

    /*var alphanum = new RegExp("^([a-zA-Z_-]+)$");
    var error = false;

    if (!alphanum.test(firstname)){
    	$('#mospace_txtFname').css({'border': 'solid 1px #f00'});
    	error = true;
    } else { $('#mospace_txtFname').css({'border': 'solid 1px #e0dfe3'}); }

    if (!alphanum.test(lastname)) {
    	$('#mospace_txtLname').css({'border': 'solid 1px #f00'});
    	error = true;
    } else { $('#mospace_txtLname').css({'border': 'solid 1px #e0dfe3'}); }
    if (!validateEmail(email)) {
    	$('#mospace_txtEmail').css({'border': 'solid 1px #f00'});
    	error = true;
    } else { $('#mospace_txtEmail').css({'border': 'solid 1px #e0dfe3'}); }

    if (error)
    	return false;*/

	$.postJSON(baseUrl+'mospace/edit-details/save-your-details',
		{
			fname: firstname,
			lname: lastname,
			email: email
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
                    $('#edit-yourDetails-firstname').text(firstname);
                    $('#edit-yourDetails-lastname').text(lastname);
                    $('#edit-yourDetails-email').text(email);
					mospace_cancelForm('edit-yourDetails');
                    $('.edit-details-about .mospace_error').remove();
                    mospace_emailBackup = email;
				}
                else
                {
                    mospace_displayFormErrors(jsonObj.errors);
                }
			}
		});
}

function mospace_cancelSaveDetails()
{
	// Remove our errors
	$('.edit-details-about .mospace_error').remove();
	// Set our email address BACK to the
    if( $('#mospace_txtEmail').length > 0 )
    	$('#mospace_txtEmail').val(mospace_emailBackup);
	mospace_cancelForm('edit-yourDetails');
	mospace_cancelForm('edit-teamDetails');
	return false;
}

function mospace_saveContactOptions()
{
	$.getJSON(baseUrl+'mospace/edit-details/save-contact',
			{
				donation: $('#donation_notification:checked').length
			},
			function(jsonObj){
				if( jsonObj )
				{
					if ( jsonObj.result )
					{
						var donationNotification = $('#donation_notification:checked').length;
						if ( donationNotification > 0 )
							Samurai.loadText( 'mospace-edit-details-donation-email-opted-in','edit-contact-options-data');
						else
							Samurai.loadText( 'mospace-edit-details-donation-email-opted-out','edit-contact-options-data');
						mospace_cancelForm('edit-contact-options');
					}
				}
			}
		);


}

function mospace_savePasswordForm()
{
	$( '#mospace_passwordError' ).css( 'display', 'none' );
	if ( $('#mospace_txtbxPassword').val() != $( '#mospace_txtbxConfirmPassword').val())
	{
		Samurai.loadText( 'mospace-edit-details-password-error-not-matched','mospace_passwordError');
		$( '#mospace_passwordError' ).css( 'display', 'block' );
        $('#mospace_txtbxPassword').val('');
        $('#mospace_txtbxConfirmPassword').val('');
	}
	else
	{
		$.postJSON(baseUrl+'mospace/edit-details/save-password',
			{
				password: $('#mospace_txtbxPassword').val()
			},
			function(jsonObj){
				if( jsonObj )
				{
					if ( jsonObj.result )
					{
                        Samurai.loadText( 'mospace-edit-details-password-saved','edit-password-data', function() {
                            mospace_cancelForm('edit-password');
                            $('#mospace_txtbxPassword').val('');
                            $('#mospace_txtbxConfirmPassword').val('');
                            window.location = baseUrl +'mospace/edit-details/';
                        });						
					}
					else
					{
                		$( '#mospace_passwordError' ).css( 'display', 'block' );
						$('#mospace_txtbxPassword').val('');
						$('#mospace_txtbxConfirmPassword').val('');
						switch(jsonObj.error)
						{
							case 'length':
								samuraiID = 'mospace-edit-details-password-error-length';
								break;
							case 'alnum':
								samuraiID = 'mospace-edit-details-password-error-alnum';
								break;
						}
						Samurai.loadText( samuraiID,'mospace_passwordError');
					}
				}
			}
		);
	}
}

function mospace_updateGalaLocInfo()
{
	$('.mospace_galaLocInfo').hide();
	$('#mospace_galaLocInfo'+$('#mospace_txtbxGalaLocation').val()).show();
}

function mospace_hideTeamInputAC()
{
    $('#mospace_joinATeamButton,#mospace_joinATeamButtonOr').hide();
	$('#mospace_teamNameData').parent().hide();
	$('#mospace_teamNameACDiv').show()
    $('#mospace_txtbxTeamNameAC').val("");
    $('#mospace_txtbxTeamNameAC').focus();
}

function mospace_toggleSpokespersonDetails()
{
	if ( $('#mospace_chkbxSpokesperson:checked').length > 0 )
	{
		//checked -> unchecked
		$('#mospace_spokespersonDetails').show();
	}
	else
		$('#mospace_spokespersonDetails').hide();
}

function mospace_makePrivate()
{
	var ids = mospace_getCheckedBoxes('.donation_row :checked','donation_');
	$.getJSON(baseUrl+'mospace/donations/make-private',
		{
			ids: ids
		},function(jsonObj){
			if(jsonObj)
			{
				$('.donation_row :checked').attr('checked',false);
				var exploded_ids = $P.explode(',',ids);
				for( var i in exploded_ids )
					$('#private_'+exploded_ids[i]).html('*');
			}
		}
	);
}

function mospace_makePublic()
{
	var ids = mospace_getCheckedBoxes('.donation_row :checked','donation_');
	$.getJSON(baseUrl+'mospace/donations/make-public',
		{
			ids: ids
		},function(jsonObj){
			if(jsonObj)
			{
				$('.donation_row :checked').attr('checked',false);
				var exploded_ids = $P.explode(',',ids);
				for( var i in exploded_ids )
					$('#private_'+exploded_ids[i]).html('');
			}
		}
	);
}

function mospace_getCheckedBoxes(selector,id_prefix)
{
	var string='';
	$(selector).each(function(){
		string += $P.str_replace(id_prefix,'',$(this).attr('id')) + ',';
	});
	return $P.substr(string,0,-1);
}

function mospace_confirmTicket()
{
	$('#mospace_submit').hide();
	$('#mospace_pleaseWait').css('display','inline-block');
	$.getJSON(baseUrl+'mospace/events-and-ticketing/confirm-ticket',
		{
			id: $('#mospace_selLocation').val()
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
					window.location = jsonObj.url;
			}
		}
	);
}

function mospace_claimPrize()
{
	$('#mospace_submit').hide();
	$('#mospace_pleaseWait').css('display','inline-block');
	$.getJSON(baseUrl+'mospace/prizes-and-rewards/claim-prize',
		{nameOnCertificate: $('#mospace_txtbxNameOnCertificate').val()},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
					window.location.reload(true);
				else
				{
					$('#mospace_submit').css('display','inline-block');
					$('#mospace_pleaseWait').hide();
					switch(jsonObj.error)
					{
						case 'incomplete':
							samuraiID = 'mospace-claim-prize-incomplete-err';
							break;
						case 'claimed':
							samuraiID = 'mospace-claim-prize-claimed-invalid-err';
							break;
					}
					Samurai.loadText( samuraiID,'mospace_prizeError');
				}
			}
		}
	);
}

function mospace_cancelPrizeDeliveryForm()
{
	if ($('#edit-delivery-data .sm-js-cmsitem_editable').length <= 0)
		$('#mospace_confirmDelivery').show();
	mospace_cancelForm('edit-delivery');
}

function mospace_rating(value,link)
{
	var string = $P.explode('_',$(link).attr('ref'));
	var id = string[1];
	var rating = string[0];
	$('#mospace_myrate_'+id).text(rating);
	$.getJSON(baseUrl+'mospace/members/rate-mo',
		{
			id:id,
			rating:rating
		},
		function(response)
		{
			e = $('#mospace_moBlock_'+response.id + ' .ave-rating input');
//			e.rating('enable');
			e.rating('select',response.rating*2+"_s");
//			e.rating('disable');
			//$('#aveRateMe_'+response.id).text(response.rating);
			toggleRatingBlock(response.id);
			$('#rateMe_'+response.id).hide();
            $('#ratingCount_'+response.id).text(response.ratingCount);
			$('#rated_'+response.id).show();
		}
	);
}

function mospace_saveMoPartyRego(step)
{
	var data;
	switch(step)
	{
		case 1:
			data = {
				street1: $('#address1').val(),
				street2: $('#address2').val(),
				contact: $('#phone_number').val(),
				step: step
			};
			if ( $('#mospace_delLocationInput').length > 0 )
			{
				data = $.extend( data, {location: $('#mospace_delLocationID').text()});
			}
			else
			{
				data = $.extend( data, {suburb: $('#city').val(),
											state: $('#state').val(),
											postcode: $('#postcode').val(),
											country_code: $('#country').val()});
			}
			//console.log(data);
			break;
	}
	$.getJSON(baseUrl+'mospace/events-and-ticketing/save-mo-party',
		data,
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
					window.location = baseUrl+'mospace/events-and-ticketing/register-mo-party/step/' + (step+1);
				}
				else
				{
					switch(jsonObj.error)
					{
						case 'incomplete':
							samuraiID = 'mospace-edit-details-location-incomplete-err';
							break;
						case 'incomplete phone':
							samuraiID = 'mospace-edit-details-phone-incomplete-err';
							break;
						case 'invalidLocation':
							samuraiID = 'mospace-edit-details-location-invalid-err';
							break;
					}
					Samurai.loadText( samuraiID,'mospace_error');
				}
			}
		}
	);
}

function emailPromotion()
{
	var win = window.open('mailto: ?body='+$P.str_replace('+',' ',$P.urlencode($('#mospace_txtbxPromotion').val())));
	if (win && win.open && !win.closed)
		win.close();
}

function tweetPromotion()
{
	var win = window.open('http://twitter.com/home/?status='+$P.str_replace('+',' ',$P.urlencode($('#mospace_txtbxPromotion').val())));
}

function facebookPromotion()
{
	//var win = window.open('mailto: ?body='+$P.str_replace('+',' ',$P.urlencode($('#mospace_txtbxPromotion').val())));
}

function toggleRatingBlock(id)
{
	if($('#rate_view_'+id).css('left') != '0px')
	{
//		$('#rateMe_'+id).show();
		$('#rate_me_'+id).animate({'left': -$('#mospace_moBlock_'+id).width()});
		$('#rate_view_'+id).animate({'left': 0});

        if (!$('.index-view').length)
            $('#mospace_moBlock_'+id+' .moRatingBlock').css('height',22);
	}
	else
	{
//		$('#rateMe_'+id).hide();
        $('#rate_view_'+id).animate({'left': $('#mospace_moBlock_'+id).width()});
		$('#rate_me_'+id).animate({'left': 0});

        if (!$('.index-view').length)
            $('#mospace_moBlock_'+id+' .moRatingBlock').css('height',30);
	}

	return false;
}

function toggleTeamForm(elm) {
}

/**
 * Hide the Samurai'd error string in the Join Network modal dialog and resize the dialog
 */
function hideNetworkJoinErrors(id)
{
    if( $('#mospace-network-join-errors_'+id).css('display') != "none" )
    {
        $('#mospace-network-join-errors_'+id).hide();
        $.fancybox.resize();
    }
}

/**
 * Show the Samurai'd error string in the Join Network modal dialog and resize the dialog
 */
function showNetworkJoinErrors(id)
{
    $('#mospace-network-join-errors_'+id).show();
    $.fancybox.resize();
}

/**
 * Hide any modal join-network dialog errors and close the modal
 */
function closeNetworkJoin()
{
    hideNetworkJoinErrors();
    $.fancybox.close()
}

/**
 * Process the Join Network modal dialog.  The user should have requested to join
 * as either a Team or as an Invididual.  If neither, show an error
 */
function joinNetwork(id)
{
	type = $('input[name=joinType_'+id+']:checked').val();

    // Check they chose one
    if( !type )
    {
        showNetworkJoinErrors(id);
        return false;
    }

    hideNetworkJoinErrors();

	$('#join-network-'+id+' .join-buttons').empty();
	$('#join-network-'+id+' .join-buttons').append(loadingImage);
	var data = {
		id : id,
		type : type
	};

	$.getJSON(baseUrl+'mospace/network/join',
		data,
		function(jsonObj){
			if ( jsonObj.result )
			{
				$('#result-list-join-'+id+' > span,#result-list-join-'+id+' a.mospace_button, .network-status > span, .network-status > .mospace_button').hide();
				if ($('.network-status').length > 0)
					location.reload(true);
				else
                {
                    //Case: joining a private network and need to get confirmation form the admin
                    if( jsonObj.needConfirmation && $('#result-list-join-'+id+' .result-list-join-request-pending').length )
                    {
                        $('#result-list-join-'+id+' .result-list-join-request-pending').show();
                    }
                    else if( $('#result-list-join-'+id+' .result-list-youre-a-member').length )
                    {
                        $('#result-list-join-'+id+' .result-list-youre-a-member').show();
                    }
                    else
                    {
    					location.reload(true);
                    }
					
                    
                }
				$.fancybox.close();
			}
		}
	);
}

function leaveNetwork(id)
{
	$('#leave-network-'+id+' .leave-buttons').empty();
	$('#leave-network-'+id+' .leave-buttons').append(loadingImage);

	var data = {
		id : id
	};

	$.getJSON(baseUrl+'mospace/network/leave',
		data,
		function(jsonObj){
			if ( jsonObj.result )
			{
				$('.network-status > span, .network-status > .mospace_button').hide();
				$('#network-block-'+id).remove();
				//$('#join-network-'+id+'-button').show();
				if ($('#join-network-'+id+'-button').length > 0)
					location.reload(true);
				$.fancybox.close();
			}
		}
	);
}

var limitText = function(limitField, limitNum) {
	if (limitField.value.length > limitNum) {
		limitField.value = limitField.value.substring(0, limitNum);
	}
}


$(document).ready(function(){
    //remove nojs class if javascript is enabled
    $('body').removeClass('nojs');
//    $('.toggler:not(.open)').parent().siblings('.summary-info').hide();
    $('.summary-box h2:has(.toggler)').bind('click', function() {
        e = this;
        $(e).siblings('.summary-info').slideToggle('medium',function(){
            t = $(e).find('.toggler');
            if (t.hasClass('open')) {
                document.cookie=$(e).parent().attr('id')+ "=0";
            } else {
                document.cookie=$(e).parent().attr('id')+ "=1";
            }
            t.toggleClass('open');
        });

    });

//    $('#mospace_teamOption .team-button').bind('click', function(){
//       var e = $(this);
//       e.parent().toggle();
//       e.parent().siblings('.form-container').toggle();
//    });
//
//    $('.form-container .mospace_button').bind('click', function(){
//       var e = $(this);
//       e.parents('.form-container').toggle();
//       e.parents('.form-container').siblings('.blurb').toggle();
//    });

    $('#accordion .ac-toggler, #accordion h2.title').bind('click', function(){
        if ($(this).hasClass('title'))
            var e = $(this).siblings('.ac-toggler');
        else
            var e = $(this);
        e.toggleClass('collapsed');
        e.parent().next().slideToggle('slow');

        if (e.hasClass('collapsed')) {
            document.cookie=e.parent().next().attr('id')+ "=0"
        } else {
            document.cookie=e.parent().next().attr('id')+ "=1"
        }
    });

	if ($('#mospace-edit-details').length > 0 ) {
		$("#mospace_txtbxTeamNameAC").autocomplete({
                        source: function( request, response ) { 
                                $.ajax({
                                        url: baseUrl + "mospace/team/load-list",
                                        dataType: "json",
                                        data: {
                                                style: "full",
                                                maxRows: 30, 
                                                name_startsWith: request.term
                                        },  
                                        success: function( data ) {
                                                response( $.map( data.teams, function( item ) { 
                            var name = item.name;
                            if (item.num_members) name += " (" + item.num_members + ")";

                                                        return {
                                                                label: name,
                                                                value: item.name,
                                                                id: item.id
                                                        }   
                                                }));
                                        }
                                }); 
                        },  
            		minLength : 3,
            		select: function( event, ui ) { 
                                $('#mospace_txtbxTeamNameAC').val(ui.name);
                                $('.edit-details #mospace_txtbxTeamNameAC').val(ui.item.name);
                                $('.edit-details #mospace_teamNameID').text( ui.item.id );
                                $('.edit-details #mospace_joinATeamButton').show();
                        },  
                        open: function() {
                                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
                                $('.edit-details #mospace_joinATeamButton').hide();
                        },  
                        close: function() {
                                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
                        }   
        	}); 
		//$("#mospace_txtbxLocLocation,#mospace_txtbxDelLocation").autocomplete( '/register/ajax-get-address-list', locJson );
		//$("#mospace_txtbxLocLocation").bind( "result", ac_locLocResponse );
		//$("#mospace_txtbxDelLocation").bind( "result", ac_delLocResponse );

		$('.textarea_140').dodosTextCounter(140, {counterDisplayClass: "spokespersonCharLeft",addLineBreak:false,counterDisplayElement:'span'});
	}

	$(function(){
        fancyboxSettings.height = 310;
		$('.initiate-tweet').fancybox(fancyboxSettings);
	});


	initSlider('#donation-slide-items');
    initSlider('#team-slide-items');
    initSlider('#poster-slide-items');

    $('#donation-btn-tweet-it').click(function(){
    	window.open('http://twitter.com/home/?status=' + encodeURIComponent( $('#donation-twitter-carousel .carousel li.active textarea').val() ));
    });
    $('#team-btn-tweet-it').click(function(){
    	window.open('http://twitter.com/home/?status=' + encodeURIComponent( $('#team-twitter-carousel .carousel li.active textarea').val() ));
    });
    $('#poster-btn-tweet-it').click(function(){
    	window.open('http://twitter.com/home/?status=' + encodeURIComponent( $('#poster-twitter-carousel .carousel li.active textarea').val() ));
    });

//    $('#twitter-carousel').dialog({
//        autoOpen: false,
//        width : 460,
//        resizable: false,
//        modal: true,
//        close: function(){
//             $('.post-content-wrapper object').css('visibility','visible');
//        }
//    });

    var reward = $('input#totalnumprizes').val() || 0;
    if ( reward > 0 )
        $('#menu-nav-rewards').html( $('#menu-nav-rewards').html() + ' <span class="rewards-count">(!)</span>' );

    if($('.other-email-client').length > 0) {
        $('.other-email-client').each(function(){
            $(this).click(function() {
                fancyboxSettings.height = 450;
                
                var onCompleteInner = function(el) {
                    // Stop trying to resize the fancybox during onclick
                    $(el).data('oldEvents',$(el).data('events'));
                    $(el).data('events',{});
                };
                
                var onClosedInner = function(el) {
                    $(el).data('events',$(el).data('oldEvents'));
                };

                if ($(this).hasClass('ask-donation')) {
                    $('div.ask-donation').show();
                    fancyboxSettings.onComplete = function() { onCompleteInner($('div.ask-donation'))};
                    fancyboxSettings.onClosed   = function() {   onClosedInner($('div.ask-donation'))};
                    $('#otherEmailTrigger-donation').fancybox().trigger('click')
                } else if ( $(this).hasClass('build-team') ) {
                    fancyboxSettings.onComplete = function() { onCompleteInner($('div.build-team'))};
                    fancyboxSettings.onClosed   = function() {   onClosedInner($('div.build-team'))};
                    $('div.build-team').show();
                    $('#otherEmailTrigger-buildteam').fancybox(fancyboxSettings).trigger('click');
                } else if ( $(this).hasClass('spread-gala') ) {
                    fancyboxSettings.onComplete = function() { onCompleteInner($('div.spread-gala'))};
                    fancyboxSettings.onClosed   = function() {   onClosedInner($('div.spread-gala'))};
                    $('div.spread-gala').show();
                    $('#otherEmailTrigger-spreadgala').fancybox(fancyboxSettings).trigger('click');
                }
                return false;
            });
        });
    }

	//mospace team photo upload
//	initAjaxImageUpload('#mospace_changeTeamProfilePic',
//						'#mospace_teamProfilePic',
//						'#mospace_teamProfilePicError',
//						'#mospace_teamProfilePicLoader',
//						'mospace/team/update-photo/',
//						{});

});

var initSlider = function ( id ) {
	var obj = $( id );
	var s = $("li", obj).length;
	var w = parseInt(obj.css('width')); //obj.width();
	var h = parseInt(obj.css('height')); //obj.height();
	var ts = s-1;
	var t = 0;
	var speed = 500;

	$("ul", obj).css('width', s*w);
	$("ul li:first", obj).addClass('active');

	$('span.next').click(function(){
		if ($('li.active', obj).next('li').length > 0) {
			t = (t>=ts) ? ts : t+1;
			p = (t*w*-1);
			$("ul",obj).animate({ marginLeft: p }, speed);

			$('li.active', obj).removeClass('active').next().addClass('active');
		} else {
			t =  0;
			p = (t*w*-1);
			$("ul",obj).animate({ marginLeft: p }, speed);

			$('li.active', obj).removeClass('active');
    		$('li:first', obj).addClass('active');
		}
	});

	$('span.previous').click(function(){
		if ($('li.active', obj).prev('li').length > 0) {
			t = (t<=0) ? 0 : t-1;
			p = (t*w*-1);
			$("ul",obj).animate({ marginLeft: p }, speed);

			$('li.active', obj).removeClass('active').prev().addClass('active');
		} else {
			t = ts;
			p = (t*w*-1);
			$("ul",obj).animate({ marginLeft: p }, speed);

			$('li.active').removeClass('active');
    		$('li:last').addClass('active');
		}

	});
}
function mospace_showId(id)
{
    alert(id);
}

// global uploader reference
var uploader;

function initAjaxImageUpload(editContainer, successContainer, errorContainer, loaderContainer, url, data, redirect, callback)
{
	$(errorContainer).hide();
	$(errorContainer+' div').hide();
    $(successContainer).hide();
    
	if ($(editContainer).length > 0){
		uploader = new AjaxUpload($(editContainer),{
			action: baseUrl+url,
			name: 'image',
			data: data,
			autoSubmit: true,
			responseType: 'json',
			onSubmit : function(file, ext){
				if (! (ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
				{
					$(errorContainer+' div.invalidExt').show();
					$(errorContainer).show();
					return false;
				}
				else
				{
					this.disable();
					$(errorContainer).hide();
					$(editContainer).css('display','');
					$(editContainer).hide();
					$(loaderContainer).html(loadingImage);
					$(loaderContainer).show();
				}
			},
			onComplete: function(file, response){
				$(loaderContainer).hide();
				if (response.success )
				{
                    if( successContainer )
                    {
                        $(successContainer).show();
//    					$(successContainer).attr('src',baseUrl+$P.urldecode(response.url)+'?timestamp='+$P.time());
                    }
                    if( redirect )
                        window.location = redirect;
                    
                    if ( callback && typeof callback == 'function' )
                        callback.call(this, response.id);
				}
				else
				{
					$(errorContainer+' div.invalidSize').show();
					$(errorContainer).show();
				}
				$(editContainer).show();
				this.enable();
			}
		});
	}
}

function cropProfilePic( id ){
    window.location = baseUrl+'mospace/photo-gallery/store/id/'+id;
}


function socialUpdate(id)
{
	$.getJSON(baseUrl+'mospace/members/social-flag/',
		{
			id: id
		}
	);
}

/**
 * When called, this will enable the 'store this crop as my profile pic' button
 */
function mospace_profileCropSaveEnable()
{
    $('#mospace-profile-crop-save-error').hide();    
    
    $("#crop-save-button").show();
}

/**
 * This will disable (hide) the save button on the mospace profile pic crop page
 */
function mospace_profileCropSaveDisable()
{
    $('#mospace-profile-crop-save-error').hide();    
    
//    Samurai.loadText( 'mospace-photo-gallery-crop-instructions', "mospace-profile-crop-save-message" );                
    
    $("#crop-save-button").hide();
}

/**
 * This assumes that we have set up a $.Jcrop variable "profilePic", the user has 
 * performed the crop and hit 'Save', after which this function is called with the
 * MediaFile id and cropping parameters.  This will then call cropProfileAction
 * with the required parameters to attempt to perform and save the cropped image.
 * If all good, redirect back to Mospace (to see the newly cropped profile pic)
 * 
 * @param int id - The ID of the original MediaFile to crop from
 */
function mospace_profileCropSave(id, redirect)
{
    var dimensions= profilePic.tellSelect();
    
	$.post(baseUrl+'mospace/photo-gallery/crop-profile/',
        { id: id, x: dimensions.x, y: dimensions.y, width: dimensions.w, height: dimensions.h },
		function(data){
			if( data )
			{
                if( data.result )
                {
                    $('#mospace-profile-crop-save-error').hide();
                    
                    $('#mospace-profile-crop-save-message').show();
                    Samurai.loadText( data.message, 'mospace-profile-crop-save-message' );

                    $('#top-level .profile-picture').attr('src',data.thumbnail);

                    profilePic.release();
                    $.cookie( ckName + '_pic', data.thumbnail, {path: '/', domain: ckUrl } );
                    if (redirect)
                        window.location = redirect
                }
                else
                {
                    $('#mospace-profile-crop-save-error').show();
                    $('#mospace-profile-crop-save-message').hide();
                    
                    Samurai.loadText( data.error, 'mospace-profile-crop-save-error' );                
                    Samurai.loadText( data.message, 'mospace-photo-gallery-crop-instructions' );                
                }
			}
		}
	);
}

/**
 * Given an element, turn it into a JCrop and set a default selection square.
 * Selection should be forced to be a square, with minimum dimensions.
 * 
 * returns the Jcrop'd object
 */
function mospace_profileCropInit( el )
{
    var height = el.height();
    var width = el.width();

    // Default selecting the entire image
    var startX = 0;
    var startY = 0;
    var endX = width;
    var endY = height;

    // Default the selection square to be in the 'middle' of the image, if the 
    // image isn't already square
    if( height > width )
        startY = ( height - width ) / 2;
    if( width > height )
        startX = ( width - height ) / 2;
    
    var minDimension = Math.min(width, height);
    var maxMinSize = 100;
    // Curve tending toward larger proportions of smaller images / smaller proportions of larger images, max 100px.
    var minSize = Math.min(maxMinSize,
    		               (1-Math.pow(1.01,-minDimension)) * maxMinSize
    		               );

    // Run Jcrop over the image, with the required defaults
    var profilePic = $.Jcrop(el, {
        aspectRatio: 1,
        boxWidth: width,
        minSize: [minSize, minSize],
        setSelect: [startX, startY, endX, endY],
        onSelect: mospace_profileCropSaveEnable,
        onRelease: mospace_profileCropSaveDisable
    });

    return profilePic;
}

/**
 * This will look for all radio buttons with class "year-button" and will
 * build a list of required years to save against the member
 */
function mospace_submitPastIndications()
{
     var pastcampaigns = $('div.year-button input[type=checkbox]:checked').map(function(i,n) {
        return $(n).val();
    }).get(); //get converts it to an array
    
	$.postJSON(baseUrl+'mospace/past-campaigns/save-past-indications',
		{
			'pastcampaigns[]': pastcampaigns
		},
		function(jsonObj){
			if( jsonObj )
			{
				if ( jsonObj.result )
				{
        			window.location.reload();
				}
			}
		}
	);
    
}

/**
 * Reset the Personalised Poster form items if Reset is clicked
 */
function mospace_posterFormReset()
{
    // Reset the radios back to the first one
    $("input:radio[name=poster-option]").filter('[value=standard]').attr('checked', true);
    
    // Clear and hide the textarea
    mospace_posterDisableDescription();
    $('#poster-option-description').val('');
}

function mospace_posterDisableDescription()
{
    $('#poster-option-description').attr('disabled','disabled');
}

function mospace_posterEnableDescription()
{
    $('#poster-option-description').removeAttr('disabled');
}

/**
 * Actions taken if the poster is deemed not complete
 */
function mospace_posterMarkIncomplete()
{
    $('#mospace-poster-share-button').hide();
    $("#mospace-poster-errors").hide().val('');
    $('#mospace-poster-info').hide();
}

/**
 * Actions taken if the poster is deemed complete
 */
function mospace_posterMarkComplete()
{
    $('#mospace-poster-share-button').show();
    $('#mospace-poster-info').show();
    $("#mospace-poster-errors").hide().val('');
}

function mospace_posterFormSave()
{
    // Can't find a decent loading method in rest of mospace that can be turned off
	$('#mospace-poster-loading').show();
    
	$.post(baseUrl+'mospace/downloads/save-poster/',
        {   type: $("input:radio[name=poster-option]:checked").val(), 
            description: $("#poster-option-description").val(), 
            image: $("#poster-image-id").val()
        },
		function(data){
			if( data )
			{
                if( data.result )
                {
                    // All good? Reload the page which should give us a new
                    // thumbnail also.  Add a timestamp to the image src
                    // to break the cache
                    mospace_posterMarkComplete();
                    var nowDate = new Date();
                    $("#mospace-poster-thumbnail").attr('src', data.thumbnail + "?"+ nowDate.getTime() );
                    $("#mospace-poster-preview").show();
                    $("#mospace-poster-link").attr("href", "/"+data.filename + "?"+ nowDate.getTime() );
                }
                else
                {
                    Samurai.loadText( data.error, "mospace-poster-errors" );
                    $("#mospace-poster-errors").show();
                }
            	$('#mospace-poster-loading').hide();
			}
		}
    );
}

/**
 * This will examine the value of the checkbox on the mospace/health-check/ page
 * and if checked, will save this against the current member and show the 
 * corresponding 'well done' content.
 * Otherwise, will save healthcheck as false for the member and show the "you should
 * get checked" content
 */
function mospace_healthCheckUpdate()
{
    // Can't find a decent loading method in rest of mospace that can be turned off
	$('#mospace-healthcheck-loading').show();
    $("#mospace-healthcheck-errors").hide();
    
	$.post(baseUrl+'mospace/health-check/update/',
        {   healthcheck: $('#healthcheck-option').is(':checked')
        },
        function(data)
        {
            if( data )
            {
                if( data.result )
                {
                    // All good? Then show the content related to the current
                    // health check setting
                    if( data.checked == 1)
                    {
                        $('#mospace-healthcheck-description-set').show();
                        $('#mospace-healthcheck-description-not-set').hide();
                    }
                    else
                    {
                        $('#mospace-healthcheck-description-set').hide();
                        $('#mospace-healthcheck-description-not-set').show();
                    }
                }
                else
                {
                    Samurai.loadText( data.error, "mospace-healthcheck-errors" );
                    $("#mospace-healthcheck-errors").show();
                }
                $('#mospace-healthcheck-loading').hide();
            }
        }
    );
}

/**
 * After the user has selected an image from the carousel, update the look and feel 
 * of the carousel and inject the media_file id into the form
 */
function mospace_posterSelectImage(id)
{
    // Clear selections
    $('.mospace-poster-image').each(function(e){
        $(this).removeClass("selected");
    });

    // Set new selection
    $("#mospace-poster-image-"+id).addClass("selected");
    
    // Copy new ID into hidden form element
    $("#poster-image-id").val(id);
}

function mospace_toggleMotivationExtra()
{
    if ( $('#edit-motivation-data-wq').length && $('#edit-motivation-data-wq-showmore').length ) {
        $('#edit-motivation-data-wq-showmore').toggle();
        $('#edit-motivation-data-wq-showless').toggle();
    }
}

/**
 * Update the classes of all existing thumbnails to line them up correctly
 * Every 5th thumbnail should be "right-most"
 */
function mospace_relayoutPhotoGalleryPics() {
	$(".image-thumbnail").each(function(index) {
		if( ( index + 1) %5 == 0 )
			$(this).addClass("right-most");
		else
			$(this).removeClass("right-most");
	});
}

/**
 * This is called after uploading a new gallery picture, to then render the thumbnail
 * HTML and insert as the first picture in the gallery
 */
function mospace_displayPhotoGalleryPic(id)
{
    $.post(baseUrl+'mospace/photo-gallery/render-photo',
    {
        id: id
    },
    function(data){
        if( data )
        {
            if( data.success )
            {
                var content = data.content;
                
                if( !$(".image-thumbnail").length )
                    window.location = baseUrl + 'mospace/photo-gallery';
                
                // check if limit has reached, if yes remove the upload button
                if ( data.limitReached ) {
                    Samurai.loadText( 'mospace-photo-gallery-max-uploaded-reached-message', $('.uploadbutton-wrapper') );
                    delete uploader;
                }
                    
                
                // Add the new image area as the first thumbnail in the list
                $(".image-thumbnail").first().before(content);
                mospace_relayoutPhotoGalleryPics();
            }
            else
            {
            }
        }
    });    
}

function mospace_deletePhotoGalleryPic(elm, ret, thumbImage) {

    if(!ret)
        return;
    
    // Add in-progress class
    var overlayElm = thumbImage.parents('.image-thumbnail').find('.photo-delete-overlay');
    overlayElm.addClass('in-progress');

    $.post(baseUrl+'mospace/photo-gallery/ajax-delete-photo',
    {
        photo: thumbImage.attr('id')
    },
    function(data){
        if( data )
        {
            overlayElm.removeClass('in-progress');
            if( data.success )
            {
                // All good? Then remove the thumbnail image
                thumbImage.parents('.image-thumbnail').fadeOut(500, function(){
                	$(this).remove()
                	mospace_relayoutPhotoGalleryPics();
                });
                
                if (data.uploadButton)
                {
                    $('.uploadbutton-wrapper').html( data.uploadButton );
                    initAjaxImageUpload('#upload-image-button a',
						'null',
						'#mospace_uploadMemberPhotoError',
						'#mospace_uploadMemberPhotoLoader',
						'mospace/photo-gallery/upload/',
						{},
                        null,
                        mospace_displayPhotoGalleryPic);
                    $("#upload-image-button").show();
                }
            }
            else
            {

            }
        }
    });
}

function mospace_deletePhotoFromTheatre(elm ,ret, thumbImage)
{
     if(!ret)
        return;

    $.post(baseUrl+'mospace/photo-gallery/ajax-delete-photo',
    {
        photo: thumbImage.attr('id')
    },
    function(data){
        if( data )
        {
            if( data.success )
            {
                // All good? Then remove the thumbnail image
                var navBlock = $('.js_block-scroller-blocks').find('[image-id='+thumbImage.attr('id').replace('photo_', '')+']').parent(),
                    newActiveBlock = null,
                    scrollBlock = navBlock.parents('.js_scroll-block'),
                    nextBlock = scrollBlock.next('.js_scroll-block'),
                    prevBlock = scrollBlock.prev('.js_scroll-block');
                if (navBlock.next('.brush-image').length > 0)
                    newActiveBlock = navBlock.next('.brush-image');
                else if (nextBlock.length > 0)
                    newActiveBlock = nextBlock.find('.brush-image').first();
                else if (navBlock.prev('.brush-image').length > 0)
                    newActiveBlock = navBlock.prev('.brush-image');
                else if ( prevBlock.length > 0 )
                    newActiveBlock = prevBlock.find('.brush-image').last();
                else
                    window.location = baseUrl + 'mospace/photo-gallery';

                thumbImage.fadeOut(400, function(){$(this).remove()});
                scrollBlock.width( scrollBlock.width() - navBlock.width() );
                navBlock.fadeOut(500, function() {
                    $(this).remove();
                    if ( newActiveBlock.length > 0 )
                        newActiveBlock.find('a').trigger('click');
                });
                
            }
            else
            {

            }
        }
    });
}

// credit to snippler
/************************************************************
 * elm = the element which was clicked
 * callback = funtion to call on close of fancy box
 * 
 */

function photoDeleteConfirm(elm, msg,thumbImage, callback, okBtnTxt, cancelBtnTxt ) {
    
    if( !okBtnTxt )
        okBtnTxt = "Ok!";
    if( !cancelBtnTxt )
        cancelBtnTxt = "Cancel!";
    
    var ret = false;
    jQuery.fancybox({
        centerOnScroll: true,
        overlayColor : '#000',
        width: 560,
        content : "<div style=\"margin:1px;text-align: center\"><img style=\"max-width: 400px\" class=\"thumbnail\" src=\"" + thumbImage.attr('src') + "\" /><br />" +msg+"<div style=\"text-align:right;margin-top:10px;\"><input id=\"fancyConfirm_cancel\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\""+cancelBtnTxt+"\"><input id=\"fancyConfirm_ok\" style=\"margin:3px;padding:0px;\" type=\"button\" value=\""+okBtnTxt+"\"></div></div>",
        onComplete : function() {
            jQuery("#fancyConfirm_cancel").click(function() {
                ret = false; 
                jQuery.fancybox.close();
            })
            jQuery("#fancyConfirm_ok").click(function() {
                ret = true; 
                jQuery.fancybox.close();
            })
        },
        onClosed : function() {
            callback.call(this, elm, ret, thumbImage);
        }
    });
}

function mospace_revokeFacebook( facebookId )
{    
    $.ajax({
        url: baseUrl + "auth/ajax-revoke-facebook-authorisation",
        dataType: "json",
        data: {
            facebookId: facebookId
        },
        success: function( data ) {
            if ( data.success )
                facebook_revokeAuthorization();
        }
    });
}
