﻿Function.prototype.method = function(name, func) {
	this.prototype[name] = func;
	return this;
};

String.method('capitalize', function () {
	return this.replace(/^([a-z])|\s+([a-z])/g, function ($1) { return $1.toUpperCase(); });
});

Function.method('inherits', function (Parent) {
	this.prototype = new Parent( );
	return this;
});

Object.beget = function (o) {
	var F = function() {};
	F.prototype = o;
	return new F();
};

var App = {
	CookieName: "AudisferaWidgetOrder",
	Container: '#conteudo-principal',
	Column: '.column',
	RootPath: "",
	ImagePath: "Util/Img/v2",
	ColNumber: 2,
	CryptPassword: 'us.840',
	IsInit: false,
	SocialMedias: function () {
		//return ["WidgetTwitter", "WidgetFacebook"]
		return ["WidgetBlogs", "WidgetTwitter", "WidgetFacebook", "WidgetInstagram", "WidgetYoutube", "WidgetFavoritos", "WidgetNews", "WidgetGaragemAudi", "WidgetLeMans", "WidgetAudiTradition", "WidgetAudiMagazine", "WidgetLifestyle"]
	} (),
	Favorites: [],
	TwitterUserId: null,
	FacebookUserId: null,
	Init: function () {
		this.IsInit = true;

		this.ImagePath = this.RootPath + this.ImagePath;
		$('.widget').remove();

		var that = this;

		this.TwitterUserId = $('#twUserId').val();
		this.FacebookUserId = $('#fbUserId').val();

		if (!this.TwitterUserId && !this.FacebookUserId) {
			var Cookie = $.cookie('AudisferaFavorites');
			this.Favorites = Cookie ? $.parseJSON(Aes.Ctr.decrypt($.cookie('AudisferaFavorites'), that.CryptPassword, 128)) : [];
		}

		$('#menu-customize-pagina').find('label').removeClass('checked');
		$('#menu-customize-pagina').find('input').attr('checked', false);

		this.Restore(function () {
			if ($('#menu-customize-pagina').find('input').not(':checked').length == 1) {
				$('#menu-customize-pagina').find('.all label').addClass('checked');
				$('#menu-customize-pagina').find('.all input').attr('checked', true);
			}
		});
	},
	GetDefaultOrder: function () {
		return Array('WidgetYoutube', 'WidgetTwitter', 'WidgetFacebook', 'WidgetGaragemAudi', 'WidgetInstagram', 'WidgetFavoritos', 'WidgetNews', 'WidgetAudiMagazine', 'WidgetBlogs', 'WidgetAudiTradition', 'WidgetLeMans', 'WidgetLifestyle');
	},
	CheckResolution: function () {
		var win_w = $(window).width();
		var visible = parseInt(win_w / 428, 10);
		var LastColNumber = this.ColNumber;
		var that = this;

		if (visible < 3) {
			this.ColNumber = 2;

			if (LastColNumber == 3) {
				$(this.Column + ':eq(2) > *').each(function (i, item) {
					var wdg = $(item).data('widget');
					wdg.Move((i + 1) * 3);
				});
			}
			$("#container-geral").removeClass("three-columns").addClass("two-columns");
		}
		else {
			this.ColNumber = 3;

			if (LastColNumber == 2) {
				var MaxItems = Math.max(Math.max($(this.Column + ':eq(0) > *').length, $(this.Column + ':eq(1) > *').length), $(this.Column + ':eq(2) > *').length);

				var Count1 = 0;
				var Count2 = 0;
				for (var j = 0; j < MaxItems; j++) {
					for (var i = 0; i < 2; i++) {
						var itemIndex = ((j * 2) + (i + 1));

						if (itemIndex % 3 == 0) {
							var ObjToSave = $(this.Column + ':eq(' + i + ') > dl:eq(' + (j - ((i == 0) ? Count1 : Count2)) + ')');
							if (ObjToSave.length > 0) {
								var wdg = ObjToSave.data('widget');
								wdg.Move(999);
							}

							if (i == 0) Count1++;
							if (i == 1) Count2++;
						}
					}
				}
			}
			$("#container-geral").removeClass("two-columns").addClass("three-columns");
		}
		$(window).data('resizing', false);
	},
	Restore: function (fn) {
		var that = this;
		var Order = $.parseJSON(Base64.decode($.cookie(this.CookieName) || '')) || this.GetDefaultOrder();
		$.each(Order, function (i, item) {
			var colNumber = i < that.ColNumber ? i : (i - (parseInt(i / that.ColNumber, 10) * that.ColNumber));
			if (item && null != item) {
				if ($.inArray(item, that.SocialMedias) < 0) return;
				//$('#menu-customize-pagina').find('input[value=' + item + ']').next().addClass('checked');
				//$('#menu-customize-pagina').find('input[value=' + item + ']').attr('checked', true);

				new _Widget({
					type: eval(item),
					colNumber: colNumber
				});
			}
		});
		this.ApplySortable();

		if (typeof fn === 'function') fn.call();
	},
	MinLengthColumn: function () {
		var that = this;
		var minColumn = 0;
		var itens = 999;

		$(App.Column + ':visible').each(function (i, item) {
			if (i >= that.ColNumber) return;

			if ($('> *', item).length < itens) {
				itens = $('> *', item).length;
				minColumn = i;
			}
		});
		return minColumn;
	},
	Search: function (keywords) {
		$('.widget[id!=WidgetFavoritos][id!=WidgetFacebook]').each(function (i, item) {
			var wdg = $(item).data('widget');

			wdg.Reset();
			wdg.Keywords = keywords;
			wdg.LoadContent();
		});
	},
	Save: function () {
		var OrderToSave = [];
		var MaxItems = this.ColNumber == 2 ?
			Math.max($(this.Column + ':eq(0) > *').length, $(this.Column + ':eq(1) > *').length) :
			Math.max(Math.max($(this.Column + ':eq(0) > *').length, $(this.Column + ':eq(1) > *').length), $(this.Column + ':eq(2) > *').length);


		for (var j = 0; j < MaxItems; j++) {
			for (var i = 0; i < this.ColNumber; i++) {
				var ObjToSave = $(this.Column + ':eq(' + i + ') > dl:eq(' + j + ')');
				OrderToSave.push(ObjToSave.attr("id"));
			}
		}
		$.cookie(this.CookieName, Base64.encode(JSON.stringify(OrderToSave)), { expires: this.cookieExpiry, path: "/" });
	},
	CheckFirstAccess: function () {
		if ($.cookie('AudisferaAccess'))
			return false;
		else {
			$.cookie('AudisferaAccess', Date(), { expires: 365, path: "/" });
			return true;
		}
	},
	ApplySortable: function () {
		if ($(this.Column).data("sortable")) {
			$(this.Column).sortable("refresh");
			return;
		}

		$(this.Column).sortable({
			connectWith: App.Column,
			handle: 'dt',
			helper: 'clone',
			cursor: 'move',
			appendTo: 'body',
			update: function () { App.Save(); }
		});

		$(this.Column).disableSelection();
	},
	ShowDialog: function (settings) {
		settings.width = settings.width || 300;
		settings.height = settings.height || "auto";

		if (settings.texto) $("#dialog").html(settings.texto);

		var d = $("#dialog").dialog({
			modal: true,
			resizable: false,
			autoOpen: false,
			dialogClass: settings.classe || "",
			width: settings.width,
			height: settings.height,
			title: settings.titulo || "Atenção",
			buttons: settings.buttons,
			zIndex: 1500
		});

		d.parent().appendTo('.UI-Smoothness');

		d.dialog('open');
	},
	ShowLoader: function (settings) {
		if (!settings) var settings = {};
		$("#view-loader").find("*:not(img)").remove();

		if (settings.texto) $("#view-loader").prepend(settings.texto);

		$("#view-loader").dialog({
			modal: true,
			resizable: false,
			dialogClass: "view-loader-container" + (settings.classe ? ' ' + settings.classe : ''),
			width: settings.width || 220,
			height: settings.height || 19,
			minHeight: 0,
			buttons: settings.buttons,
			zIndex: 1500,
			close: function (event, ui) {
				$("#view-loader").find("*:not(img)").remove();
			}
		});
	},
	CloseLoader: function () {
		$("#view-loader").dialog('close');
	},
	AddFavorite: function (addToFav, fn) {
		var that = this;
		if (!this.TwitterUserId && !this.FacebookUserId) {
			this.Favorites.push(addToFav);

			$.cookie('AudisferaFavorites', Aes.Ctr.encrypt(JSON.stringify(this.Favorites), that.CryptPassword, 128), { expires: 365 })
			this.AfterAddFavorite(addToFav, fn);
		}
		else {
			$.getJSON(App.RootPath + 'Service/AddFavorite.ashx', { favorito: JSON.stringify(addToFav), FacebookUserId: that.FacebookUserId, TwitterUserId: that.TwitterUserId },
			function (ret) {
				if (ret.error) {
					that.ShowDialog({
						texto: '<p>' + ret.error + '</p>',
						buttons: {
							'Ok': function () {
								$(this).dialog('close');
							}
						}
					});
					return;
				}
				that.Favorites.push(addToFav);
				that.AfterAddFavorite(addToFav, fn);
			});
		}
	},

	AfterAddFavorite: function (addToFav, fn) {
		if ($("#WidgetFavoritos").length > 0) {
			$("#WidgetFavoritos").find('.nocontent').remove();
			var widget = $("#WidgetFavoritos").data('widget');

			if ($('#' + addToFav.WidgetId + 'Favorites').length <= 0) {
				var newItem = $('<li />', { id: addToFav.WidgetId + 'Favorites' })
							.append($('<h3 />', { text: addToFav.WidgetTitle }))
							.append($('<div />')
								.append($('<ul />'))
							);

				$("#WidgetFavoritos").find('dd ul.item-list').append(newItem);

				widget.ApplyAccordion(true);
			}
			widget.InsertContent(addToFav);

			var jsp = $("#WidgetFavoritos").find('.widgetScroll').data('jsp');
			if (jsp != null) {
				jsp.reinitialise();
			}
		}

		if (typeof fn === 'function') fn.call();
	},
	RemoveFavorite: function (removeFromFav, fn) {
		var that = this;
		if (!this.TwitterUserId && !this.FacebookUserId) {
			$.each(this.Favorites, function (i, item) {
				if (item.Type == removeFromFav.Type && item.Id == removeFromFav.Id) {
					App.Favorites.splice(i, 1);
					return false;
				}
			});

			$.cookie('AudisferaFavorites', Aes.Ctr.encrypt(JSON.stringify(this.Favorites), that.CryptPassword, 128), { expires: 365 })

			that.AfterRemoveFavorite(removeFromFav, fn);
		}
		else {
			$.getJSON(App.RootPath + 'Service/RemoveFavorite.ashx', { favorito: JSON.stringify(removeFromFav), FacebookUserId: that.FacebookUserId, TwitterUserId: that.TwitterUserId },
				function (ret) {
					if (ret.error) {
						that.ShowDialog({
							texto: '<p>' + ret.error + '</p>',
							buttons: {
								'Ok': function () {
									$(this).dialog('close');
								}
							}
						});
						return;
					}
					$.each(that.Favorites, function (i, item) {
						if (item.Type == removeFromFav.Type && item.Id == removeFromFav.Id) {
							App.Favorites.splice(i, 1);
							return false;
						}
					});
					that.AfterRemoveFavorite(removeFromFav, fn);
				});
		}
	},
	AfterRemoveFavorite: function (removeFromFav, fn) {
		if ($("#WidgetFavoritos").length > 0) {
			var widget = $("#WidgetFavoritos").data('widget');

			$('#' + removeFromFav.WidgetId + 'Favorites').find('#fav-' + removeFromFav.Id).remove();

			if ($("#WidgetFavoritos").find('#' + removeFromFav.WidgetId + 'Favorites').find('li').length <= 0) {
				$("#WidgetFavoritos").find('#' + removeFromFav.WidgetId + 'Favorites').remove();
			}
			widget.Check();

			var jsp = $("#WidgetFavoritos").find('.widgetScroll').data('jsp');
			if (jsp != null) {
				jsp.reinitialise();
			}
		}

		if (typeof fn === 'function') fn.call();
	},
	IsFavorite: function (Id, Type) {
		var favorite = JSLINQ(this.Favorites)
					.Where(function (item) { return item.Id == Id && item.Type == Type; })
					.Select(function (item) { return true });

		return favorite.items.length > 0 ? favorite.items : false;
	},
	CheckUser: function (data, callback) {
		var that = this;
		if (data.facebookUserId) App.FacebookUserId = data.facebookUserId;
		if (data.twitterUserId) App.TwitterUserId = data.twitterUserId;

		$.getJSON(App.RootPath + 'Service/CheckUser.ashx?nc=' + new Date().getTime(), data,
		function (ret) {
			if (ret.error) {
				this.ShowDialog({
					texto: '<p>' + ret.error + '</p>',
					buttons: {
						'Ok': function () {
							$(this).dialog('close');
						}
					}
				});
				return;
			}


			if (ret.code != 1 || that.Favorites.length <= 0) {
				that.CloseLoader();
			}

			if (ret.code == 1) {
				if (that.Favorites.length > 0) {
					that.SynchronizeFavorites(callback);
				}
				else {
					callback.call();
				}
			}
			else {
				that.Favorites = ret.favoritos || [];
				if (typeof callback === 'function') callback.call();
			}
		}
		);
	},
	SynchronizeFavorites: function (callback) {
		var that = this;
		this.ShowLoader({
			texto: $('<p />', { text: 'Sincronizando os favoritos' }),
			classe: 'view-loader-text',
			height: 'auto'
		});


		$.getJSON(App.RootPath + 'Service/SynchronizeFavorites.ashx',
			{
				favorites: JSON.stringify(that.Favorites),
				TwitterUserId: that.TwitterUserId,
				FacebookUserId: that.FacebookUserId
			},
			function (ret) {
				if (ret.error) {
					this.ShowDialog({
						texto: '<p>' + ret.error + '</p>',
						buttons: {
							'Ok': function () {
								$(this).dialog('close');
							}
						}
					});
					return;
				}
				that.CloseLoader();
				that.ShowDialog({
					texto: '<p>Seus favoritos foram sincronizados com sucesso.</p>',
					buttons: {
						'Ok': function () {
							$(this).dialog('close');
						}
					}
				});
				$.cookie('AudisferaFavorites', null);
				if (typeof callback === 'function') callback.call();
			}
		);
	},
	UpdateFavorites: function () {
		if (App.Favorites.length <= 0) return;
		App.ShowLoader({
			texto: $('<p />', { text: 'Carregando seus favoritos.' }),
			classe: 'view-loader-text',
			height: 'auto'
		});

		$('.widget[id!=WidgetFacebook]').each(function (i, item) {
			var wdg = $(item).data('widget');

			wdg.IsUpdate = true;
			wdg.Reset();
			wdg.Keywords = "";
			wdg.LoadContent();
		});

		App.CloseLoader();
	},
	TwitterPopup: null,
	ShowTwitterAuth: function (settings) {
		var w = screen.width;
		var h = screen.height;
		var popwid = 750;
		var pophei = 510;
		var leftPos = (w - popwid) / 2;
		var topPos = (h - pophei) / 2;

		this.ShowLoader({
			texto: $('<p />', { text: 'Conectando ao Twitter.' }),
			classe: 'view-loader-text',
			height: 'auto'
		});

		var data = '?action=' + settings.action;

		if (settings.message) data += '&message=' + settings.message;
		this.TwitterPopup = window.open('TwitterHandler.aspx' + data, '_blank', "directories=no,height=510,width=750,location=0,resizable=no,scrollbars=no,status=no,toolbar=no,left=" + leftPos + ",top=" + topPos);
	},
	CloseTwiterAuth: function (error) {
		this.TwitterPopup.close();
		this.TwitterPopup = null;
		this.CloseLoader();
		if (error) {
			$('.btLogin').closest('li').show();
			$("#txtUsuarioLogado").text("");
			this.ShowDialog({
				texto: '<p>' + error + '</p>',
				buttons: {
					'Ok': function () {
						$(this).dialog('close');
					}
				}
			});
		}
	},
	SetTwitterUser: function (twitterUserId, twitterUserName) {
		$('#twUserId').val(twitterUserId);
		$("#txtUsuarioLogado").text("Olá, " + twitterUserName);
		this.CloseTwiterAuth();
		this.CheckUser({
			twitterUserId: twitterUserId,
			nome: twitterUserName
		}, function () { $('.btLogin').closest('li').hide(); App.UpdateFavorites() });
	},
	FecharDestaque: function () {
		//$("#destaque-principal").addClass("closed").hide();
		$("#destaque-aberto").slideUp();
		$("#destaque-fechado").show("fast");
		$("#conteudo-principal").addClass("semDestaque");
	},
	AbrirDestaque: function () {
		$("#destaque-fechado").hide("fast", function () {
			$("#destaque-aberto").slideDown();
		});
		$("#conteudo-principal").removeClass("semDestaque");
	},
	ApplyAccordion: function (container) {
		$(container).accordion({
			autoHeight: false,
			collapsible: true,
			header: '> dt',
			icons: {
				header: "ui-icon",
				headerSelected: "ui-icon-selected"
			}
		});
	},
	Opts: null
};

var _Widget = function (settings) {
	var widget = new settings.type();

	if ($("#" + widget.WidgetId).length > 0) return;

	$('#menu-customize-pagina').find('input[value=' + widget.WidgetId + ']').next().addClass('checked');
	$('#menu-customize-pagina').find('input[value=' + widget.WidgetId + ']').attr('checked', true);

	widget.Create(settings);

	if (settings.saveCookie) App.Save();
}

var Widget = function (Type) {
	this.Scrollable = true;
	this.Closable = true;
	this.Container = null;
	this.ScrollClass = 'widgetScrollVertical';
	this.ScrollLimit = 0.8;
	this.Page = 1;
	this.TitleLimit = 55;
	this.ContentLimit = 165;
	this.Collapsible = false;
	this.IsUpdate = false;
	this.Keywords = '';
	this.InsertMode = 'append';
	this.EndReached = false;
	this.Callback = null;
}
.method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);

	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>')
		.append($('<div></div>', {
			className: 'widget-loading'
		}
		))
	)
	.data('widget', this);

	if (this.WidgetTitleImage) {
		$("dt", item).append($('<img />', {
			src: this.WidgetTitleImage,
			alt: this.WidgetTitle
		}));
	}
	else
		$("dt", item).wrap($('<span />', { className: 'title' })).text(this.WidgetTitle);

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })));
	}

	if (this.Scrollable) {
		$("dd", item).append($("<div></div>", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($('<ul />', { className: 'item-list' })));
	}
	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);
	this.Container = item;
	this.Callback = settings.callback;
	this.LoadContent();
})
.method("Move", function (toPosition) {
	var CurObj = $('#' + this.WidgetId);
	var WidgetObj = CurObj.data("widget");
	var ClonedObj = $('#' + this.WidgetId).remove();
	ClonedObj.data("widget", WidgetObj);

	var toColumn = App.ColNumber == 2 ? (toPosition - 1) % 2 : 2;

	toPosition = toPosition % App.ColNumber == 0 ? parseInt(toPosition / App.ColNumber, 10) - 1 : parseInt(toPosition / App.ColNumber, 10);

	if (toPosition >= $(App.Column + ':eq(' + toColumn + ') > *').length) {
		$(App.Column + ':eq(' + toColumn + ')').append(ClonedObj);
	}
	else {
		ClonedObj.insertBefore($(App.Column + ':eq(' + toColumn + ') dl:eq(' + toPosition + ')'));
	}
})
.method("LoadContent", function () {
	var that = this;
	$.getJSON(App.RootPath + 'Service/ListContent.ashx',
		{
			page: that.Page,
			socialId: that.SocialId,
			keywords: that.Keywords
		},
		function (Content) {
			that.Load(Content);
			that.AfterLoadContent();
		}
	);
})
.method("AfterLoadContent", function (Content) {
	this.IsUpdate = false;
	this.InsertMode = "append";

	this.Container.find('dt .close').unbind('click').bind('click', function (e) {
		e.preventDefault();
		var container = $(this).closest('.widget');
		var wdg = container.data('widget');
		wdg.Close();
	});
	if (this.Collapsible) {
		App.ApplyAccordion(this.Container);
	}

	if (typeof this.Callback === 'function') {
		this.Callback.call(this);
		this.Callback = null;
	}
})
.method("Load", function (Content) {
	var that = this;
	if (null != Content) {
		$.each(Content, function (i, item) {
			that.InsertContent(item);
		});
	} else this.EndReached = true;
	this.Show();
})
.method("InsertContent", function (item) {
	try {
		var newItem = $('<li />', {
			id: item.Id
		}).data("url", item.Url);

		if (item.Thumb) {
			newItem.append($('<span />', {
				className: 'img'
			})
				.append($('<a/>', {
					href: item.Url,
					target: '_blank',
					title: item.Title
				})
					.append($('<img />', {
						src: item.Thumb,
						alt: item.Title,
						width: this.ThumbWidth,
						height: this.ThumbHeight
					}))
				)
			);
		}

		var isFavorite = App.IsFavorite(item.Id, this.SocialId);

		newItem
			.append($('<h3/>', { text: this.LimitCheck(item.Title, this.TitleLimit) }))
			.append($('<p/>', { html: this.LimitCheck(this.CleanTags(item.Content), this.ContentLimit) }))
			.append($('<div />', {
				className: 'addthis_default'
			})
				.append($('<a />', {
					className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
					href: ''
				})
					.append($('<img />', {
						src: 'Util/Img/v2/Widget/favorite-loader.gif',
						alt: 'Carregando',
						width: 15,
						height: 15,
						className: 'favorite-loading'
					})))
				.append($('<span />', {
					className: 'fblike'
				}))
				.append($('<span />', {
					className: 'tweet'
				}))
			);
		if (this.InsertMode == 'prepend') {
			$("ul", this.Container).prepend(newItem);
		}
		else {
			$("ul", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("LimitCheck", function (Content, Limit) {
	if (!Limit) return;
	if (Content.length > Limit) {
		Content = Content.substring(0, Limit) + '...';

	}
	return Content;
})
.method("CleanTags", function (Content) {
	return Content.replace(/<\/?[^>]+(>|$)/g, "");
})
.method("Show", function (item) {
	var that = this;

	if (this.Scrollable)
		this.ApplyScroll();
	this.Check();

	$("ul li", this.Container).unbind("click").bind("click", function (e) {
		if ($(this).hasClass('share')) return;
		if (e.target.tagName.toLowerCase() == 'a' || $(e.target).closest('a').length > 0) return true;
		that.ShowContent(this);
	});

	$(".widget-loading", this.Container).hide();
})
.method("Check", function () {
	if (!this.IsUpdate && $("ul li", this.Container).length <= 0) {
		$("ul", this.Container).append($('<li/>', { className: 'nocontent', text: 'Nenhum conteúdo encontrado' }));
	}
})
.method("ApplyScroll", function () {
	var that = this;

	var jsp = $(".widgetScroll", this.Container).data('jsp');
	if (jsp != null) {
		jsp.reinitialise();
		return;
	}

	$(".widgetScroll", this.Container).removeData('totalHeight').hide().show().jScrollPane({
		scrollbarWidth: 24,
		verticalDragMinHeight: 43,
		verticalDragMaxHeight: 43,
		verticalGutter: 0,
		showArrows: true
	}).bind(
		'jsp-scroll-y',
		function (event, scrollPositionY, isAtBottom, isAtTop) {
			if (!that.IsUpdate) {

				var totalHeight = $(this).data("totalHeight") || $(".jspPane", this).height();
				var scrollY = scrollPositionY + $(this).height();

				$(this).data("totalHeight", totalHeight);
				if ((scrollY / totalHeight) > that.ScrollLimit) {

					var scroll = $(this);

					that.IsUpdate = true;
					that.Page++;
					scroll.removeData('totalHeight');
					that.LoadContent();
				}
			}
		}
	);
})
.method("ShowContent", function (list) {
	var that = this;

	var listItem = $(list, this.Container);

	if (App.IsFacebook) {
		window.open(listItem.data("url"), "_blank", "");
		return;
	}

	$('#view-loader').dialog({
		modal: true,
		resizable: false,
		dialogClass: 'view-loader-container',
		width: 220,
		height: 19
	});

	$.getJSON(App.RootPath + "Service/GetContent.ashx", { id: list.id.replace(/[^0-9]+/, '') },
	function (item) {
		if (!item || item == null) return;

		var Share = $('<div />', {
			className: 'addthis_toolbox'
		});

		var isFavorite = $('.add_favorite', listItem).hasClass('on') || (listItem.closest('#WidgetFavoritos').length > 0);

		Share.append($('<ul />')
		.append($('<li/>', { className: 'like' })
			.append($('<a />', {
				className: 'addthis_button_facebook_like',
				'addthis:url': item.Url,
				'fb:like:layout': 'button_count',
				'fb:like:width': 85
			}))
		)
		.append($('<li/>', { className: 'tweet' })
			.append($('<a />', {
				className: 'addthis_button_tweet',
				'addthis:url': item.Url,
				'tw:width': 96
			}))
		)
		.append($('<li/>', { className: 'email' })
			.append($('<a />', {
				className: 'addthis_button_email',
				'addthis:url': item.Url
			}))
		)
		.append($('<li/>', { className: 'share-more' })
			.append($('<a />', {
				className: 'addthis_button',
				'addthis:url': item.Url,
				href: 'http://www.addthis.com/bookmark.php',
				html: '<img src="Util/Img/v2/Misc/btViewMore.gif" alt="Mais" />'
			}))
		)
		.append($('<li/>', { className: 'share-link' })
			.append($('<a />', {
				className: 'share_link',
				target: '_blank',
				title: 'Ir para o link original',
				href: item.Url
			}))
		)
		.append($('<li/>', { className: 'sep' }))
		.append($('<li/>', { className: 'share_favorite' })
			.append($('<a />', {
				className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
				href: ''
			})
			.append($('<img />', {
				src: 'Util/Img/v2/Widget/favorite-loader-view.gif',
				alt: 'Carregando',
				width: 25,
				height: 25,
				className: 'favorite-loading'
			})))
		));

		$('#view-share').html(Share);

		window.addthis.ost = 0;
		window.addthis.ready();

		$('#view-content *').remove();
		$('#view-content').append($('<h3 />', {
			'class': 'TitleAudisfera',
			'text': item.Title
		}));

		$('#view-content').append(that.Paragraphfy(item.Content.replace(/width\=\"[0-9]+\"/ig, 'width="640"').replace(/height\=\"[0-9]+\"/ig, 'height="385"')));

		$('#view-loader').dialog('close');

		var dialogClass = "ViewItem" + that.WidgetId
		$('#view-item').dialog({
			modal: true,
			resizable: false,
			title: that.WidgetTitle,
			dialogClass: 'view-item-container ' + dialogClass,
			width: 700,
			height: 'auto',
			open: function (event, ui) {
				$('#view-item').data('Item', list);
			},
			beforeClose: function (event, ui) {
				if ($('#view-share').find('.add_favorite').hasClass('on')) {
					$('.add_favorite', listItem).addClass('on');
				}
				else {
					$('.add_favorite', listItem).removeClass('on');
				}
			}
		});
	});
})
.method("Paragraphfy", function (t) {
	t = $.trim(t);
	return (t.length > 0 ? '<p>' + t.replace(/[\r\n]+/, '</p><p>') + '</p>' : t);
})
.method("Reset", function () {
	$(this.Container).find('dd ul li').remove();
	this.Page = 1;
	this.EndReached = false;
	$(".widget-loading", this.Container).show();
})
.method("Close", function () {
	var that = this;
	$(this.Container).slideUp('normal', function () {
		$(this).remove();

		if ($('#menu-customize-pagina').find('.all input').is(':checked')) {
			$('#menu-customize-pagina').find('.all label').removeClass('checked');
			$('#menu-customize-pagina').find('.all input').attr('checked', false);
		}

		$('#menu-customize-pagina').find('input[value=' + that.WidgetId + ']').next().removeClass('checked');
		$('#menu-customize-pagina').find('input[value=' + that.WidgetId + ']').attr('checked', false);

		App.Save();
	});
})
.method("AddFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#view-share').length > 0) ? jQuery(jQuery('#view-item').data("Item")).closest('li') : $(item).closest('li');
	var addToFav = {};
	addToFav.Id = listItem.attr('id');
	addToFav.Title = listItem.find('h3').text();
	addToFav.Type = this.SocialId;
	addToFav.WidgetTitle = this.WidgetTitle;
	addToFav.WidgetId = this.WidgetId;

	App.AddFavorite(addToFav, function () {
		that.AfterAddFavorite(item);
	});
})
.method("AfterAddFavorite", function (item) {
	$(item).addClass('on');
	$(item).removeClass('loading');
})
.method("RemoveFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#view-share').length > 0) ? jQuery(jQuery('#view-item').data("Item")).closest('li') : $(item).closest('li');
	var removeFromFav = {};
	removeFromFav.Id = listItem.attr('id');
	removeFromFav.Type = this.SocialId;
	removeFromFav.WidgetId = this.WidgetId;

	App.RemoveFavorite(removeFromFav, function () {
		that.AfterRemoveFavorite(item);
	});
})
.method("AfterRemoveFavorite", function (item) {
	$(item).removeClass('on');
	$(item).removeClass('loading');
});

/* TWITTER */
var WidgetTwitter = function () {
	this.WidgetTitle = "Twitter";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titTwitter.png"
	this.SocialId = 'TWITTER';
	this.WidgetId = "WidgetTwitter";
	this.ThumbWidth = 73;
	this.ThumbHeight = 73;
	this.ContentLimit = 0;
	this.HelpText = "Confira o que as pessoas estão falando sobre a Audi no Twitter.";
	this.CanAddFavorite = false;
}
.inherits(Widget)
.method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);

	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>')
		.append($('<div></div>', {
			className: 'widget-loading'
		}
		))
	)
	.data('widget', this);

	if (this.WidgetTitleImage) {
		$("dt", item).append($('<img />', {
			src: this.WidgetTitleImage,
			alt: this.WidgetTitle
		}));
	}
	else
		$("dt", item).wrap($('<span />', { className: 'title' })).text(this.WidgetTitle);

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })))
		.append($('<ul />', { className: 'abas' })
			.append($('<li />', { className: 'active first' })
				.append($('<a />', { title: 'Menções', href: '#mencoes', text: 'Menções' }))
			)
			.append($('<li />', { className: 'posactive' })
				.append($('<a />', { title: 'AudiBr', href: '#audibr', text: 'AudiBr' }))
			)
			.append($('<li />', { className: 'last' })
				.append($('<a />', { title: 'Guto Kleien', href: '#gutokleien', text: 'Guto Kleien' }))
			)
		);

		item.find('dt ul a').unbind('click').bind("click", function (e) {
			e.preventDefault();
			var targetLi = $(this).closest('li');
			if (targetLi.hasClass('active')) return;

			that.Reset();
			$(this).closest('dt').find('.active').removeClass('active');
			$(this).closest('dt').find('.posactive').removeClass('posactive');

			targetLi.addClass('active');
			targetLi.next('li').addClass('posactive');
			that.ChangeTab($(this).attr('href'));
		});
	}

	if (this.Scrollable) {
		$("dd", item).append($("<div></div>", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($('<ul />', { className: 'item-list' })));
	}
	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);
	this.Container = item;
	this.Callback = settings.callback;

	currentTab = this.Container.find('dt .active a').attr('href');
	that.ChangeTab(currentTab);
})
.method("ChangeTab", function (tab) {
	var that = this;
	that.CurrentTab = tab;

	if (this.IsUpdate == false) {
		var jsp = $(".widgetScroll", this.Container).data('jsp');

		if (jsp != null) {
			jsp.scrollToY(0, false);
		}
	}

	switch (tab) {
		case '#audibr':
			$.getJSON(App.RootPath + "Util/Json/AudiBrTweets.json", function (Content) {
				that.CanAddFavorite = false;
				that.Data = Content;
				that.LoadContent();
			});
			break;
		case '#gutokleien':
			$.getJSON(App.RootPath + "Util/Json/GutoKleienTweets.json", function (Content) {
				that.CanAddFavorite = false;
				that.Data = Content;
				that.LoadContent();
			});
			break;
		default:
			$.getJSON(App.RootPath + 'Service/ListContent.ashx', { page: that.Page, socialId: that.SocialId, keywords: that.Keywords },
			function (Content) {
				that.CanAddFavorite = true;
				that.Load(Content);
				that.AfterLoadContent();
			});
			break;
	}
})
.method("LoadContent", function () {
	var that = this;

	var TwData = this.Data.splice(((that.Page - 1) * 10), 10);

	that.Load(TwData);
	that.AfterLoadContent();
})
.method("AfterLoadContent", function () {
	$('.timestamp abbr', this.Container).timeago();

	this.IsUpdate = false;
	this.InsertMode = "append";

	this.Container.find('dt .close').unbind('click').bind('click', function (e) {
		e.preventDefault();
		var container = $(this).closest('.widget');
		var wdg = container.data('widget');
		wdg.Close();
	});

	if (this.Collapsible) {
		App.ApplyAccordion(this.Container);
	}

	if (typeof this.Callback === 'function') {
		this.Callback.call(this);
		this.Callback = null;
	}
})
.method("InsertContent", function (item) {
	try {
		var newItem = $('<li />', {
			id: item.Id
		});

		newItem.append($('<div />', { className: 'item-wrapper' }));

		if (item.Thumb) {
			$('.item-wrapper', newItem).append($('<span />', {
				className: 'img'
			})
					.append($('<img />', {
						src: item.Thumb,
						alt: item.Creator,
						width: this.ThumbWidth,
						height: this.ThumbHeight
					}))
			);
		}

		var isFavorite = App.IsFavorite(item.Id, this.SocialId);

		$('.item-wrapper', newItem).append($('<h3/>')
			.append($('<a></a>', {
				href: item.Url,
				target: '_blank',
				title: item.Creator,
				text: '@' + item.Creator
			})))
			.append($('<p/>', {
				html: item.Content
			})
			).append($('<span/>', {
				className: 'timestamp'
			})
				.append($('<abbr />', {
					title: item.PubDate+ ' -300'
				}))); /*
				.append($('<a/>', {
					href: item.Url,
					target: '_blank',
					title: item.Creator,
					text: 
				}))
			);*/
		if (this.CanAddFavorite === true) {
			newItem.find('.timestamp').prepend($('<a />', {
				className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
				href: ''
			})
			.append($('<img />', {
				src: 'Util/Img/v2/Widget/favorite-loader.gif',
				alt: 'Carregando',
				width: 15,
				height: 15,
				className: 'favorite-loading'
			})));
		}

		if (this.InsertMode == 'prepend') {
			$("dd ul", this.Container).prepend(newItem);
		}
		else {
			$("dd ul", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("Linkify", function (statusText) {
	var statusText = statusText.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function (url) {
		return '<a href="' + url + '">' + url + '</a>';
	}).replace(/\B@([_a-z0-9]+)/ig, function (reply) {
		return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
	}).replace(/\B#([_a-z0-9]+)/ig, function (search) {
		return search.charAt(0) + '<a href="http://twitter.com/#!/search/%23' + search.substring(1) + '">' + search.substring(1) + '</a>';
	});
	return statusText;
})
.method("ApplyScroll", function () {
	var that = this;
	var jsp = $(".widgetScroll", this.Container).data('jsp');
	$(".widgetScroll", this.Container).removeData('totalHeight');
	if (jsp != null) {
		jsp.reinitialise();
		return;
	}

	$(".widgetScroll", this.Container).removeData('totalHeight').hide().show().jScrollPane({
		scrollbarWidth: 24,
		verticalDragMinHeight: 43,
		verticalDragMaxHeight: 43,
		verticalGutter: 0,
		showArrows: true
	}).bind(
		'jsp-scroll-y',
		function (event, scrollPositionY, isAtBottom, isAtTop) {
			if (!that.IsUpdate) {

				var totalHeight = $(this).data("totalHeight") || $(".jspPane", this).height();
				var scrollY = scrollPositionY + $(this).height();

				$(this).data("totalHeight", totalHeight);
				if ((scrollY / totalHeight) > that.ScrollLimit) {
					var scroll = $(this);

					that.IsUpdate = true;
					that.Page++;
					scroll.removeData('totalHeight');

					if (that.CurrentTab == "#mencoes" || !that.Data) that.ChangeTab(that.CurrentTab);
					else that.LoadContent();
				}
			}
		}
	);
})
.method("ShowContent", function (list) {
	var that = this;
	var listItem = $(list, this.Container);
	var item = {};
	item.Url = $('h3 a', listItem).attr('href');

	var Share = $('<div />', {
		className: 'addthis_toolbox'
	});

	var isFavorite = $('.timestamp .add_favorite', listItem).hasClass('on') || (listItem.closest('#WidgetFavoritos').length > 0);

	Share.append($('<ul />')
	    .append($('<li/>', { className: 'like' })
		    .append($('<a />', {
		    	className: 'addthis_button_facebook_like',
		    	'addthis:url': item.Url,
		    	'fb:like:layout': 'button_count',
		    	'fb:like:width': 85
		    }))
	    )
	    .append($('<li/>', { className: 'tweet' })
		    .append($('<a />', {
		    	className: 'addthis_button_tweet',
		    	'addthis:url': item.Url,
		    	'tw:width': 96
		    }))
	    )
	    .append($('<li/>', { className: 'email' })
		    .append($('<a />', {
		    	className: 'addthis_button_email',
		    	'addthis:url': item.Url
		    }))
	    )
	    .append($('<li/>', { className: 'share-more' })
		    .append($('<a />', {
		    	className: 'addthis_button',
		    	'addthis:url': item.Url,
		    	href: 'http://www.addthis.com/bookmark.php',
		    	html: '<img src="' + App.ImagePath + '/Misc/btTwitterMore.gif" alt="Mais" />'
		    }))
	    )
	    .append($('<li/>', { className: 'share-link' })
		    .append($('<a />', {
		    	className: 'share_link',
		    	target: '_blank',
		    	title: 'Ir para o link original',
		    	href: item.Url
		    }))
	    ));

	if (this.CanAddFavorite === true) {
		Share.find('ul')
		.append($('<li/>', { className: 'sep' }))
	    .append($('<li/>', { className: 'share_favorite' })
		    .append($('<a />', {
		    	className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
		    	href: ''
		    })
					.append($('<img />', {
						src: 'Util/Img/v2/Widget/favorite-loader-twitter.gif',
						alt: 'Carregando',
						width: 25,
						height: 25,
						className: 'favorite-loading'
					})))
	    )
		Share.removeClass('no-favorite');
	}
	else {
		Share.addClass('no-favorite');
	}

	Share.append($('<a />', { href: '', title: 'Voltar', id: 'btVoltarTwitter' }).append($('<img />', { src: App.ImagePath + '/Widget/btVoltarTwitter.gif', alt: 'Voltar' })));

	listItem.addClass('share').prepend(Share);

	$('.item-wrapper', listItem).hide("slide", { direction: "right" }, 1000, function () {
		window.addthis.ost = 0;
		window.addthis.ready();
	});

	$("#btVoltarTwitter").unbind('click').bind("click", function (e) {
		e.preventDefault();
		$('.item-wrapper', listItem).show("slide", { direction: "right" }, 1000, function () {
			if ($('.addthis_toolbox .add_favorite', listItem).hasClass('on')) {
				$('.timestamp .add_favorite', listItem).addClass('on');
			}
			else {
				$('.timestamp .add_favorite', listItem).removeClass('on');
			}

			$('.addthis_toolbox', listItem).remove();
			listItem.removeClass('share');
		});
	});
})
.method("AddFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#WidgetTwitter .timestamp').length > 0) ? $(item).closest('li') : $(item).closest('li.share');

	var addToFav = {};
	addToFav.Id = listItem.attr('id');
	addToFav.Title = listItem.find('h3').text() + ': ' + listItem.find('p').html();
	addToFav.Type = this.SocialId;
	addToFav.WidgetTitle = this.WidgetTitle;
	addToFav.WidgetId = this.WidgetId;

	App.AddFavorite(addToFav, function () {
		that.AfterAddFavorite(item);
	});
})
.method("RemoveFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#WidgetTwitter .timestamp').length > 0) ? $(item).closest('li') : $(item).closest('li.share');

	var removeFromFav = {};
	removeFromFav.Id = listItem.attr('id');
	removeFromFav.Type = this.SocialId;
	removeFromFav.WidgetId = this.WidgetId;

	App.RemoveFavorite(removeFromFav, function () {
		that.AfterRemoveFavorite(item);
	});
});

/* FACEBOOK */
var WidgetFacebook = function () {
	this.WidgetTitle = "Facebook";
	this.SocialId = 'FACEBOOK';
	this.WidgetTitleImage = App.ImagePath + '/Widget/titFacebook.png';
	this.WidgetId = "WidgetFacebook";
	this.Data = null;
	this.HelpText = "Saiba quais assuntos o pessoal está curtindo nos perfis oficiais da Audi."
}
.inherits(Widget)
.method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);
	that = this;

	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>')
		.append($('<div></div>', {
			className: 'widget-loading'
		}
		))
	)
	.data('widget', this);

	if (this.WidgetTitleImage) {
		$("dt", item).append($('<img />', {
			src: this.WidgetTitleImage,
			alt: this.WidgetTitle
		}));
	}
	else
		$("dt", item).wrap($('<span />', { className: 'title' })).text(this.WidgetTitle);

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })))
		.append($('<ul />', { className: 'abas' })
			.append($('<li />', { className: 'active first' })
				.append($('<a />', { title: 'Audi Brasil', href: '#audibr', text: 'Audi Brasil' }))
			)
			.append($('<li />', { className: 'posactive last' })
				.append($('<a />', { title: 'Audi A1', href: '#audia1', text: 'Audi A1' }))
			)
		);
	}

	if (this.Scrollable) {
		$("dd", item).append($("<div />", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($('<div />', { id: 'facebook-header', className: 'addthis_toolbox' })
			.append($('<a />', { className: 'thumb', href: '', target: '_blank' })
				.append($('<img />'))
			)
			.append($('<a />', { className: 'title', href: '', target: '_blank' }))
		)
		.append($('<ul />', { className: 'item-list' }))
		.append($('<div />', { id: 'facebook-single' })));
	}

	item.find('dt ul a').unbind('click').bind("click", function (e) {
		e.preventDefault();
		var targetLi = $(this).closest('li');
		if (targetLi.hasClass('active')) return;

		that.Reset();
		$(this).closest('dt').find('.active').removeClass('active');
		$(this).closest('dt').find('.posactive').removeClass('posactive');

		targetLi.addClass('active');
		targetLi.next('li').addClass('posactive');
		that.ChangeTab($(this).attr('href'));
	});

	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);

	this.Container = item;
	this.Callback = settings.callback;

	currentTab = this.Container.find('dt .active a').attr('href');
	that.ChangeTab(currentTab);
})
.method("ChangeTab", function (tab) {
	var that = this;
	that.CurrentTab = tab;
	$("#facebook-header").find('.addthis_button_facebook_like, .atclear').remove();
	
	switch (tab) {
		case '#audibr':
			$("#facebook-header").find('a').not('.addthis_button_facebook_like').attr('href', 'http://www.facebook.com/audibrasil');
			$("#facebook-header").find('.title').text('Audi Brasil');

			$("#facebook-header").append($('<a />', {
				className: 'addthis_button_facebook_like',
				'fb:like:layout': 'button_count',
				'addthis:url': 'http://www.facebook.com/audibrasil'
			}));
			$("#facebook-header").find('a img').attr({ src: 'Util/Img/v2/Widget/thumbAudiBr.jpg', alt: "Audi Brasil" });
			$.getJSON(App.RootPath + "Util/Json/FacebookAudiBr.json", function (Content) {
				that.Data = Content.data;
				that.LoadContent();
			});
			break;
		case '#audia1':
			$("#facebook-header").find('a').not('.addthis_button_facebook_like').attr('href', 'http://www.facebook.com/audia1brasil');
			$("#facebook-header").find('.title').text('Audi A1 Brasil');

			$("#facebook-header").append($('<a />', {
				className: 'addthis_button_facebook_like',
				'fb:like:layout': 'button_count',
				'addthis:url': 'http://www.facebook.com/audia1brasil'
			}));
			$("#facebook-header").find('a img').attr({ src: 'Util/Img/v2/Widget/iconeA1.jpg', alt: "Audi A1 Brasil" });
			$.getJSON(App.RootPath + "Util/Json/FacebookAudiA1.json", function (Content) {
				that.Data = Content.data;
				that.LoadContent();
			});
			break;
	}

	window.addthis.ost = 0;
	window.addthis.ready();
})
.method("LoadContent", function () {
	var that = this;
	
	var FbData = this.Data.splice(((that.Page - 1) * 10), 10);

	that.Load(FbData);
	that.AfterLoadContent();
})
.method("Show", function (item) {
	var that = this;

	if (this.Scrollable)
		$('.img img', that.Container).unbind('load').bind('load', function () { that.ApplyScroll() });
	this.Check();

	$("ul li", this.Container).not('.nocontent').unbind("click").bind("click", function (e) {
		if (e.target.tagName.toLowerCase() == 'a' || $(e.target).closest('a').length > 0) {
			return true;
		}
		that.ShowContent(this);
	});

	$("a.share", this.Container).unbind("click").bind("click", function (e) {
		e.preventDefault();
		var listItem = $(this).parents('li')[1];
		var name = $('.media h3', listItem).text();
		var caption = $('.caption', listItem).text();
		var desc = $(".description", listItem).text();
		var message = $(".item-wrapper > p", listItem).text();
		var link = "http://www.audisfera.com.br";

		var opts = {
			method: 'feed',
			link: link,
			caption: caption,
			description: message || name,
			message: desc
		};

		FB.ui(opts);
	});

	$(".widget-loading", this.Container).hide();
})
.method("AfterLoadContent", function (Content) {
	if (this.IsUpdate == false) {
		var jsp = $(".widgetScroll", this.Container).data('jsp');
		$(".widgetScroll", this.Container).removeData('totalHeight');
		if (jsp != null) {
			jsp.scrollToY(0, false);
		}
	}
	
	this.IsUpdate = false;
	this.InsertMode = "append";
	
	this.Container.find('dt .close').unbind('click').bind('click', function (e) {
		e.preventDefault();
		var container = $(this).closest('.widget');
		var wdg = container.data('widget');
		wdg.Close();
	});

	if (this.Collapsible) {
		App.ApplyAccordion(this.Container);
	}

	if (typeof this.Callback === 'function') {
		this.Callback.call(this);
		this.Callback = null;
	}
})
.method("InsertContent", function (item) {
	var that = this;
	try {
		var newItem = $('<li />', {
			id: item.id
		}).append($('<div />', { className: 'item-wrapper' }));


		if (item.message) {
			var facebookUrl, facebookTitle;
			if (that.CurrentTab == '#audia1') {
				facebookUrl = 'http://www.facebook.com/audia1brasil';
				facebookTitle = 'Audi A1 Brasil';
			}

			if (that.CurrentTab == '#audibr') {
				facebookUrl = 'http://www.facebook.com/audibrasil';
				facebookTitle = 'Audi Brasil';
			}
			newItem.find('.item-wrapper')
			.append($('<p/>', { text: ' ' + item.message })
				.prepend($('<a />', { href: facebookUrl, title: facebookTitle, text: facebookTitle, target: '_blank' }))
			);
		}

		if (item.picture || (!item.message && (item.description || item.name))) {
			newItem.find('.item-wrapper').append($('<br />', { className: 'clear' }));
			newItem.find('.item-wrapper').append($('<span />', {
				className: 'media ' + item.type
			}));

			if (item.picture)

				newItem.find('.media').append($('<span />', {
					className: 'img'
				}).append($('<img />', {
					src: item.picture
				})));

			if (item.name) {
				newItem.find('.media')
					.append($('<h3/>', { text: item.name }));
			}

			if (item.caption) {
				newItem.find('.media')
					.append($('<span />', { text: item.caption, className: 'caption' }))
			}

			if (item.description) {
				newItem.find('.media')
					.append($('<p />', { text: item.description, className: 'description' }))
			}
		}
		newItem.find('.item-wrapper').append($('<br />', { className: 'clear' }));

		newItem.find('.item-wrapper').append($('<span />', { className: 'streamFooter' }));

		if (item.icon) {
			newItem.find('.streamFooter')
				.append($('<span />', { className: 'fb-icon' })
					.append($('<img />', { src: item.icon }))
				);
		}
		newItem.find('.streamFooter').append($('<a />', { href: item.link, className: 'created_time', target: '_blank' })
			.append($('<abbr />', { text: this.fuzzyFacebookTime(item.created_time.replace(/-/gi, "/")) })));

		newItem.find('.streamFooter').append($('<ul />')
			.append($('<li />',
				{
					className: 'comments',
					text: item.comments.count
				}))
			.append($('<li />',
				{
					className: 'likes',
					text: item.likes.count
				}))
			.append($('<li />', { className: 'sep' }))
			.append($('<li />')
				.append($('<a />', { className: 'share', href: '', text: 'Compartilhar' }))
			));

		if (this.InsertMode == 'prepend') {
			$(".item-list", this.Container).prepend(newItem);
		}
		else {
			$(".item-list", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("fuzzyFacebookTime", function (timeValue) {
	fuzzyTime.defaultOptions = {
		// time display options
		relativeTime: 48,
		// language options
		monthNames: ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro', 'novembro', 'dezembro'],
		amPm: ['AM', 'PM'],
		ordinalSuffix: function (n) { return ['th', 'st', 'nd', 'rd'][n < 4 || (n > 20 && n % 10 < 4) ? n % 10 : 0] }
	}
	function fuzzyTime(timeValue, options) {
		var options = options || fuzzyTime.defaultOptions, date = parseDate(timeValue), delta = parseInt(((new Date()).getTime() - date.getTime()) / 1000), relative = options.relativeTime, cutoff = +relative === relative ? relative * 60 * 60 : Infinity;

		if (relative === false || delta > cutoff)
			return formatDate(date, options) + ' às ' + formatTime(date, options);
		if (delta < 60) return 'há menos de um minuto';
		var minutes = parseInt(delta / 60 + 0.5);
		if (minutes <= 1) return 'há um minuto';
		var hours = parseInt(minutes / 60 + 0.5);
		if (hours < 1) return 'há ' + minutes + ' minutos';
		if (hours == 1) return 'há uma hora';
		var days = parseInt(hours / 24 + 0.5);
		if (days < 1) return 'há ' + hours + ' horas';
		if (days == 1) return formatTime(date, options) + ' ontem';
		var weeks = parseInt(days / 7 + 0.5);
		if (weeks < 2) return 'há ' + formatTime(date, options) + ' ' + days + ' dias';
		var months = parseInt(weeks / 4.34812141 + 0.5);
		if (months < 2) return 'há ' + weeks + ' semanas';
		var years = parseInt(months / 12 + 0.5);
		if (years < 2) return 'há ' + months + ' meses';
		return 'há ' + years + ' anos';
	}
	function parseDate(str) {
		var v = str.replace(/[T\+]/g, ' ').split(' ');
		return new Date(Date.parse(v[0] + " " + v[1])).addHours(-3);
	}
	function formatTime(date, options) {
		var h = date.getHours(), m = '' + date.getMinutes(), am = options.amPm;
		return h + ':' + (m.length == 1 ? '0' : '') + m + ' ';
	}
	function formatDate(date, options) {
		var mon = options.monthNames[date.getMonth()], day = date.getDate(), year = date.getFullYear(), thisyear = (new Date()).getFullYear(), suf = options.ordinalSuffix(day);
		return day + ' de ' + mon + (thisyear != year ? ', ' + year : '');
	}
	return fuzzyTime;
} ())
.method("ShowContent", function (list) {
	var that = this;
	var listItem = $(list, this.Container);

	var jsp = $(".widgetScroll", this.Container).data('jsp');

	if (jsp != null) {
		jsp.scrollToY(0, false);
	}

	//var item = {};
	var Url = $('.created_time', listItem).attr('href');
	var content = listItem.find('.item-wrapper').clone();

	content.find('ul').remove();
	content.append($('<div />', { className: 'addthis_toolbox' })
		.append($('<a />', {
			className: 'addthis_button_facebook_like',
			'addthis:url': Url,
			'fb:like:layout': 'button_count',
			'fb:like:width': 85
		}))
		.append($('<a />', { href: '', title: 'Voltar', id: 'btVoltarFacebook' })
			.append($('<img />', { src: App.ImagePath + '/Widget/btVoltarFacebook.gif', alt: 'Voltar' })))
	);

	$("#facebook-single").html(content.html());

	$('#facebook-single').show("slide", { direction: "right" }, 1000, function () {
		$(this).css('position', 'static');
		listItem.closest('ul').hide();
		window.addthis.ost = 0;
		window.addthis.ready();

		if (jsp != null) { jsp.reinitialise(); }
	});

	$("#btVoltarFacebook").unbind("click").bind("click", function (e) {
		e.preventDefault();
		$("#facebook-single").css('position', 'absolute');
		listItem.closest('ul').show();
		$("#facebook-single").hide("slide", { direction: "right" }, 1000, function () {
			$(this).html("");
			if (jsp != null) { jsp.reinitialise(); }
		});
	});
});

/* YOUTUBE */
var WidgetYoutube = function () {
	this.WidgetTitle = "Youtube";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titYoutube.png";
	this.SocialId = 'YOUTUBE';
	this.WidgetId = "WidgetYoutube";
	this.ScrollClass = 'widgetScrollHorizontal';
	this.ThumbWidth = 98;
	this.ThumbHeight = 68;
	this.ContentLimit = 0;
	this.HelpText = "Assista os comerciais, test drives, comparativos e muito mais."
}
.inherits(Widget)
.method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);
	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>', {
		id: 'youtubeVideo'
	})
		.append($('<div />', {
			className: 'widget-loading'
		}))
		.append($('<div />', { id: 'youtube-share' }))
	)
	.append($('<dd></dd>', {
		id: 'youtubeGallery'
	})).data('widget', this);


	$("dt", item).append($('<span />').append($('<img />', {
		src: this.WidgetTitleImage,
		alt: this.WidgetTitle
	})));

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })));
	}

	if (this.Scrollable) {
		$("#youtubeGallery", item).append($("<div></div>", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($('<ul />')))
		.append($('<span />', {
			title: 'Anterior',
			className: 'btArrow btArrowLeft',
			text: 'Anterior'
		}))
		.append($('<span />', {
			title: 'Próximo',
			className: 'btArrow btArrowRight',
			text: 'Próximo'
		}));
	}


	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);
	this.Container = item;
	this.Callback = settings.callback;
	this.LoadContent();
})
.method("AfterLoadContent", function () {
	if (!this.Callback) {
		$('ul li:eq(0) > a', this.Container).click();
	}
	this.IsUpdate = false;
	this.InsertMode = "append";

	this.Container.find('dt .close').bind('click', function (e) {
		e.preventDefault();
		var container = $(this).closest('.widget');
		var wdg = container.data('widget');
		wdg.Close();
	});

	if (this.Collapsible) {
		App.ApplyAccordion(this.Container);
	}

	if (typeof this.Callback === 'function') {
		this.Callback.call(this);
		this.Callback = null;
	}
})
.method("InsertContent", function (item) {
	try {
		var newItem = $('<li />', {
			id: item.Id
		});

		var isFavorite = App.IsFavorite(item.Id, this.SocialId);

		newItem.append($('<a/>', {
			href: item.Url,
			target: '_blank',
			title: item.Title
		})
			.append($('<img />', {
				src: item.Thumb,
				alt: item.Title,
				width: this.ThumbWidth,
				height: this.ThumbHeight
			}))
			.append($('<a />', {
				className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
				href: ''
			})
					.append($('<img />', {
						src: 'Util/Img/v2/Widget/favorite-loader.gif',
						alt: 'Carregando',
						width: 31,
						height: 31,
						className: 'favorite-loading'
					})))
		)

		if (this.InsertMode == 'prepend') {
			$("#youtubeGallery ul", this.Container).prepend(newItem);
		}
		else {
			$("#youtubeGallery ul", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("Check", function () {

	if (!this.IsUpdate && $("ul li", this.Container).length <= 0) {
		$("#youtubeVideo", this.Container).append($('<p/>', { className: 'nocontent', text: 'Nenhum conteúdo encontrado' }));
		$(".btArrow", this.Container).hide();
	}
	else $(".btArrow", this.Container).css('display', 'block');
})
.method("Show", function (item) {
	var that = this;
	var listWidth = parseInt($("#youtubeGallery", this.Container).find("ul li:eq(0)").width(), 10) + parseInt($("#youtubeGallery", this.Container).find("ul li:eq(0)").css("margin-left"), 10) + parseInt($("#youtubeGallery", this.Container).find("ul li:eq(0)").css("margin-right"), 10);
	$("ul", this.Container).width($("#youtubeGallery", this.Container).find("ul li").length * listWidth);

	if (this.Scrollable)
		this.ApplyScroll();
	this.Check();

	$("#youtubeGallery", this.Container).find("ul li a").unbind("click").bind("click", function (e) {
		e.preventDefault();
		if ($(e.target).hasClass('add_favorite')) return;
		that.ShowContent(this);
	});

	$(".widget-loading", this.Container).hide();
})
.method("ApplyScroll", function () {
	var that = this;

	var jsp = $(".widgetScroll", this.Container).data('jsp');
	if (jsp != null) {
		jsp.reinitialise();
		return;
	}

	var api = $(".widgetScroll", this.Container).removeData('totalWidth').hide().show().jScrollPane({
		scrollbarWidth: 24,
		verticalDragMinHeight: 43,
		verticalDragMaxHeight: 43,
		verticalGutter: 0,
		showArrows: false
	}).bind(
		'jsp-scroll-x',
		function (event, scrollPositionX, isAtRight, isAtLeft) {
			if (!that.IsUpdate && !that.EndReached) {

				var totalWidth = $(this).data("totalWidth") || $("ul", this).width();
				var scrollX = scrollPositionX + $(this).width();

				$(this).data("totalWidth", totalWidth);
				if ((scrollX / totalWidth) > that.ScrollLimit) {
					var scroll = $(this);
					that.IsUpdate = true;
					that.Page++;
					scroll.removeData('totalHeight');
					that.LoadContent();
				}
			}
		}
	).data('jsp');

	$('.btArrow', this.Container).repeatedclick(function (e) {
		var scrollTo = $(this).hasClass('btArrowLeft') ? -20 : 20;
		api.scrollByX(scrollTo);
	},
	{
		duration: 150

	});
})
.method("ShowContent", function (item) {
	var that = this;
	var listItem = $(item).closest('li');

	var youtubeUrl = $(item).attr('href');
	var youtubeId = youtubeUrl.match(/\/v\/([^?]+)/i);
	if (youtubeId && youtubeId.length > 1) youtubeId = youtubeId[1];
	$(this.Container).find('#youtubeVideo iframe').remove();
	var embed = '<iframe title="YouTube video player" width="428" height="314" src="http://www.youtube.com/embed/' + youtubeId + '?&amp;wmode=Transparent" frameborder="0" allowfullscreen></iframe>';

	$("#youtubeVideo").append(embed);

	var Share = $('<div />', { className: 'addthis_toolbox' });

	var isFavorite = $('.add_favorite', listItem).hasClass('on') || (listItem.closest('#WidgetFavoritos').length > 0);

	Share.append($('<ul />')
	.append($('<li/>', { className: 'like' })
		.append($('<a />', {
			className: 'addthis_button_facebook_like',
			'addthis:url': youtubeUrl,
			'fb:like:layout': 'button_count',
			'fb:like:width': 85
		}))
	)
	.append($('<li/>', { className: 'tweet' })
		.append($('<a />', {
			className: 'addthis_button_tweet',
			'addthis:url': youtubeUrl,
			'tw:width': 96
		}))
	)
	.append($('<li/>', { className: 'email' })
		.append($('<a />', {
			className: 'addthis_button_email',
			'addthis:url': youtubeUrl
		}))
	)
	.append($('<li/>', { className: 'share-more' })
		.append($('<a />', {
			className: 'addthis_button',
			'addthis:url': youtubeUrl,
			href: 'http://www.addthis.com/bookmark.php',
			html: '<img src="' + App.ImagePath + '/Misc/btYoutubeMore.gif" alt="Mais" />'
		}))
	)
	.append($('<li/>', { className: 'share-link' })
		.append($('<a />', {
			className: 'share_link',
			target: '_blank',
			title: 'Ir para o link original',
			href: youtubeUrl
		}))
	)
	.append($('<li/>', { className: 'sep' }))
	.append($('<li/>', { className: 'share_favorite' })
		.append($('<a />', {
			className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
			href: ''
		})
					.append($('<img />', {
						src: 'Util/Img/v2/Widget/favorite-loader-youtube.gif',
						alt: 'Carregando',
						width: 25,
						height: 25,
						className: 'favorite-loading'
					})))
	));

	$('#youtube-share').html(Share).data('Item', item);

	window.addthis.ost = 0;
	window.addthis.ready();

	$('#youtube-share').unbind('mouseenter mouseleave').hoverIntent(function () {
		$('.addthis_toolbox', this).fadeIn('fast');
	},
    function () {
    	$('.addthis_toolbox', this).fadeOut('fast');
    });
})
.method("Reset", function () {
	this.Page = 1;
	$(this.Container).find('dd ul li').remove();
	$(this.Container).find('#youtubeVideo *:not(.widget-loading)').remove();
	this.EndReached = false;
	$(".widget-loading", this.Container).show();
})
.method("AddFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#youtubeGallery').length > 0) ? $(item).closest('li') : $($(item).closest('#youtube-share').data('Item')).closest('li');

	var addToFav = {};
	addToFav.Id = listItem.attr('id');
	addToFav.Title = listItem.find('h3').text();
	addToFav.Thumb = listItem.find('> a img').attr('src');
	addToFav.Url = listItem.find('> a').attr('href');
	addToFav.Type = this.SocialId;
	addToFav.WidgetTitle = this.WidgetTitle;
	addToFav.WidgetId = this.WidgetId;

	App.AddFavorite(addToFav, function () {
		that.AfterAddFavorite(item, listItem)
	});
})
.method("AfterAddFavorite", function (item, listItem) {
	$(item).addClass('on');
	if ($(item).closest('#youtube-share').length > 0) {
		$('.add_favorite', listItem).addClass('on');
	}
	else {
		$('#youtube-share .add_favorite').addClass('on');
	}
	$(item).removeClass('loading');
})
.method("RemoveFavorite", function (item) {
	var that = this;
	var listItem = ($(item).closest('#youtubeGallery').length > 0) ? $(item).closest('li') : $($(item).closest('#youtube-share').data('Item')).closest('li');
	var removeFromFav = {};
	removeFromFav.Id = listItem.attr('id').replace(/[^0-9]+/, '');
	removeFromFav.Type = this.SocialId;
	removeFromFav.WidgetId = this.WidgetId;

	App.RemoveFavorite(removeFromFav, function () {
		that.AfterRemoveFavorite(item, listItem)
	});
})
.method("AfterRemoveFavorite", function (item, listItem) {
	$(item).removeClass('on');
	if ($(item).closest('#youtube-share').length > 0) {
		$('.add_favorite', listItem).removeClass('on');
	}
	else {
		$('#youtube-share .add_favorite').removeClass('on');
	}
	$(item).removeClass('loading');
});

/* AUDI MAGAZINE */
var WidgetAudiMagazine = function () {
	this.WidgetTitle = "Audi Magazine";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titAudiMagazine.png"
	this.SocialId = 'AUDIMAGAZINE';
	this.WidgetId = "WidgetAudiMagazine";
	this.ThumbWidth = 57;
	this.ThumbHeight = 75;
	this.HelpText = "Leia as principais reportagens publicadas na revista da Audi."
}
.inherits(Widget)
.method("ShowContent", function (list) {
	var that = this;
	var listItem = $(list, this.Container);

	if (App.IsFacebook) {
		window.open(listItem.data("url"), "_blank", "");
		return;
	}

	$('#view-loader').dialog({
		modal: true,
		resizable: false,
		dialogClass: 'view-loader-container',
		width: 220,
		height: 19
	});

	if (!jQuery.fn.flash.hasFlash(9)) {
		$('#view-content *').remove();

		$('#view-content')
			.append($('<div />', { id: 'view-flash-required' })
				.append($('<h3 />', { text: 'Plugin do flash não detectado' }))
				.append($('<p />', { html: 'Para acessar esse conteúdo você precisa ter o Adobe Flash Player instalado no seu computador. Faça o <a href="http://get.adobe.com/br/flashplayer/" target"_blank">download aqui</a>.' }))
				);

		$('#view-loader').dialog('close');

		$('#view-item').dialog({
			modal: true,
			resizable: false,
			title: that.WidgetTitle,
			dialogClass: 'view-item-container view-item-flash-required',
			width: 700,
			height: 'auto'
		});

		return;
	}

	$.getJSON(App.RootPath + "Service/GetContent.ashx", { id: list.id.replace(/[^0-9]+/, '') },
	function (item) {
		if (!item || item == null) return;

		var Share = $('<div />', {
			className: 'addthis_toolbox'
		});

		var isFavorite = $('.add_favorite', listItem).hasClass('on') || (listItem.closest('#WidgetFavoritos').length > 0);

		Share.append($('<ul />')
		    .append($('<li/>', { className: 'like' })
			    .append($('<a />', {
			    	className: 'addthis_button_facebook_like',
			    	'addthis:url': item.Url,
			    	'fb:like:layout': 'button_count',
			    	'fb:like:width': 85
			    }))
		    )
		    .append($('<li/>', { className: 'tweet' })
			    .append($('<a />', {
			    	className: 'addthis_button_tweet',
			    	'addthis:url': item.Url,
			    	'tw:width': 96
			    }))
		    )
		    .append($('<li/>', { className: 'email' })
			    .append($('<a />', {
			    	className: 'addthis_button_email',
			    	'addthis:url': item.Url
			    }))
		    )
		    .append($('<li/>', { className: 'share-more' })
			    .append($('<a />', {
			    	className: 'addthis_button',
			    	'addthis:url': item.Url,
			    	href: 'http://www.addthis.com/bookmark.php',
			    	html: '<img src="Util/Img/v2/Misc/btViewMore.gif" alt="Mais" />'
			    }))
		    )
		    .append($('<li/>', { className: 'share-link' })
			    .append($('<a />', {
			    	className: 'share_link',
			    	target: '_blank',
			    	title: 'Ir para o link original',
			    	href: item.Url
			    }))
		    )
		    .append($('<li/>', { className: 'sep' }))
		    .append($('<li/>', { className: 'share_favorite' })
			    .append($('<a />', {
			    	className: 'add_favorite' + ((isFavorite) ? ' on' : ''),
			    	href: ''
			    })
					.append($('<img />', {
						src: 'Util/Img/v2/Widget/favorite-loader-view.gif',
						alt: 'Carregando',
						width: 25,
						height: 25,
						className: 'favorite-loading'
					})))
		    ));

		$('#view-share').html(Share);

		window.addthis.ost = 0;
		window.addthis.ready();

		$('#view-content *').remove();
		//$('#view-content *:not(h3)').remove();
		/*$('#view-content').find('h3').text(item.Title);
		$('#view-content').append($('<p/>', { text: item.Content }));*/

		$('#view-content').append('<iframe class="scribd_iframe_embed" src="' + item.Url + '" data-auto-height="false" data-aspect-ratio="1.33333333333333" scrolling="no" id="doc_81098" width="640" height="500" frameborder="0"></iframe>');
		//$('#view-content').append($('<div/>', { id: 'magazine-view', html: '<iframe class="scribd_iframe_embed" src="'+ item.Url +'" data-auto-height="false" data-aspect-ratio="1.33333333333333" scrolling="no" id="doc_81098" width="640" height="500" frameborder="0"></iframe>' }));
		$('#view-loader').dialog('close');

		$('#view-item').dialog({
			modal: true,
			resizable: false,
			title: that.WidgetTitle,
			dialogClass: 'view-item-container',
			width: 700,
			height: 'auto',
			open: function (event, ui) {
				$('#view-item').data('Item', list);
			},
			beforeClose: function (event, ui) {
				if ($('#view-share').find('.add_favorite').hasClass('on')) {
					$('.add_favorite', listItem).addClass('on');
				}
				else {
					$('.add_favorite', listItem).removeClass('on');
				}
			}
		});
	});
});

/* GARAGEM AUDI */
var WidgetGaragemAudi = function () {
	this.WidgetTitle = "Garagem Audi";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titGaragemAudi.png"
	this.SocialId = 'GARAGEMAUDI';
	this.WidgetId = "WidgetGaragemAudi";
	this.ThumbWidth = 104;
	this.ThumbHeight = 45;
	this.HelpText = "Escolha o seu modelo Audi e clique pra saber mais.";
}
.inherits(Widget)
.method("InsertContent", function (item) {
	try {
		var newItem = $('<li />', {
			id: item.Id
		}).data("url", item.Url);

		if (item.Thumb) {
			newItem.append($('<span />', {
				className: 'img'
			})
				.append($('<img />', {
					src: App.IsFacebook ? ('http://www.audisfera.com.br/'+ item.Thumb) : item.Thumb,
					alt: item.Title,
					width: this.ThumbWidth,
					height: this.ThumbHeight
				}))
			);
		}

		var isFavorite = App.IsFavorite(item.Id, this.SocialId);

		newItem
			.append($('<h3/>', { text: this.LimitCheck(item.Title, this.TitleLimit) }))
			.append($('<p/>', { html: this.LimitCheck(this.CleanTags(item.Content), this.ContentLimit) }));

		if (this.InsertMode == 'prepend') {
			$("ul", this.Container).prepend(newItem);
		}
		else {
			$("ul", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("ShowContent", function (list) {
	var that = this;

	var listItem = $(list, this.Container);

	if (App.IsFacebook) {
		window.open(listItem.data("url"), "_blank", "");
		return;
	}

	$('#view-loader').dialog({
		modal: true,
		resizable: false,
		dialogClass: 'view-loader-container',
		width: 220,
		height: 19
	});

	$.getJSON(App.RootPath + "Service/GetContent.ashx", { id: list.id.replace(/[^0-9]+/, '') },
	function (item) {
		if (!item || item == null) return;

		$('#view-content *').remove();

		var image = $(item.Content).find('img');
		image.attr({ width: 700, height: 450 });
		$('#view-content').html(image);

		$('#view-content').append($('<div />', { 'class': 'description' })
			.append($('<h4 />', {
				'class': 'TitleAudisfera'
			})
				.append($('<span />', { text: item.Title }))
				.append($('<a />', { href: item.Url, title: item.Title, target: '_blank' })
					.append($('<img />', { alt: 'Saiba mais', src: App.ImagePath + '/Widget/GaragemAudi/btSaibaMais.gif' }))
				)
			)
			.append($('<p />', { text: image.attr("alt") }))
		);

		$('#view-loader').dialog('close');

		var dialogClass = "ViewItem" + that.WidgetId
		$('#view-item').dialog({
			modal: true,
			resizable: false,
			title: that.WidgetTitle,
			dialogClass: 'view-item-container ' + dialogClass,
			width: 700,
			height: 'auto',
			open: function (event, ui) {
				$('#view-item').data('Item', list);
			},
			beforeClose: function (event, ui) {
				if ($('#view-share').find('.add_favorite').hasClass('on')) {
					$('.add_favorite', listItem).addClass('on');
				}
				else {
					$('.add_favorite', listItem).removeClass('on');
				}
			}
		});
	});
});

/* INSTAGRAM */
var WidgetInstagram = function () {
	this.WidgetTitle = "Instagram";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titInstagram.png"
	this.SocialId = 'INSTAGRAM';
	this.WidgetId = "WidgetInstagram";
	this.ThumbWidth = 388;
	this.ThumbHeight = 388;
	this.HelpText = "Fotos exclusivas do universo Audi em primeira mão para você.";
}
.inherits(Widget)
.method("InsertContent", function (item) {
	try {
		var newItem = $('<li />', {
			id: item.Id
		});

		newItem.append($('<img />', {
			src: item.Thumb,
			alt: item.Title,
			width: this.ThumbWidth,
			height: this.ThumbHeight
		}))
		
		if(this.InsertMode == 'prepend') {
			$("ul", this.Container).prepend(newItem);
		}
		else {
			$("ul", this.Container).append(newItem);
		}
	} catch (Error) { }
})
.method("Show", function (item) {
	var that = this;

	if (this.Scrollable)
		this.ApplyScroll();
	this.Check();

	$(".widget-loading", this.Container).hide();
});

/* BLOG */
var WidgetBlogs = function () {
	this.WidgetTitle = "Blogs";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titBlogs.png"
	this.SocialId = 'BLOG';
	this.WidgetId = "WidgetBlogs";
	this.HelpText = "Veja o que os principais blogs automobilísticos falam sobre a Audi.";
}
.inherits(Widget);

/* AUDI TRADITION */
var WidgetAudiTradition = function () {
	this.WidgetTitle = "Audi Tradition";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titAudiTradition.png"
	this.SocialId = 'AUDITRADITION';
	this.WidgetId = "WidgetAudiTradition";
	this.HelpText = "Veja o que estão falando sobre os clássicos das quatro argolas.";
}
.inherits(Widget);

/* NEWS */
var WidgetNews = function () {
	this.WidgetTitle = "News";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titNews.png"
	this.SocialId = 'NEWS';
	this.WidgetId = "WidgetNews";
	this.HelpText = "Confira as notícias da Audi nas principais publicações automobilísticas.";
}
.inherits(Widget);

/* LIFESTYLE */
var WidgetLifestyle = function () {
	this.WidgetTitle = "Lifestyle";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titLifestyle.png"
	this.SocialId = 'LIFESTYLE';
	this.WidgetId = "WidgetLifestyle";
	this.HelpText = "Notícias e curiosidades que têm o estilo da marca Audi.";
}
.inherits(Widget);

/* LE MANS */
var WidgetLeMans = function () {
	this.WidgetTitle = "Le Mans";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titLeMans.png"
	this.SocialId = 'LEMANS';
	this.WidgetId = "WidgetLeMans";
	this.HelpText = "Todas as notícias sobre a tradicional corrida de 24h que acontece na França.";
}
.inherits(Widget);

/* FAVORITOS */
var WidgetFavoritos = function () {
	this.WidgetTitle = "Favoritos";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titFavoritos.png";
	this.WidgetId = "WidgetFavoritos";
	this.ThumbWidth = 95;
	this.ThumbHeight = 66;
	this.HelpText = "Acesse rapidamente todos os seus conteúdos preferidos.";
}
.inherits(Widget).method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);
	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>')
		.append($('<div></div>', {
			className: 'widget-loading'
		}
		))
	)
	.data('widget', this);

	if (this.WidgetTitleImage) {
		$("dt", item).append($('<img />', {
			src: this.WidgetTitleImage,
			alt: this.WidgetTitle
		}));
	}
	else
		$("dt", item).wrap($('<span />', { className: 'title' })).text(this.WidgetTitle);

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })));
	}

	if (this.Scrollable) {
		$("dd", item).append($("<div></div>", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($('<ul />', { className: 'item-list' })));
	}

	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);
	this.Container = item;
	this.Callback = settings.callback;

	this.LoadContent();
})
.method("Check", function () {
	if (!this.IsUpdate && $("ul.item-list li", this.Container).length <= 0) {
		$("ul", this.Container).append(
			$('<li/>', { className: 'nocontent' }));

		$('.nocontent', this.Container).append('<p><img src="Util/Img/v2/Widget/nenhumFavorito.gif" alt=""></p>');
	}
	else {
		if (this.Scrollable)
			this.ApplyScroll();
	}
})
.method("ApplyScroll", function () {
	var that = this;

	var jsp = $(".widgetScroll", this.Container).data('jsp');
	if (jsp != null) {
		jsp.reinitialise();
		return;
	}

	$(".widgetScroll", this.Container).removeData('totalHeight').hide().show().jScrollPane({
		scrollbarWidth: 24,
		verticalDragMinHeight: 43,
		verticalDragMaxHeight: 43,
		verticalGutter: 0,
		showArrows: true
	});
})
.method("LoadContent", function () {
	var that = this;

	var favorites = JSLINQ(App.Favorites)
				.Distinct(function (item) { return item.WidgetTitle });

	if (favorites.items && favorites.items.length > 0) {
		$('.nocontent', this.Container).remove();
		var favList = $('<ul />');
		$.each(favorites.items, function (i, fav) {
			favList.append($('<li />', { id: 'Widget' + fav.replace(' ', '') + 'Favorites' })
				.append($('<h3 />', { text: fav }))
				.append($('<div />')
					.append($('<ul />'))
				)
			);
		});
		$('.item-list', that.Container).append(favList.find('li'));
	}

	this.Check();

	if (null != App.Favorites) {
		$.each(App.Favorites, function (i, item) {
			that.InsertContent(item);
		});
	}
	this.AfterLoadContent();
})
.method("InsertContent", function (item) {
	var newItem = $('<li />', { id: 'fav-' + item.Id });
	switch (item.Type) {
		case 'YOUTUBE':
			newItem.append($('<a />', {
				href: item.Url,
				title: item.Title
			})
					.append($('<img />', {
						src: item.Thumb,
						alt: item.Title,
						width: 94,
						height: 66
					})));
			break;
		case 'TWITTER':
			item.Title = item.Title.replace(/\B@([_a-z0-9]+)/ig, function (reply) {
				return reply.charAt(0) + '<a href="http://twitter.com/' + reply.substring(1) + '">' + reply.substring(1) + '</a>';
			});
			newItem.append($('<p />', { html: item.Title }));
			break;
		default:
			newItem.append($('<p />', { html: item.Title }));
			break;
	}
	$("#" + item.WidgetId + "Favorites").find('ul').append(newItem);
})
.method("AfterLoadContent", function (Content) {
	this.Container.find('dt .close').unbind('click').bind('click', function (e) {
		e.preventDefault();
		var container = $(this).closest('.widget');
		var wdg = container.data('widget');
		wdg.Close();
	});

	if (this.Collapsible) {
		App.ApplyAccordion(this.Container);
	}

	this.Show();
})
.method("Show", function () {
	var that = this;
	$("ul.item-list", this.Container).undelegate("li[id=WidgetYoutubeFavorites] a").delegate("li[id=WidgetYoutubeFavorites] a", "click", function (e) {
		e.preventDefault();
		var thatLink = this;
		var widgetId = $(this).closest('ul').closest('li').attr('id').replace('Favorites', '');
		var youtubeBox = $("#" + widgetId);

		if (youtubeBox.length > 0) {
			var widget = youtubeBox.data('widget');
			widget.ShowContent(thatLink);
		}
		else {
			App.ShowDialog({
				texto: '<p>Para visulizar o vídeo é necessário que o box do YouTube esteja aberto. Deseja abrir agora?</p>',
				buttons: {
					'Sim': function () {
						$(this).dialog('close');
						new _Widget({
							type: WidgetYoutube,
							colNumber: App.MinLengthColumn(),
							callback: function () {
								var thatWidget = this;
								$.scrollTo("#" + widgetId, 800, function () {
									$("#" + widgetId).effect("pulsate", {}, 280, function () {
										thatWidget.ShowContent(thatLink);
									});
								});
							},
							saveCookie: true
						});
					},
					'Não': function () {
						$(this).dialog('close');
					}
				}
			});
		}
	});

	$("ul.item-list", this.Container).undelegate("li[id=WidgetAudiMagazineFavorites] li").delegate("li[id=WidgetAudiMagazineFavorites] li", "click", function (e) {
		e.preventDefault();
		var thatLink = this;
		var widgetId = $(this).closest('ul').closest('li').attr('id').replace('Favorites', '');
		var widgetBox = $("#" + widgetId);

		if (widgetBox.length > 0) {
			var widget = widgetBox.data('widget');
			widget.ShowContent(thatLink);
		}
		else {
			var tempWidget = new WidgetAudiMagazine();
			tempWidget.ShowContent(thatLink);
			tempWidget = null;
		}
	});


	$("ul.item-list", this.Container).undelegate("li[id!=WidgetAudiMagazineFavorites][id!=WidgetYoutubeFavorites][id!=WidgetTwitterFavorites] li").delegate("li[id!=WidgetAudiMagazineFavorites][id!=WidgetYoutubeFavorites][id!=WidgetTwitterFavorites] li", "click", function (e) {
		e.preventDefault();
		var thatLink = this;
		that.ShowContent(thatLink);
	});
	this.ApplyAccordion(this.IsUpdate);

	$(".widget-loading", this.Container).hide();
})
.method("ApplyAccordion", function (reset) {
	if (reset) $('ul.item-list', this.Container).accordion('destroy');
	$('ul.item-list', this.Container).accordion({
		active: false,
		autoHeight: false,
		collapsible: true,
		icons: {
			header: "icon-favorite",
			headerSelected: "icon-favorite-on"
		},
		change: function (event, ui) {
			var jsp = $('.widgetScroll', this.Container).data('jsp');
			if (jsp != null) {
				jsp.reinitialise();
			}
		}
	});

	$(".widget-loading", this.Container).hide();
});



/* Audi Gift Day */
var WidgetAudiGiftDay = function () {
	this.WidgetTitle = "Audi Gift Day";
	this.WidgetTitleImage = App.ImagePath + "/Widget/titGiftDay.png";
	this.WidgetId = "WidgetAudiGiftDay";
	this.ThumbWidth = 95;
	this.ThumbHeight = 66;
	this.HelpText = "Tudo sobre o concurso que oferece experiências incríveis com nossos superesportivos.";
}
.inherits(Widget).method("Create", function (settings) {
	var that = this;
	$.extend(this, App.Opts);
	var item = $('<dl />', {
		className: 'widget',
		id: this.WidgetId
	})
	.append($('<dt/>'))
	.append($('<dd></dd>'))
	.data('widget', this);

	if (this.WidgetTitleImage) {
		$("dt", item).append($('<img />', {
			src: this.WidgetTitleImage,
			alt: this.WidgetTitle
		}));
	}
	else
		$("dt", item).wrap($('<span />', { className: 'title' })).text(this.WidgetTitle);

	if (this.Closable) {
		$("dt", item)
		.append($('<span />', {
			className: 'close',
			title: 'Minimizar'
		}))
		.append($('<span />', {
			className: 'help'
		}).append($('<span />', { 'class': 'help-box', text: that.HelpText })));
	}

	if (this.Scrollable) {
		$("dd", item).append($("<div></div>", {
			className: 'widgetScroll' + (this.ScrollClass ? ' ' + this.ScrollClass : '')
		})
		.append($("<a />").attr({ "href": "/Concurso/?utm_source=Audisfera&utm_medium=Box&utm_campaign=AudiGiftDay", "title": "Veja os vencedores" })
        .append($("<img />").attr({ "alt": "Veja os vencedores", "src": App.ImagePath + "/Widget/btVejaVencedores.gif" })
        )));
	}

	$(App.Column + ':eq(' + settings.colNumber + ')').append(item);
	this.Container = item;
	this.Callback = settings.callback;

	this.LoadContent();
});
