/**
 *
 * @author: Catalin Bucur <catalin.bucur@greenpixel.ro>
 * @copyright: Green Pixel Interactive; www.greenpixel.ro;
 * @license: You may NOT use, copy or reproduce without our prior written consent
 *
 */
if (!window.facebookApp) facebookApp = {
	id:null,
	url: '',
	returnUrl: null,
	_reqirePerms: "email,user_birthday",
	_user:null,
	_userPerms:null,
	_session:null,
	_uid:null,
	_css: {
		facebookAppOverlayer: {
			background: '#333333',
			opacity: 0.5,
			position: 'absolute',
			top: 0,
			left: 0,
			'z-index': 99999
		},
		facebookAppPopup: {
			position: 'fixed',
			top: '5%',
			left: '30%',
			'z-index': 100000
		},
		facebookAppPopupBox: {}
	},
	wallPost: {
		method: 'stream.publish',
		message: 'enterMessageHere',
		attachment: {},
		action_links: [],
		user_message_prompt: 'enterQuestionHere'
	},
	invitation: {
		name: 'setNameHere',
		title: 'setTitleHere',
		text: 'setTextHere',
		label: null,
		url: null
	},
	setEnv: function (appId, url, returnUrl) {
		facebookApp.id = appId;
		facebookApp.url = (url == undefined)? document.location.origin + document.location.pathname : url;
		facebookApp.returnUrl = (returnUrl == undefined)? facebookApp.url + 'fb.php' : returnUrl;

		document.write('<div id="fb-root"></div>');
		var e = document.createElement('script');
		e.type = 'text/javascript';
		// e.src = document.location.protocol + '//connect.facebook.net/ro_RO/all.js#appId=' + appId +'&xfbml=1';
		e.src = document.location.protocol + '//connect.facebook.net/ro_RO/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);

		window.fbAsyncInit = function (){
			facebookApp.init();
		};
	},
	init: function (){
		FB.init({
			appId: facebookApp.id,
			status: true,
			cookie: true,
			xfbml: true
		});

		FB.Event.subscribe('auth.login', function(response) {
			facebookApp.onLogin(response);
		});
		FB.Event.subscribe('auth.logout', function(response) {
			facebookApp.onLogout(response);
		});
		FB.getLoginStatus(function(response) {
			if (response.session) {
				facebookApp.onLogin(response, true);
			}
		});
	},
	login: function() {
		FB.login(function(response) {  }, {
			perms: facebookApp._reqirePerms
		})
	},
	logout: function() {
		FB.logout(function(response) { });
	},
	onLogout: function (res){
		facebookApp._user = null;
		facebookApp._uid = null;
		facebookApp._userPerms = [];
		facebookApp.events.run(facebookApp.events.onLogout, res);
	},
	onLogin: function (response, isLoggedIn){
		if (response.session) {

			if (response.perms) {
				facebookApp._userPerms = response.perms.split(',');
			}
			facebookApp._session = response.session;
			facebookApp._uid = response.session.uid;

			facebookApp.events.set ('onLoginEvent',  function (isLoggedIn){
				facebookApp.events.run(facebookApp.events.onLogin);
				if(isLoggedIn === true) {
					facebookApp.events.run(facebookApp.events.loadPageIsLoggedin);
				} else {
					facebookApp.events.run(facebookApp.events.onLoginOk);
				}
			});
			facebookApp.loadUser(isLoggedIn);
		} else {
			if(isLoggedIn === true) {
				facebookApp.events.run(facebookApp.events.onLoginFailed);
			} else {
				facebookApp.events.run(facebookApp.events.loadPageIsNotLoggedin);
			}
		}
	},
	loadUser: function (isLoggedIn){
		FB.api('/me', function(response) {
			facebookApp._user = response;
			facebookApp.events.runAndReset('onLoginEvent',isLoggedIn);
		});
	},
	events: {
		onLoginOk: 1,
		onLoginFailed: 2,
		onLogin: 3,
		onLogout: 4,
		loadPageIsLoggedin: 5,
		loadPageIsNotLoggedin: 6,
		onWallPost: 7,
		onWallPostCanceled: 8,
		onCourtainShow: 9,
		onCourtainHide: 10,
		goAway: -1,

		eh: {},
		set: function(event, handler, first) {
			if(typeof(handler) != 'function') {
				return false;
			}
			var highpriority = first === true;
			if(!facebookApp.events.has(event)) {
				facebookApp.events.eh[event] = [];
			}
			if(highpriority) {
				facebookApp.events.eh[event].splice(0,0, handler);
			}
			else {
				facebookApp.events.eh[event][facebookApp.events.eh[event].length] = handler;
			}
			return true;
		},
		has: function(event) {
			return (typeof facebookApp.events.eh[event] != 'undefined' && facebookApp.events.eh[event] != null);
		},
		run: function(eventName, e, callback) {
			if(facebookApp.events.has(eventName)) {
				for(var i = 0; i < facebookApp.events.eh[eventName].length; i++) {
					if(facebookApp.events.eh[eventName][i](e) === false) {
						return false;
					}
				}
				if(callback) {
					callback();
				}
				return true;
			}
			return false;
		},
		reset: function(event) {
			facebookApp.events.eh[event] = null;
			return null;
		},
		runAndReset: function(eventName, e, callback) {
			var out = facebookApp.events.run(eventName, e, callback);
			facebookApp.events.reset(eventName);
			return out;
		}
	},
	entitize: function (string , sep){
		string = string.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
		if(sep == undefined || sep == '"') {
			string = string.replace(/"/g, '&quot;');
		} else {
			string = string.replace(/'/g, "\'");
		}
		return string;
	},
	wall:  function (){
		if(facebookApp._uid == null || facebookApp._user == null) {
			facebookApp.events.set(facebookApp.events.onLoginOk, function (){
				facebookApp.wall();
			});
			return facebookApp.login();
		}
		facebookApp.wallPost.method = 'stream.publish';

		FB.api('/me', function(response) {
			FB.ui (facebookApp.wallPost, function(response) {
				if (response && response.post_id) {
					facebookApp.events.run(facebookApp.events.onWallPost, response);
				} else {
					facebookApp.events.run(facebookApp.events.onWallPostCanceled, response);
				}
			})
		});
	},
	validateRegister: function(form, cb) {

		errors = {};
		if (form.username !== "test") {
			errors.username = "scrie test";
		}

		$.getJSON('http://graph.facebook.com/' + form.username + '?callback=?',
			function(response) {
				if (response.error) {
					// Username isn't taken, let the form submit
					cb();
				}
				cb({
					username: 'That username is taken'
				});
			});
	},

	register: function (){
		var __popupWidth = 700;
		var __popupHeight = 650;

		if($('#facebookAppPopup').size()) {
			$('#facebookAppPopup').remove();
		}
		$('body').append('<div id="facebookAppPopup" style="display:none"><div id="facebookAppPopupBox" ' +
			'style="width:' + __popupWidth + 'px; height:'+ __popupHeight +'px;"' +
			'></div></div><div id="facebookAppOverlayer"></div>'
			);
		$('#facebookAppOverlayer').css(facebookApp._css.facebookAppOverlayer);
		$('#facebookAppPopup').css(facebookApp._css.facebookAppPopup);
		$('#facebookAppPopupBox').css(facebookApp._css.facebookAppPopupBox);
		$('#facebookAppOverlayer').css({
			width: $(document).width(),
			height: $(document).height()
		});


		var
		fbml  = '<fb:registration ';
		fbml += 'redirect-uri="' + facebookApp.returnUrl +'" fields="[' ;
		fbml += "{'name':'name'},";
		fbml += "{'name':'email'},";
		fbml += "{'name':'username', 'type':'text', 'description':'Utilizator'},";
		fbml += "{'name':'password',   'view':'not_prefilled'}";

		// fbml += "{'name':'phone'},";


		fbml += ']" ';
		// fbml += 'onvalidate="validateRegister"';
		fbml += '></fb:registration>';


		facebookApp.setCourtain(true);
		$('#facebookAppPopupBox').html(fbml);
		//$('#facebookAppPopupBox').html('<fb:serverfbml width="'+ __popupWidth + '" id="fbml" fbml="' + facebookApp.entitize(fbml) + '"</fb:serverfbml>');
		//	$('#facebookAppPopupBox').html('<fb:serverfbml width="'+ __popupWidth + '" id="fbml" fbml="' + facebookApp.entitize(fbml) + '"</fb:serverfbml>');
		FB.XFBML.parse(document.getElementById('facebookAppPopupBox'));
	},
	invite: function () {
		if(facebookApp._uid == null || facebookApp._user == null) {
			facebookApp.events.set(facebookApp.events.onLoginOk, function (){
				facebookApp.invite();
			});
			return facebookApp.login();
		}
		var postBack = (facebookApp.invitation.url == null)? facebookApp.url : facebookApp.invitation.url;
		var label = (facebookApp.invitation.label == null)? '' : facebookApp.invitation.label;

		var postAction = facebookApp.returnUrl;

		var __popupWidth = 625;
		var __popupHeight = 513;

		var
		invite = "<fb:req-choice url='" + postBack + "' label='" + facebookApp.entitize(label,"'") + "' />";
		var
		fbml  = '<fb:request-form target="_self" action="';
		fbml += postAction;
		fbml += '" method="GET" invite="false" type="';
		fbml += facebookApp.entitize(facebookApp.invitation.name);
		fbml += '" content="';
		fbml += facebookApp.entitize(facebookApp.invitation.text);
		fbml += facebookApp.entitize(invite);
		fbml += '" >';
		fbml += '<fb:multi-friend-selector target="_self"';
		fbml += 'showborder="true" import_external_friends="false" ';
		fbml += 'rows="2" cols="5" actiontext="';
		fbml += facebookApp.entitize(facebookApp.invitation.title);
		fbml += '"></fb:multi-friend-selector></fb:request-form>';

		if(! $('#FbPopup').size()){
			if($('#facebookAppPopup').size()) {
				$('#facebookAppPopup').remove();
			}
			$('body').append('<div id="facebookAppPopup" style="display:none"><div id="facebookAppPopupBox" ' +
				'style="width:' + __popupWidth + 'px; height:'+ __popupHeight +'px;"' +
				'></div></div><div id="facebookAppOverlayer"></div>'
				);
			$('#facebookAppOverlayer').css(facebookApp._css.facebookAppOverlayer);
			$('#facebookAppPopup').css(facebookApp._css.facebookAppPopup);
			$('#facebookAppPopupBox').css(facebookApp._css.facebookAppPopupBox);
		}

		$('#facebookAppOverlayer').css({
			width: $(document).width(),
			height: $(document).height()
		});

		facebookApp.setCourtain(true);

		$('#facebookAppPopupBox').html('<fb:serverfbml width="'+ __popupWidth + '" id="fbml" fbml="' + facebookApp.entitize(fbml) + '"</fb:serverfbml>');
		FB.XFBML.parse(document.getElementById('facebookAppPopupBox'));
	},
	setCourtain: function (show) {
		if(show == true) {
			$('#facebookAppOverlayer').show();
			$('#facebookAppPopup').show();
			facebookApp.events.runAndReset(facebookApp.events.onCourtainShow);
		} else {
			$('#facebookAppPopup').hide();
			$('#facebookAppOverlayer').hide();
			facebookApp.events.runAndReset(facebookApp.events.onCourtainHide);
		}
	},
	isLoggedIn : function (){
		return (facebookApp._uid == null || facebookApp._user == null)? false : true;
	}
}

