;(function($) {

function getAppBase() {
	if (window.__appBase === undefined) {
		return '';
	}
	else {
		return __appBase;
	}
}

var _remove = $.fn.remove;

$.fn.remove = function( selector, keepData ) {
	return this.each(function() {
		if ( !keepData ) {
			if ( !selector || $.filter( selector, [ this ] ).length ) {
				$( "*", this ).add( this ).each(function() {
					$( this ).triggerHandler( "remove" );
				});
			}
		}
		return _remove.call( $(this), selector, keepData );
	});
};


$.fbWidget = function( name, base, prototype ) {
	var namespace = name.split( "." )[ 0 ],
		fullName;

	name = name.split( "." )[ 1 ];
	fullName = namespace + "-" + name;

	if ( !prototype ) {
                prototype = base;
                base = $._fbWidget;
        }

	$.expr[ ":" ][ fullName ] = function( elem ) {
		return !!$.data( elem, name );
	};

	
	$[ namespace ] = $[ namespace ] || {};
	$[ namespace ][ name ] = function( options, element ) {
		// allow instantiation without initializing for simple inheritance
		if ( arguments.length ) {
			this._createWidget( options, element );
		}
	};

	var basePrototype = new base();

	basePrototype.options = $.extend( {}, basePrototype.options );
	$[ namespace ][ name ].prototype = $.extend( true, basePrototype, {
		namespace: namespace,
		widgetName: name,
		widgetEventPrefix: $[ namespace ][ name ].prototype.widgetEventPrefix || name,
		widgetBaseClass: fullName
	}, prototype );

	$.fbWidget.bridge( name, $[ namespace ][ name ] );
}

$.fbWidget.bridge = function( name, object ) {
	$.fn[ name ] = function( options ) {
		var isMethodCall = typeof options === "string",
			args = Array.prototype.slice.call( arguments, 1 ),
			returnValue = this;

		// allow multiple hashes to be passed on init
		options = !isMethodCall && args.length ?
			$.extend.apply( null, [ true, options ].concat(args) ) :
			options;

		// prevent calls to internal methods
		if ( isMethodCall && options.substring( 0, 1 ) === "_" ) {
			return returnValue;
		}

		if ( isMethodCall ) {
			this.each(function() {
				var instance = $.data( this, name ),
					methodValue = instance && $.isFunction( instance[options] ) ?
						instance[ options ].apply( instance, args ) :
						instance;
				if ( methodValue !== instance && methodValue !== undefined ) {
					returnValue = methodValue;
					return false;
				}
			});
		} else {
			this.each(function() {
				var instance = $.data( this, name );
				if ( instance ) {
					if ( options ) {
						instance.option( options );
					}
					instance._init();
				} else {
					$.data( this, name, new object( options, this ) );
				}
			});
		}

		return returnValue;
	};
};

$._fbWidget = function( options, element ) {
	// allow instantiation without initializing for simple inheritance
	if ( arguments.length ) {
		this._createWidget( options, element );
	}
};


$._fbWidget.prototype = {
	widgetName: "widget",
	widgetEventPrefix: "",
	options: {
		disabled: false
	},
	_createWidget: function( options, element ) {
		// $.widget.bridge stores the plugin instance, but we do it anyway
		// so that it's stored even before the _create function runs
		this.element = $( element ).data( this.widgetName, this );
		this.options = $.extend( true, {},
			this.options,
			$.metadata && $.metadata.get( element )[ this.widgetName ],
			options );

		var self = this;
		this.element.bind( "remove." + this.widgetName, function() {
			self.destroy();
		});

		this._create();
		this._init();
	},
	_create: function() {},
	_init: function() {},

	destroy: function() {
		this.element
			.unbind( "." + this.widgetName )
			.removeData( this.widgetName );
		this.fbWidget()
			.unbind( "." + this.widgetName )
			.removeAttr( "aria-disabled" )
			.removeClass(
				this.widgetBaseClass + "-disabled " +
				this.namespace + "-state-disabled" );
	},

	widget: function() {
		return this.element;
	},

	option: function( key, value ) {
		var options = key,
			self = this;

		if ( arguments.length === 0 ) {
			// don't return a reference to the internal hash
			return $.extend( {}, self.options );
		}

		if  (typeof key === "string" ) {
			if ( value === undefined ) {
				return this.options[ key ];
			}
			options = {};
			options[ key ] = value;
		}

		$.each( options, function( key, value ) {
			self._setOption( key, value );
		});

		return self;
	},
	_setOption: function( key, value ) {
		this.options[ key ] = value;

		if ( key === "disabled" ) {
			this.widget()
				[ value ? "addClass" : "removeClass"](
					this.widgetBaseClass + "-disabled" + " " +
					this.namespace + "-state-disabled" )
				.attr( "aria-disabled", value );
		}

		return this;
	},

	enable: function() {
		return this._setOption( "disabled", false );
	},
	disable: function() {
		return this._setOption( "disabled", true );
	},

	_trigger: function( type, event, data ) {
		var callback = this.options[ type ];

		event = $.Event( event );
		event.type = ( type === this.widgetEventPrefix ?
			type :
			this.widgetEventPrefix + type ).toLowerCase();
		data = data || {};

		// copy original event properties over to the new event
		// this would happen if we could call $.event.fix instead of $.Event
		// but we don't have a way to force an event to be fixed multiple times
		if ( event.originalEvent ) {
			for ( var i = $.event.props.length, prop; i; ) {
				prop = $.event.props[ --i ];
				event[ prop ] = event.originalEvent[ prop ];
			}
		}

		this.element.trigger( event, data );

		return !( $.isFunction(callback) &&
			callback.call( this.element[0], event, data ) === false ||
			event.isDefaultPrevented() );
	}
};


$.fbWidget('_fb.facebookConnect', {
	options: {
		'xfbmlParse': false,
		'loginText':'Login',
		'logoutText':'Logout'
	},
	_create: function() {
		var self=this;
		$(document).bind('FB.init', function() {
			if ( self.options.xfbmlParse ) {
				FB.XFBML.parse(self.element[0]);
			}
			FB.getLoginStatus(function(response) {
				self._update(response);
			});
		});
		$(document).bind('FB.auth.sessionChange', function(event, response){
			self._update(response);
		});
	},
	_change: function(status) {
		var self = this;
		self.element.trigger('change');
	},
	_update: function(response) {
		var self=this;
		if (response.authResponse) {
			self.element.find('.fb_button_text').html(self.options.logoutText);
			self.populateForm();
			self.element.trigger('connected');
		}
		else {
			self.element.find('.fb_button_text').html(self.options.loginText);
			self.element.trigger('disconnected');
		}				
		self._change(response.authResponse);
	},
	populateForm: function() {
		var self = this;
		var form = self.element.closest('form');
		var fields = ['first_name', 'last_name', 'hometown', 'email'];
		if ( form ) {
			FB.api('/me', function(response) {
				for( i in fields ) {
					var field = fields[i];
					switch(field) {
						case 'first_name':
						case 'last_name':
						case 'email':
							var input = form.find('input[name="data[DynamicFormSubmission][' + field + ']"]');
							if ( input && input.val() == '' ) {
								input.val(response[field]);
							}
							break;
						case 'hometown':
							if ( response.hometown && response.hometown.name ) {
								var location = response.hometown.name.split(', ');
								if ( location.length == 2 ) {
									var input = form.find('input[name="data[DynamicFormSubmission][city]"]');
									if ( input && input.val() == '' ) {
										input.val(location[0]);
									}
									/*input = form.find('input[name="data[DynamicFormSubmission][state_province]"]');
									if ( input && input.val() == '' ) {
										var val = input.find("[text='" + location[1] + "']").val();
										if ( val ) {
											input.val(val);
										}
											
									}*/	
								}
							}
							break;
					}
				}
			});
		}
	}
});

$.fbWidget('_fb.facebookPrepopulateForm', {
	options: {
		'fields': ['first_name', 'last_name', 'hometown', 'location', 'email']
	},
	_create: function() {
		var self = this;
	},
	_init: function() {
		var self = this;
		self.options.form = self.element.closest('form');

		self.element.click(function() {
			self.prepopulate();
			return false;
		});
	},
	prepopulate: function() {
		var self = this;
		if ( self.options.form ) {
			FB.login(function(response) {
				if (response.authResponse) {
					FB.api('/me', function(response) {
						for( i in self.options.fields ) {
							var field = self.options.fields[i];
							switch(field) {
								case 'first_name':
								case 'last_name':
								case 'email':
									var input = self.options.form.find('input[name="data[DynamicFormSubmission][' + field + ']"]');
									if ( input && input.val() == '' ) {
										input.val(response[field]);
									}
									break;
								case 'hometown':
									if ( response.hometown && response.hometown.name ) {
										var location = response.hometown.name.split(', ');
										if ( location.length == 2 ) {
											var input = self.options.form.find('input[name="data[DynamicFormSubmission][city]"]');
											if ( input && input.val() == '' ) {
												input.val(location[0]);
											}
											/*input = self.options.form.find('input[name="data[DynamicFormSubmission][state_province]"]');
											if ( input && input.val() == '' ) {
												var val = input.find("[text='" + location[1] + "']").val();
												if ( val ) {
													input.val(val);
												}
												
											}*/	
										}
									}
									break;
							}
						}
					});
				}
			}, {scope: 'email'});
		}
	}
});

$.fbWidget('_fb.tooltip', {
	options: {
		'position':{
			'corner':{
				'tooltip':'bottomLeft',
				'target':'topCenter'
			}
		},
		'hide': {
			'fixed': true
		},
		'delay': 500
	},
	_create: function() {
		var self=this;
		if ( self.element.data('qtip') ) {
			return;
		}
		if ( !self.options.content ) {
			self.options.content = self.element.attr('tooltip').replace(/\\/g,"");
		}
		if ( self.options.content ) {
			self.element.qtip(self.options);
		}
	}
});

$.fbWidget('_fb.twitterConnect', {
	options: {
		'close': function() {
		}
	},
	_create: function() {
		var self = this;

		self.elementOrig = self.element;
	},
	_init: function() {
		var self = this;

		self._getAuthStatus();
		
		self.element.click(function() {
			self.open();
			return false;
		});
	},
	open: function() {
		var self = this;

		self.close();
		self._authWin = window.open(getAppBase() + '/socnet/twitter/connect/popup:1', 'TwitterConnect', 'location=0,status=0,width=800,height=400');
		self._authInterval = window.setInterval(function() {
			if (self._authWin.closed) {
				self.close();
				self._getAuthStatus();
			}
		}, 1000);
	},
	close: function() {
		var self = this;
		if (self._authInterval) {
			window.clearInterval(self._authInterval);
			self._authInterval = null;
		}
		if (self._authWin) {
			if (!self._authWin.closed) {
				self._authWin.close();
			}
			self._authWin = null;
		}
		
	},
	_getAuthStatus: function() {
		var self = this;
		$.get(getAppBase() + '/socnet/twitter/auth_status', 
			{}, 
			function(data) {
				data = $.extend({}, data);
				if (data.user_id) {
					self.element.hide().after('Connected as @<a href="http://twitter.com/' + data.screen_name + '" target="_new">' + data.screen_name + '</a>');
					self.element.closest('form').find('input[name="data[DynamicFormSubmission][twitter_user_id]"]').val(data.user_id);
					self.element.closest('form').find('input[name="data[DynamicFormSubmission][twitter_screen_name]"]').val(data.screen_name);
					self.element.trigger('connected');
				}
			}, 
			'json'
		);
	}
	
});

$.fbWidget('_fb.twitterMessage', {
	options: {
		counterHtml: '<div class="twitterCharCounter"></div>',
		counterText: ' characters left'
	},
	_create: function() {
		var self = this;
		
		self.counter = $(self.options.counterHtml).insertAfter(self.element);
	},
	_init: function() {
		var self = this;

		self.updateCount();
		
		self.element.keyup(function(){
			self.updateCount();
            	});
	},
	updateCount: function() {
		var self = this;

		var left = 140 - self.element.val().length;
                var lines = self.element.val().replace(/\\r/g,'').split('\\n');
               	left = left - lines.length + 1;
               	if ( left < 0 ) {
                        self.counter.addClass('overlimit');
                }
               	else {
                        self.counter.removeClass('overlimit');
                }
                self.counter.html('<span>' + left + '</span>' + self.options.counterText);
	}
	
});

$.fbWidget('_fb.facebookInvite', {
	options: {
		message: null
	},
	_create: function() {
		var self=this;
		if (self.options.message == null || self.options.message == '') {
			self.options.message = 'Join me on ' + configuration.portalName + '. Here is the link: http://' + document.domain + configuration.portalPrefix;
		}
		$(document).bind('FB.init', function() {
			self.element.click(function() {
				var options = $.extend({}, {method: 'apprequests'}, self.options);
				var receiverUserIds = FB.ui(options, function(receiverUserIds) {
					if (receiverUserIds && receiverUserIds.request_ids) {
						$.each(receiverUserIds.request_ids, function(index, value) {
							FB.api('/'+value, function(response) {
								if (response && response.to && response.to.id) {
									$.post(__appBase + '/socnet/facebook/invites', response.to);
								}
							});
						});
					}
				});
				return false;
			});
		});
	}
});

$.fbWidget('_fb.foursquareConnect', {
	options: {
		'close': function() {
		}
	},
	_create: function() {
		var self = this;

		self.elementOrig = self.element;
		self.element.html('<img src="' + getAppBase() + '/img/btn-foursquare-connect.png">');
	},
	_init: function() {
		var self = this;

		self._getAuthStatus();
		
		self.element.click(function() {
			self.open();
			return false;
		});
	},
	open: function() {
		var self = this;

		self.close();
		self._authWin = window.open(getAppBase() + '/socnet/foursquare/connect/popup:1', 'FoursquareConnect', 'location=0,status=0,width=800,height=500');
		self._authInterval = window.setInterval(function() {
			if (self._authWin.closed) {
				self.close();
				self._getAuthStatus();
			}
		}, 1000);
	},
	close: function() {
		var self = this;
		if (self._authInterval) {
			window.clearInterval(self._authInterval);
			self._authInterval = null;
		}
		if (self._authWin) {
			if (!self._authWin.closed) {
				self._authWin.close();
			}
			self._authWin = null;
		}
		
	},
	_getAuthStatus: function() {
		var self = this;
		$.get(getAppBase() + '/socnet/foursquare/auth_status', 
			{}, 
			function(data) {
				data = $.extend({}, data);
				if (data.id) {
					self.element.hide().after('<img src="'+getAppBase()+'/img/btn-foursquare-small.png"> Connected as @<a href="http://foursquare.com/user/' + data.id + '" target="_new">' + data.firstName + ' ' + data.lastName + '</a>');
					self.element.closest('form').find('input[name="data[DynamicFormSubmission][foursquare_user_id]"]').val(data.id);
					self.element.trigger('connected');
				}
			}, 
			'json'
		);
	}
	
});


})(jQuery);

