var cacheRetry 				= false;
var facebookPageID 			= "nodesdk";
var infographicsLanguage 	= "dk";

$(document).bind('fbAsyncInit', function () {
	$(document.body).removeClass('loading');

	$('#submit_and_initialize_infographics').bind('click', function () {
		jQuery(this).hide();
		jQuery('#infographics-loader').show();

		infographicsLanguage = jQuery(this).attr('data-language');
		fbook.invoke(fbook.vote);
		return false;
	});

	jQuery.getJSON(getURLPrefix() + 'getResult.json', function(aggregates) {
		jQuery('.meter .count').html(parseInt(aggregates.smiling.percent_true) + '<sub>%</sub>');
		jQuery('.meter .progress').css('left', -501 + (parseInt(aggregates.smiling.percent_true) * 5) + 'px');
	})
});

getURLPrefix = function () {
	return "https://nodesdk.officecloud.dk/website/infographics/website/infographics/";
};

getParameterByName = function (name) {
	var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
	return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
};

fbook = {
	invoke: function (callback, check, perms) {
		var _self = this;
		FB.login(function (response) {
			if (response.authResponse) {
				callback && callback();
			} else {
				_self.denied();
			}
		}, {
			scope: 'user_about_me,user_photos,user_birthday,user_relationships'
		});
	},

	denied: function () {
		//alert('We need your permission to gather and analyze your data. Click "Allow" to continue.','Facebook permissions:');

		jQuery('#submit_and_initialize_infographics').show();
		jQuery('#infographics-loader').hide();

		$(document.body).addClass('denied');
	},

	get: function (options) {
		var args = {
			facebook_session: FB.getAuthResponse()
		};
		$.extend(args, options.args, {});
		$.ajax({
			url: getURLPrefix() + options['do'],
			type: 'POST',
			dataType: options.dataType || 'json',
			data: {
				data: args
			},
			success: function (data) {
				$(document.body).removeClass('loading');
				if (this.dataType == "html") {
					options.go(data);
				} else {
					if (data.status) {
						options.go(data);
					} else {
						options.nogo(data);
					}
				}
			}
		});
	},

	vote: function() {
		$('.visitor-o-meter').addClass('loading');

		var _batch = [];
		_batch.push(
			{
				method: 'GET',
				relative_url: 'method/fql.query?query=SELECT+uid,name,username,sex,wall_count,friend_count,pic,birthday,birthday_date,about_me,relationship_status+FROM+user+WHERE+uid=me()+LIMIT+1'
			}, {
				method: 'GET',
				relative_url: '/me/albums?fields=id,type&limit=500'
			}
		);

		FB.api('/', 'POST', { batch: _batch }, function (res) {
			var userdata = $.parseJSON(res[0].body)[0];
			var albums	 = $.parseJSON(res[1].body);

			// Load additional info
			userdata.operating_system = fbook.get_operating_system();

			profileAlbum = $.grep(albums['data'], function (a) {
				return a["type"] == "profile"
			});

			// Check if we have a profile album
			if (profileAlbum) {
				profileAlbumID = profileAlbum[0]["id"];
				FB.api('/' + profileAlbumID + '/photos?limit=500', function (photos) {
					if (photos && photos['data'] && photos['data'].length > 0) {
						photos['data'].sort(function (a, b) {
							return +a.id - +b.id
						});

						var firstImg = photos.data[0].images[photos.data[0].images.length - 1].source;
						userdata.first_profile_picture = firstImg;
						userdata.first_profile_picture_date = photos.data[0].created_time;
					}
					fbook.submit(userdata)
				});
			} else {
				fbook.submit(userdata)
			}
		});
	},

	get_operating_system: function() {
		var os = "";

		if (/Linux/i.test(navigator.userAgent)) {
			os = "Linux";
		}
		else if(/Macintosh/i.test(navigator.userAgent)) {
			os = "Mac";
		} else {
			os = "PC";
		}

		return os
	},

	submit: function(userdata) {
		userdata = jQuery.extend({ }, {
				first_profile_picture: null,
				first_profile_picture_date: null
			},
			userdata
		);

		jQuery.ajax({
			'url'	: getURLPrefix() + 'add',
			'async'	: true,
			'cache'	: false,
			'type'	: 'post',
			'data'	: {
				'data': {
					'language'			: infographicsLanguage,
					'user'				: userdata,
					'facebook_session'	: FB.getAuthResponse()
				}
			},
			'complete'	: function(jqXHR, textStatus) {
//				console.log(jqXHR, textStatus);
			},
			'error'		: function(jqXHR, textStatus, errorThrown) {
//				console.log(jqXHR, textStatus, errorThrown);
			},
			'success'	: function(data, textStatus, jqXHR) {
				jQuery('#frontpageSlider').remove();

				jQuery(data).insertAfter('.main section .headline');
//				console.log(data, textStatus, jqXHR);
			}
		});
	},

	share: function (data) {
		var tableID = $('div.container.table').data('tableid');
		var feed = {
			method: 'feed',
			name: data.name || 'dragons be here..',
			caption: '&nbsp;',
			link: Nodes.config('Application.canvas_url') + '/' + tableID,
			picture: 'http://akvavit.officecloud.dk/theme/akvavit/img/90x90.png',
			description: data.desc || 'description be here..'
		};

		FB.ui(feed, function (response) {

		});
	}
};
