/*******************************************************************************
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 *
 *
 * Copyright (c) 2008 - 2010 Sun Microsystems Inc. All Rights Reserved
 *
 * This file is available and licensed under the following license:
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of Sun Microsystems nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ******************************************************************************/

/*
 *Require:
 *- jquery.js - 1.2.6 and greater
 *- jquery.template.js
 *- login_templates.js
 *
 *Usage:
 */


;
(function($) {
	function _(str, args) {
		return $.i18n('login', str, args);
	}

	$.FbConnect = function() {
		//--------MEMBER VARS
		this.ID = 1;
		this.CONTAINER_ID = "fbconnect_" + this.ID;
		this.CS = "#" + this.CONTAINER_ID + " ";

		//templates
		this.facebook_api_key = "";
		this.template_widget = $.template(TEMPLATE_FBCONNECT_WIDGET);
		this.template_item = $.template(TEMPLATE_FBCONNECT_ITEM);

		this.WEBSERVICE_URL = WEBSERVICE_RESSOURCE_PATH+"/jersey/Facebook/fbstatus";
		this.AUTH_WEBSERVICE_URL = "ceq-ws/jersey/Facebook/authorize";
		/* TODO: Turn into a jndi configuration parameter */
		this.FACEBOOK_LOGIN_URL = "http://www.facebook.com/login.php";

		String.prototype.bool = function() {
		    return (/^true$/i).test(this);
		};

		//------------------------------------------------------------------------------
		//-------------------- CONTENT -------------------------------------------------
		//------------------------------------------------------------------------------

		this.removeContent = function() {
			$("#fbconnect_content").html('');
		};

		//------------------------------------------------------------------------------
		//-------------------- WAIT ----------------------------------------------------
		//------------------------------------------------------------------------------

		this.showWait = function() {
			$(this.CS + " #fbconnect_content").html("<div id='login_loading'><img width='12px' height='12px' src='" + WIDGET_RESSOURCE_PATH + "/ceq_siteconnect/images/wait.gif'/>&nbsp;Please wait...</div>");
		}

                  this.setWebserviceURL = function(urlvar) {
                        this.WEBSERVICE_URL = urlvar;
                    }

		this.showLoginLink = function(loginurl) {
			var link = document.createElement("a") ;
			if (loginurl.indexOf('?') != -1) {
				link.href = loginurl + '&goto=' + location.href;
			} else {
				link.href = loginurl + '?goto=' + location.href;
			}
			link.appendChild(document.createTextNode('Please login!'));
			$(this.CS + " #fbconnect_content").html('');
			$(this.CS + " #fbconnect_content").append(link);
		}

		this.showFacebookLoginLink = function(fbloginurl) {
			var nextUrl = $.url.setUrl(window.location).attr("base") + this.AUTH_WEBSERVICE_URL;

			var link = document.createElement("a") ;
			link.href = '#';
			var fblink = fbloginurl + '?api_key=' + facebook_api_key +
			             '&fbconnect=true&v=1.0&connect_display=popup&return_session=true' +
			             '&req_perms=read_stream,offline_access&next=' + nextUrl;
			link.onclick = function() {
				window.open(fblink, "popup", "width=640, height=500");
			}
			var img = document.createElement("img");
			img.setAttribute('src', 'http://static.ak.fbcdn.net/images/fbconnect/login-buttons/connect_light_large_long.gif');
			img.setAttribute('alt', 'Facebook Login');
			img.setAttribute('border', '0');
			link.appendChild(img);
			$(this.CS + " #fbconnect_content").html('');
			$(this.CS + " #fbconnect_content").append(link);
		}

		this.handleResponse = function(response) {
			//Check for error in response
			if (response.statusCode == '200') {
				fbloggedin = false;

				if (response.data.attributes != null) {

					$.each(response.data.attributes.entry, function(i, item) {
						if (item.key.$ == "apiKey") {
							facebook_api_key = item.value.$;
						}
						if (item.key.$ == "isLoggedIn") {
							fbloggedin = item.value.$.bool();
						}
					});
				}
				if (!fbloggedin) {
					if (facebook_api_key == "") {
						$(this.CS +" #fbconnect_content").html('');
						$(this.CS + "#fbconnect_content").append(document.createTextNode("Facebook API Key not configured"));
					} else {
						this.showFacebookLoginLink(this.FACEBOOK_LOGIN_URL);
					}
				} else {
					this.createItems(response.data);
				}
			} else if (response.statusCode == '403') {
				this.showLoginLink(response.url);
			} else {
				$(this.CS + "#fbconnect_content").append(document.createTextNode("Service not available"));
			}
		}

		this.createItems = function(result) {
			//show items
			thisobj = this;
			thisobj.removeContent();

			var itemObj = {};
			itemObj.GIVENNAME = result.givenname;
			itemObj.SURNAME = result.surname;
			itemObj.EMAIL = result.email;
			$(thisobj.CS + " #fbconnect_content").append(thisobj.template_item, itemObj);


		}
		//------------------------------------------------------------------------------
		//-------------------- LOAD ITEMS ----------------------------------------------
		//------------------------------------------------------------------------------


		this.loadItemsFromLocal = function() {
			//HTTP Status Code in Header
			var fbconnectwidget = this;

			$.ajax({
				type: "GET",
				url: this.WEBSERVICE_URL,
				dataType: "json",
				error: function (xhr, textStatus, errorThrown) {
					fbconnectwidget.removeContent();
					if (xhr.status == '403') {
						fbconnectwidget.showLoginLink(xhr.getResponseHeader('X-CeqLoginUrl'));
					} else {
						$(fbconnectwidget.CS + "#tagcloud_content").append(document.createTextNode("Service not available"));
					}
				},
				success: function(result) {
					fbconnectwidget.handleResponse(result);
				}
			});

		};


		//------------------------------------------------------------------------------
		//-------------------- DEPLOY --------------------------------------------------
		//------------------------------------------------------------------------------
		this.deploy = function(widgetid) {
			$('#' + widgetid).html("<div id='" + this.CONTAINER_ID + "' class='ceq_loginwidget' height='" + this.HEIGHT + "'></div>");
			var itemObj = {};
			itemObj.WIDGET_RESSOURCE_PATH = WIDGET_RESSOURCE_PATH;
			$(this.CS).append(this.template_widget, itemObj);
			this.showWait();
			this.loadItemsFromLocal();
		}
	};

})(jQuery);


