﻿var apiKey = "666e212ecd51022eb09a6fc88678dfbc";
//var apiKey = "ea965650d884fbcbc46fefd9504e0e70";
function showPopup(url, name, width, height, callback, showScrollbars, arguments) {
	if (window.popupReturnValues == null) {
		window.popupReturnValues = {};
	}

	if (window.popupArgumentsValues == null) {
		window.popupArgumentsValues = {};
	}

	window.popupArgumentsValues[name] = arguments;

	var left = 100;
	var top = 100;

	if (window.screen && window.screen.availWidth && window.screen.availHeight) {
		left = Math.floor((window.screen.availWidth - width) / 2);
		top = Math.floor((window.screen.availHeight - height) / 2) - 30;
	}

	var popup = window.open(
		url,
		name,
		format(
			"width={width},height={height},top={top},left={left},toolbar=no,locationbar=yes,directories=no,status=yes,menubar=no,scrollbars={scrollbars},resizable=no,copyhistory=no",
			{
				width: width,
				height: height,
				top: top,
				left: left,
				scrollbars: showScrollbars == true ? "yes" : "no"
			}
		)
	);

	if (popup != null) {
		var timer = setInterval(function() {
			if (popup.closed) {
				clearInterval(timer);
				if (callback != null) {
					callback(window.popupReturnValues[name]);
				}
			}
		}, 200);
		return true;
	} else {
		return false;
	}
}

function setPopupReturnValue(value) {
	try {
		window.opener.popupReturnValues[window.name] = value;
		return true;
	}
	catch (e) {
		return false;
	}
}

function getPopupArguments() {
	try {
		return window.opener.popupArgumentsValues[window.name];
	}
	catch (e) {
		return null;
	}
}

function format(text, args) {
	text += "{}";

	var pattern = /([^\{]*)\{([^\}]*)\}/g;
	var match;
	var lastIndex = 0;
	var result = [];
	while ((match = pattern.exec(text)) != null) {
		result.push(match[1]);
		if (match[2].length > 0) {
			var useNamedArgs = parseInt(match[2]).toString() != match[2];
			var value = useNamedArgs ? eval("var __x; try { __x = args." + match[2] + ";} catch(e){__x = e;}__x") : arguments[1 + parseInt(match[2])];
			result.push(value);
		}
	}
	return result.join("");
}

function trim(text) {
	return /^\s*([\s\S]*?)\s*$/.exec(text)[1];
}

function adjustPopupToElementSize(selector, marginTop, marginRight, marginBottom, marginLeft) {
	var previousWidth = -1;
	var previousHeight = -1;

	marginLeft = marginLeft || 0;
	marginTop = marginTop || 0;
	marginRight = marginRight || 0;
	marginBottom = marginBottom || 0;

	setInterval(function() {
		var element = $(selector);
		if (element.length && (element.width() != previousWidth || element.height() != previousHeight)) {
			previousWidth = element.width();
			previousHeight = element.height();

			element.css({
				left: marginLeft + "px",
				top: marginTop + "px"
			});

			var deltaX = element.width() - $(window).width() + marginLeft + marginRight;
			var deltaY = element.height() - $(window).height() + marginTop + marginBottom;

			window.resizeBy(deltaX, deltaY);
			window.moveBy(-deltaX / 2, -deltaY / 2);
		}
	}, 200);
}

/////////////////////////////////////////////////

function initializeFacebook(callback) {
	alert(initializeFacebook);
	FB_RequireFeatures(["XFBML"], function() {
		FB.Facebook.init(apiKey, "xd_receiver.htm");
		if (callback != null) {
			callback();
		}
	});
}

function facebookLogin(callback, showLoginButton) {
	var callbackInvoked = false;
	FB.Connect.requireSession(function() {
		if (!callbackInvoked) {
			callbackInvoked = true;

			if (callback != null) {
				callback();
			}
		}
	}, true != showLoginButton);
}

function facebookLogout(callback) {
	var callbackInvoked = false;
	FB.Connect.logout(function() {
		if (!callbackInvoked) {
			callbackInvoked = true;
			if (callback != null) {
				callback();
			}
		}
	});
}

function getUser(parameters_in) {
	facebookLogin(function() {
		var currentUserId = FB.Connect.get_loggedInUser();
		// Get some info of the current user
		FB.Facebook.apiClient.users_getInfo([currentUserId], parameters_in, function(users) {
			//alert('flashObj: ' + flashObject + '\nmethod: ' + flashObject.onGetUser + '\nuser: ' + users[0] + '\nfirst_name:' + users[0].first_name);
			flashObject.onGetUser(users[0]);
		});
	});
}

function getFriends() {
	facebookLogin(function() {
		var currentUserId = FB.Connect.get_loggedInUser();
		FB.Facebook.apiClient.fql_query(
			format('select uid, first_name, last_name, pic, pic_square, sex from user where uid in (select uid2 from friend where uid1 = {0})', currentUserId),
			function(friends) {
				//alert(friends);
				flashObject.onGetFriends(friends);
			}
		);
	});
}

function getAlbums() {
	facebookLogin(function() {
		var currentUserId = FB.Connect.get_loggedInUser();

		FB.Facebook.apiClient.photos_getAlbums(currentUserId, null, function(albums) {
			var photoIds = [];
			for (var i = 0; i < albums.length; i++) {
				photoIds.push(albums[i].cover_pid);
			}

			FB.Facebook.apiClient.photos_get(null, null, photoIds, function(photos) {
				for (var i = 0; i < albums.length; i++) {
					for (var j = 0; j < photos.length; j++) {
						if (photos[j].pid == albums[i].cover_pid) {
							albums[i].cover = photos[j];
							break;
						}
					}

				}
				flashObject.onGetAlbums(albums);
			});
		});
	});
}

//function getPhotos(albumId, callBack) {
function getPhotos(albumId) {
	facebookLogin(function() {
		FB.Facebook.apiClient.photos_get(null, albumId, null, function(photos) {
			flashObject.onGetPhotos(photos);
		});
	});
}

function postVideo(link, users) {
	//alert("link : " + link);
	//alert("users : " + users)
	if (users != null && users.length > 0) {
		users = users.split(",");
	} else {
		users = null;
	}

	showPopup(
        "/TMN Institucional/Minisites/Namorados2010/PublishStory.html",
        "PublishStory",
        640,
        500,
        function() {
			flashObject.onPostVideo();
        },
        false,
        {
        	link: link,
        	users: users
        }
    );
}

function postCartaz(link, users) {
	alert("link : " + link);
	alert("users : " + users)
	if (users != null && users.length > 0) {
		users = users.split(",");
	} else {
		users = null;
	}
	showPopup(
        "PublishStory.html",
        "PublishStory",
        640,
        400,
        function() {
			flashObject.onPostCartaz();
        },
        false,
        {
        	link: link,
        	users: users
        }
    );
}

function postEcard(link, users) {
	//alert("link : " + link);
	//alert("users : " + users)
	if (users != null && users.length > 0) {
		users = users.split(",");
	} else {
		users = null;
	}

	showPopup(
        "PublishStory.html",
        "PublishStory",
        720,
        500,
        function() {
			flashObject.onPostCard();
        },
        false,
        {
        	link: link,
        	users: users
        }
    );
}

function initializeFacebookAndPublishStories() {
	
	var popupArgs = getPopupArguments();
	initializeFacebook(apiKey, function() {
		facebookLogin(function() {
			var currentUserId = FB.Connect.get_loggedInUser();

			FB.Facebook.apiClient.fql_query(
                    format('select publish_stream from permissions where uid = {0}', currentUserId),
                    function(permissions) {

                    	var hasPermission = permissions != null && 0 < permissions.length ? permissions[0].publish_stream == 1 : false;

                    	if (hasPermission || null == popupArgs.users || 1 == popupArgs.users.length) {
                    		publishStories(popupArgs, hasPermission);
                    	} else {
                    		// Call this if no permissions are granted
                    		FB.Connect.showPermissionDialog("publish_stream", function(permissions) {
                    			hasPermission = 0 <= permissions.indexOf("publish_stream");
                    			publishStories(popupArgs, hasPermission);
                    		});
                    	}
                    }
                );
		}, true);
	});
}

function startPublishingStories() {
	var popupArgs = getPopupArguments();
	var currentUserId = FB.Connect.get_loggedInUser();

    FB.Facebook.apiClient.fql_query(
        format('select publish_stream from permissions where uid = {0}', currentUserId),
        function(permissions) {

            var hasPermission = permissions != null && 0 < permissions.length ? permissions[0].publish_stream == 1 : false;

            if (hasPermission || null == popupArgs.users || 1 == popupArgs.users.length) {
                publishStories(popupArgs, hasPermission);
            } else {
                // Call this if no permissions are granted
                FB.Connect.showPermissionDialog("publish_stream", function(permissions) {
                    hasPermission = 0 <= permissions.indexOf("publish_stream");
                    publishStories(popupArgs, hasPermission);
                });
            }
        }
    );
}

function publishStories(popupArgs, hasPermission) {
	var users = popupArgs.users || [null];
	var link = popupArgs.link;

	facebookLogin(function() {
	    var currentUserId = FB.Connect.get_loggedInUser();

	    // Get some info of the current user
	    FB.Facebook.apiClient.users_getInfo([currentUserId], ['name'], function(userInfo) {
	        var userName = userInfo[0].name;

	        var publish = function(index) {
	            if (index >= users.length) {					
	                window.close();
	                return;
	            }

	            var attachment = {
	                name: 'tmn Dia dos Namorados',
	                href: link,
	                caption: 'Love Movie Maker',
	                description: userName + ' acabou de criar um vídeo no site do dia dos namorados da tmn. Cria o teu também e envia a quem mais gostas!',
	                media: [
				    {
				        type: 'image',
				        src: 'http://www.tmn.pt/TMN Institucional/Minisites/Namorados2010/images/site-logo.jpg',
				        href: link
				    }
			    ]
	            };

	            var actionLinks = [{ text: 'Ver', href: link}];

	            FB.Connect.streamPublish('', attachment, actionLinks, users[index], 'Envia a tua mensagem.', function() {
	                publish(index + 1);
	            }, hasPermission);
	        }

	        publish(0);
	    });
	});
}


//--------------
function thisMovie(movieName) {
         if (navigator.appName.indexOf("Microsoft") != -1) {
             return window[movieName];
         } else {
             return document[movieName];
         }
     }
