Sparcq = ( this["Sparcq"] || {} );


if (!Sparcq.Account) {
	Sparcq.Account = function (settings) {
		this.init(settings);
	};
}

Sparcq.Account.prototype.init = function(args) {
	if (args) {
	}	
};

Sparcq.Account.prototype.showError = function(msg) {
	alert(msg);
};

Sparcq.Account.prototype.loadAccount = function() {
    var self = this;

    self.uid = false;
	
	SPARCQ.FB.actionOnLoginStatus(function(uid) {
		self.uid = uid;
		//self.loadProfileInformationFromFacebook();
	});

	$('#facebook_post_after_rate, #facebook_post_after_comment').click( function() {
        var count = ( $('#facebook_post_after_rate').attr('checked') ? 1 : 0 ) +
        ( $('#facebook_post_after_comment').attr('checked') ? 1 : 0 );

        var self = this;
        if ( this.checked && count == 1 ) {
            return SPARCQ.SOCIAL.requireFacebookPermissions(function() {
				$(self).attr('checked', 1);
			});
        }
        return true;
    });

	$('#member_bio').keyup(function(){
		var max = parseInt($(this).attr('maxlength'));
		if($(this).val().length > max){
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		}
		$('.charsRemaining').html('You have ' + (max - $(this).val().length) + ' characters remaining');
	});
	$('#member_bio').keyup();

	var self = this;
	var maxRows = 20;
	$('#member_location').autocomplete(
		function(args) {
			SPARCQ.COMPONENTS.queryGeonamesDB($('#member_location').val(), args, maxRows);
		}, {
			formatItem: function(item) {
				return (item) ?
					item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName :
					'';
			},
			formatResult: function(item) {
				return (item) ?
					item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName :
					'';
			},
			minChars: 3,
			max: maxRows,
			delay: 100,
			width: 350
		}
	).result( function(event, item, formatted) {
		self.location = {
			name: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
			id: item.geonameId
		};
		$('#member_location_geonameid').val(item ? item.geonameId : 0);
	});

	self.location = {
		name: $('#member_location').val(),
		id: $('#member_location_geonameid').val()
	};
}

Sparcq.Account.prototype.linkAccountWithService = function( service ) {
    var callback_url = document.location.href;
    callback_url = callback_url.replace( /\?error=([^&]+)/, '' );

    var self = this;        
	SPARCQ.API.callMethod('user.linkAccountWithService', {
        params: {
            sparcq_member_id: SPARCQ.SESSION.getMemberId(),
            service: service,
            callback: callback_url
        },
		onSuccess: function(ret) {
			self.handleLinkAccountWithService(ret, service);
		},
		onError: function(ret,id) {
			self.showError('error link with service');
		}
	});
}

Sparcq.Account.prototype.handleLinkAccountWithService = function( ret, service ) {
	var redirect = ret.parsed_return;

	if (redirect && redirect.url) {
        document.location.href = redirect.url;
    }
	else {
		this.addSocialNetwork(service);
	}
}

Sparcq.Account.prototype.unlinkAccountWithService = function( service ) {
    var self = this;        
	SPARCQ.API.callMethod('user.unlinkAccountWithService', {
        params: {
            sparcq_member_id: SPARCQ.SESSION.getMemberId(),
            service: service
        },
		onSuccess: function(ret) {
			self.handleUnlinkAccountWithService(ret, service);
		},
		onError: function(ret,id) {
			self.showError('error unlink with service');
		}
	});
}

Sparcq.Account.prototype.handleUnlinkAccountWithService = function( ret, service ) {
    this.removeSocialNetwork(service);
}

Sparcq.Account.prototype.loadPreferences = function() {
    var self = this;	
	SPARCQ.API.callMethod('user.getAccountPreferences', {
        params: {
            sparcq_member_id: SPARCQ.SESSION.getMemberId()
        },
		onSuccess: function(ret) {
			self.handleLoadPreferences( ret );
		},
		onError: function(ret,id) {
			self.showError('error load preferences');
		}
	}); 
}

Sparcq.Account.prototype.handleLoadPreferences = function( ret ) {
    var preferences = ret.parsed_return;
    if ( preferences.facebook ) {
        var html = 'Your account is linked to ' + 
            preferences.facebook.name;
            
        $('#facebook_account').html( html );
    }

    if ( preferences.twitter ) {
        var html = 'Your account is linked to ' + 
            preferences.twitter.name +
            ' (<a href="#" onClick="SPARCQ.COMPONENTS.account.unlinkAccountWithService( \'Twitter\' ); return false;">unlink</a>)';
        $('#twitter_account').html( html );
    }
    else {
        var html = 'Link your account to your ' +
            '<a href="#" onClick="SPARCQ.COMPONENTS.account.linkAccountWithService( \'Twitter\' ); return false;">Twitter profile</a>';
        $('#twitter_account').html( html );
        
        // Disable all the Twitter options
        $('#twitter_settings input, #twitter_settings select').attr( 'disabled', true );
    }

    // Set profile information from backend.
    if ( preferences.name ) {
        $('#member_name').val( preferences.name );
    }

    if ( preferences.location ) {
        $('#member_location').val( preferences.location );
    }

    if ( preferences.gender ) {
        $('#member_gender').val( preferences.gender );
    }

    // If none of the above fields are populated, grab them from facebook
    if ( !preferences.name && !preferences.location && !preferences.gender ) {
        if ( this.uid ) {
            this.loadProfileInformationFromFacebook();
        }
        else {
            // Login, then load information
        }
    }
    
    for ( var option in preferences.options ) {
        $( '#' + option + '[type=checkbox]').attr( 
            'checked', 
            true 
        );
        
        $( '#' + option ).val( 
            preferences.options[option]
        );
    }    
}

Sparcq.Account.prototype.validatePreferences = function(params, view) {
	var isValid = true;

	if (!this.validateDate(params.member_birthday_month, params.member_birthday_day, params.member_birthday_year)) {
		view.invalidBirthday(true);
		isValid = false;
	}
	else {
		view.invalidBirthday(false);
	}
	return isValid;
}

Sparcq.Account.prototype.daysInMonth = function(month,year) {
	if (month == 2)
		return (year % 4 == 0) ? 29 : 28;

	if (month == 9 || month == 4 || month == 6 || month == 11)
		return 30;
	
	return 31;
}

Sparcq.Account.prototype.validateDate = function(month,day,year) {
	if (month > 0 && day > 0) {
		return month > 0 && month < 13 &&
			day > 0 && day <= this.daysInMonth(month,year);
	}
	return true;
}

Sparcq.Account.prototype.invalidBirthday = function(bool) {
	if (bool)
		$('.birthday').addClass('error')
	else
		$('.birthday').removeClass('error');
}

Sparcq.Account.prototype.setPreferences = function() {
    var params = {};
	var options = '';
	var social = '';
    var self = this;

    $('#facebook_settings input, #facebook_settings select, ' +
        '#twitter_settings input, #twitter_settings select').each( function() {
        var key = false;
        var val = false;
                
        if ( this.type == 'checkbox' ) {
            key = this.id;
            val = ( this.checked ? '1' : '0' );            
        }
        else {
            // Select
            key = this.id;
            val = $(this).val();
        }
        
        if ( key ) {
            options += (options ? '&' : '' ) + 
                key + '=' + val;
        }
    });

	$('#linked_profile_list .profile.on input').each(function () {
		var key = false;
        var val = false;

        if ( this.type == 'checkbox' ) {
            key = this.id;
            val = ( this.checked ? '1' : '0' );
        }
        else {
            // Select
            key = this.id;
            val = $(this).val();
        }

        if ( key ) {
            social += (social ? '&' : '' ) +
                key + '=' + val;
        }
	});

    $('.member_field:not(type=checkbox)').each( function() {
        var value = $(this).val();
        if ( value ) {
            params[this.id] = value;
        }
    });

	$('.member_field[type=checkbox]').each(function() {
		var value = $(this).val();
		params[this.id] = this.checked ? value : 0;
	});

	// Make sure the location name and id match
	if (params['member_location'] && this.location.name) {
		if (params['member_location'] != this.location.name)
			params['member_location_geonameid'] = 0;
	}

	params.sparcq_member_id = SPARCQ.SESSION.getMemberId();
    params.options = options;
    params.social = social;

	if (!this.validatePreferences(params,this)) {
		return;
	}

	SPARCQ.API.callMethod('user.setAccountPreferences', {
        params: params,
		onSuccess: function(ret) {
			//self.handleLoadPreferences( ret );
			SPARCQ.COMPONENTS.statusUpdate( 'preferences updated');
		},
		onError: function(ret,id) {
			self.showError('error save preferences');
		}
	}); 
}

Sparcq.Account.prototype.addSocialNetwork = function(network) {
	network = network.replace(/\W/g, '').toLowerCase();
	$('#linked_profile_list .' + network).remove().appendTo('#linked_profile_list').addClass('on');
	$('#linked_profile_list .' + network + " a").click(function() {
        SPARCQ.COMPONENTS.account.removeSocialNetwork(network);
        return false;
    });
    $('#unlinked_profile_list .' + network).hide();
}

Sparcq.Account.prototype.removeSocialNetwork = function(network) {
	network = network.replace(/\W/g, '').toLowerCase();
    $('#linked_profile_list .' + network).removeClass('on');
    $('#unlinked_profile_list .' + network).show();
}

