/**
 * Initialize the facebook app asynchronously
 */
window.fbAsyncInit = function() {
	FB.init({
		appId      : '126807237378361', // App ID
		status     : true, // check login status
		logging	   : false,
		cookie     : true, // enable cookies to allow the server to access the session
		oauth      : true, // enable OAuth 2.0
		xfbml      : true  // parse XFBML
    });
};

/**
 * This object provides methods to call the ExternalInterface of the Tape.tv player.
 */
var tapePlayerAPI = {
    
    /**
     * Loads a specific channel with a given id.
     *
     * @param id The id of the channel to be loaded as string.
     */
    loadChannel: function(id) {
        try {
            swfobject.getObjectById(playerId).loadChannel(id);
        } catch(e) {
            alert("Could not loadChannel. " + id);
        }
    },

    /**
     * Loads a specific deeplink channel with a given channel id.
     *
     * @param id The id of a video to be loaded as string.
     */
    loadDeeplinkChannel: function(id) {
        try {
            swfobject.getObjectById(playerId).loadDeeplinkChannel(id);
        } catch(e) {
            alert("Could not loadDeeplinkChannel. " + id);
        }
    },

    /**
     * Loads the default channel.
     */
    loadDefaultChannel: function() {
        try {
            swfobject.getObjectById(playerId).loadDefaultChannel();
        } catch(e) {
            alert("Could not loadDefaultChannel.");
        }
    },

    /**
     * Loads a specific artist channel with a given artist id.
     *
     * @param id The id of the channel to be loaded as string.
     */
    loadArtistChannel: function(id) {
        try {
            swfobject.getObjectById(playerId).loadArtistChannel(id);
        } catch(e) {
            alert("Could not loadArtistChannel. " + id);
        }
    },

    /**
     * Loads a specific mixtape channel with a given channel id.
     *
     * @param id The id of the channel to be loaded as string.
     */
    loadMixtapeChannel: function(id) {
        try {
            swfobject.getObjectById(playerId).loadMixtapeChannel(id);
        } catch(e) {
            alert("Could not loadMixtapeChannel. " + id);
        }
    },

    /**
     * Loads the more like this channel with a given video id.
     *
     * @param id The id of the channel to be loaded as string.
     */
    loadMoreLikeThisChannel: function(id) {
        try {
            swfobject.getObjectById(playerId).loadMoreLikeThisChannel(id);
        } catch(e) {
            alert("Could not loadMoreLikeThisChannel. " + id);
        }
    },
    
    /**
     * Refresh the userdata
     * 
     * @param data the user data xml
     * @param callback method to call after completion, expects a boolean retrun value
     */
    refreshUser: function(data, callback) {
        try {
            swfobject.getObjectById(playerId).refreshUser(data);
            callback.call(this, true);
        } catch(e) {
        	//alert("Refresh User has failed with " + e);
        	callback.call(this, false);
        }    	
    },
    
    /**
     * set the facebook social Mode
     * 
     * @param mode
     */
    setMode: function(mode) {
    	try {
    		swfobject.getObjectById(playerId).setMode(mode);
    	} catch(e) {
    		alert("Mode setting failed with " + e);
    	}
    }
    
    
}

/**
 * Section with global functions
 */

/**
 * open a share window from flash
 */
function openShareWindow(url, parameters) {
	window.open(url, 'tapeTvWindow', parameters);
	return true;
}

/**
 * change browser history in HTML5 browsers
 */
function changeHistory(title, url) {
	//History.replaceState(null, title, url);
}

/**
 * initialize the history object
 */
(function(window,undefined){
	var History = window.History; // Note: We are using a capital H instead of a lower h
})(window);


//Methods used by facebook

// Permissions that are needed for the app
var permsNeeded = ['email', 'publish_actions'];

// Function that checks needed user permissions
function promptForPerms() {
	FB.api('/me/permissions', function(response) {
		var permsArray = response.data[0];
		var permsToPrompt = [];
		for (var i in permsNeeded) {
		  if (permsArray[permsNeeded[i]] == null) {
		    permsToPrompt.push(permsNeeded[i]);
		  }
		}
		if (permsToPrompt.length > 0) {
		  return true;
		} else {
		  return false;
		}
	});
};

/**
 * method called by the player to start facebook interaction
 */
function setupComplete() {
	FB.getLoginStatus(function(response) {
	  if (response.authResponse) {
		 var override = false;
	     FB.api('/me', function(response) {
		 if (window.location.hash != null) {
			hashString = window.location.hash;
			hashString = hashString.substring(1);
			hashArray = hashString.split('&');
			for (entry in hashArray) {
				entryArray = hashArray[entry].split('=');
				if (entryArray.length > 1) {
					if(entryArray[0] == "access_token") {
						override = true;
					}
				}
			}
		 }
		 loginUser(response.email,response.id,override,false);
	     });		  
	  } else {
	   
	  }
	});
}

function loginFBUser() {
	FB.login(function(response) {
	   if (response.authResponse) {
	     FB.api('/me', function(response) {
		    loginUser(response.email,response.id,true,false);
            });
	   } else {
	     //showOverlay(101);
	   }
	 }, {scope: 'email,publish_actions'});
}


function registerFBUser() {
	FB.login(function(response) {
	   if (response.authResponse) {
	     FB.api('/me', function(response) {
	    	 loginUser(response.email,response.id,true,false);
	     });
	   } else {
	     //showOverlay(101);
	   }
	 }, {scope: 'email,publish_actions'});
}

function loginUser(femail, id, useroverride, usermerge, callback) {
	booleanResult = false;
	$.ajax({
		url : '/tapeMVC/services/facebook/login/'+id,
		data : {email : femail, override : useroverride, merge : usermerge},
		dataType : 'text',
		async : false,
		success : function(data) {
			xmlDoc = $.parseXML(data);
			$xml = $(xmlDoc);
			$action = $xml.find("action");
			action = $action.text();
			if (action != "") {
				booleanResult = doAction.call(this, action, [femail, id, true, true]);
			} else {
				tapePlayerAPI.refreshUser(data, function(ret) {
					booleanResult = ret;
				});
				if (callback != null) {
					callback.call(this);
				}
			}
			
		}
	});
	return booleanResult;
}

function doAction(action, params) {
	result = false;
	switch (action) {
		case "merge":
			getMergeConfirm(function(ret) {
				if(ret) {
					trace(FacebookWrapper.enableSocialMode);
					callback = null;
					if(FacebookWrapper.enableSocialMode) {
						callback = FacebookWrapper.socialMode;
					}					
					result = loginUser.call(this, params[0], params[1], params[2], params[3], callback);
				} else {
					FacebookWrapper.enableSocialMode = false;
				}
			})
			break;
		case "connected_fbaccount":
			FacebookWrapper.enableSocialMode = false;
			getUserInfoDialog("fbuser", function(ret) {
				if(ret) {
					$.get('/tapeMVC/services/facebook/deactivate',		
							function(data) {
								$.get('/tapeMVC/services/facebook/disconnect',		
										function(data) {
											try {
									 			swfobject.getObjectById(playerId).refreshUser(data);
											} catch(e) {
												alert("Request has failed with " + e);
											}
										}, 
										'text'
									);
							}, 
							'text'
						);
					
				}
			})
			break;
		case "connected_tapeaccount":
			FacebookWrapper.enableSocialMode = false;
			getUserInfoDialog("tapeuser", function(ret) {
				if(ret) {
					$.get('/tapeMVC/services/facebook/deactivate',		
							function(data) {
								$.get('/tapeMVC/services/facebook/disconnect',		
										function(data) {
											try {
									 			swfobject.getObjectById(playerId).refreshUser(data);
											} catch(e) {
												alert("Request has failed with " + e);
											}
										}, 
										'text'
									);
							}, 
							'text'
						);
				}
			})			
			break;
		case "connected_account":
			getUserInfoDialog("tapeuser", function(ret) {
				if(ret) {
					//loginUser(params[0], params[1], params[2], params[3]);					
				}
			})			
			break;
	}
	return result;
}

function sendToTimeline(url, duration) {
	var videoUrl = "http://www.tape.tv/vid/" + url;
	FB.getLoginStatus(function(response) {
		  if (response.authResponse) {
			  FB.api('/me/permissions', function(response) {
					var permsArray = response.data[0];
					var permsToPrompt = [];
					for (var i in permsNeeded) {
					  if (permsArray[permsNeeded[i]] == null) {
					    permsToPrompt.push(permsNeeded[i]);
					  }
					}
					if (permsToPrompt.length > 0) {
						FB.login(function(response) {
							   if (response.authResponse) {
							     FB.api('/me', function(response) {
							    	 sendToTimeline(url, duration);
							    });
							   } else {
							     //showOverlay(101);
							   }
							 }, {scope: 'email,publish_actions'});
					} else {
						if(FacebookWrapper.postId != null) {
							FB.api(FacebookWrapper.postId, 'post', { expires_in : 0 }, function(response) {
								  if (!response || response.error) {
								    trace(response.error.message);
								  } else {
									//trace("updated");
								  }
								});				
						}
						FB.api('/me/video.watches', 'post', { video : videoUrl, expires_in : duration }, function(response) {
						  if (!response || response.error) {
						    //alert('An error occured:' + response.error.message);
						    trace(response.error.message);
						  } else {
							FacebookWrapper.postId = response.id;
							//trace('Post ID: ' + response.id);
						  }
						});
					}
				})			  
		  } else {
			FB.login(function(response) {
			   if (response.authResponse) {
			     FB.api('/me', function(response) {
				    loginUser(response.email,response.id,true,false);
		            });
			   } else {
			     //showOverlay(101);
			   }
			 }, {scope: 'email,publish_actions'});
		  }
		});	
}

function showOverlay(otype) {
	$.fancybox({
	 href: '/tapeMVC/services/facebook/overlay/'+otype,
	 type: 'iframe',
	 padding: 0,
	 margin:0,
	 width:640,
	 height:600,
	 enableEscapeButton:true
	});
}

 function showMergeConfirm() {
	 getMergeConfirm(function(ret) {
			alert(ret)
		})
 }


function getMergeConfirm(callback) {
	var ret;
	var dialog = new TapeDialog(
				  "confirm",
			      "merge",
				  true,
			      "hey, hier ist nicht genug platz f&uuml;r zwei accounts.",
			      "deshalb verbinden wir deinen tape.tv und facebook account. einverstanden?"
			      );	
	$.fancybox({
		modal : true,
		padding:0,
		margin:0,
		width:680,
		overlayColor : '#000',
		overlayOpacity : 1,
		content : dialog.dialog(),
		onComplete : function() {
		$.fancybox.center();
		$("#merge_cancel").click(function() {
		ret = false;
		$.fancybox.close();
		})
		$("#merge_ok").click(function() {
		ret = true;
		$.fancybox.close();
		})
		},
		onClosed : function() {
		callback.call(this,ret);
		}
	});
}


function getUserInfoDialog(info, callback) {
	var ret;
	text = "<span class=\"error\">";
	text += "hey, diesen facebook account kennen wir doch.";
	text += "<br /><br />";
	text += "um den social mode f&uuml;r dieses profil zu aktivieren, musst du folgendes tun:<br />";
	text += "log dich mit diesem facebook account bei uns ein und trenne diese verbindung dann in den profileinstellungen (fb-connect trennen). danach kannst du in einem neuen profil den social mode aktivieren!";
	text += "</span>";
	var dialog = new TapeDialog(
				"ok",
			      "info",
				true,
				null,
				text
				 );
	switch (info) {
		case "fbuser":
			//dialog.setTitle("");
			//dialog.setText("hey, hast du diesen facebook account schon mal mit tape.tv verbunden? falls ja, bitte trenne diese verbindung zuerst.");
			break;
		case "tapeuser":
			//dialog.setTitle("");
			//dialog.setText("hey, hast du diesen facebook account schon mal mit tape.tv verbunden? falls ja, bitte trenne diese verbindung zuerst.");
			break;
	}

	//dialog.setText("hey, hast du diesen facebook account schon mal mit tape.tv verbunden? falls ja, bitte trenne diese verbindung zuerst.");

	$.fancybox({
		modal : true,
		padding:0,
		margin:0,
		width:680,
		overlayColor : '#000',
		overlayOpacity : 1,
		content : dialog.dialog("error"),
		onComplete : function() {
		$.fancybox.center();
		$("#info_ok").click(function() {
		ret = true;
		$.fancybox.close();
		})
		},
		onClosed : function() {
		callback.call(this,ret);
		}
	});
}


function logoutUser() {
	FacebookWrapper.logout();
}

/** 
 * This object encapsualtes the whole FB interaction with the backend
 */
var FacebookWrapper = {
		
		changeSocialModeTrigger : null,
		
		enableSocialMode : false,
		
		
		
		postId : null,
		
		/**
		 * login via facebook
		 */
		login : function(femail, id, useroverride, usermerge) {
		
		},
		
		loginStatus : function() {
			var status = 'unknown';
			FB.getLoginStatus(function(response) {
				status = response.status;
  		    });
			return status;
		},
		/**
		 * triggers the logout
		 */
		logout : function() {
			var result = false;
			this.fblogout();
			$.post('/tapeMVC/tape/auth/logout',
					{},
					function(data) {
						tapePlayerAPI.refreshUser(data, function(ret) {
							result = ret;
						});
					}, 
					'text'
				);
		},
		/**
		 * checks wether the socialmode is enabled
		 */
		socialMode : function() {
			$.ajax({
				url : '/tapeMVC/services/facebook/connect',
				dataType : 'text',
				async : false,
				success : function(data) {
					tapePlayerAPI.setMode("facebook");
				}
			});			 		
		},
		/**
		 * starts an API call
		 */
		apiCall : function(callback, endpoint) {
			 target = endpoint ? endpoint : '/me';
		     FB.api(target, function(response) {
		    	 callback.call(this, response);
		     });			
		},
		/**
		 * disconnect a user
		 */
		disconnect : function() {
			var result = false;
			this.fblogout();
			$.get('/tapeMVC/services/facebook/logout', function(data) {
				tapePlayerAPI.refreshUser(data, function(ret) {
					result = ret;
				});
				}, 
				'text'
			);
			return result;
		},
		/**
		 * single facebook logout
		 */
		fblogout : function() {
			$.ajax({
				url : '/tapeMVC/services/facebook/getfacebookuserinfo',
				dataType : 'xml',
				async : false,
				success : function(data) {
					$facebookId = $(data).find("facebookId");
					if($facebookId.text() != "") { 
						FB.logout(function(response) {
						  //trace("FB-User has been logged out");
						}); 
					}
				}
			});
		}

}

/**
 * class to create custom tape dialogs
 */
function TapeDialog(type, name, showBtn, title , text){
		this.title=title;
		this.type=type;
		this.name=name;
		this.text=text;
		this.showButton=showBtn;
		this.caption="";
		
		this.setCaption = function(val) {
			this.caption = val;
		}
		
		this.setName = function(val) {
			this.name = val;
		}
		
		this.setTitle = function(val) {
			this.title = val;
		}
		
		this.setText = function(val) {
			this.text = text;
		}

		this.buttons = function(type, name, caption) {
			var buttonHTML = " ";
			switch(type) {
				case "confirm":
					confirmButtonCancel = buildHTML("input", {
							"id"   : name+"_cancel",
							"type" : "button",
							"value": ""
					})
					confirmButtonOk = buildHTML("input", {
							"id"    : name+"_ok",
							"type"  : "button",
							"value" : ""
					})
					buttonHTML = confirmButtonCancel + confirmButtonOk;
					break;
				case "ok":
					confirmButtonOk = buildHTML("input", {
							"id"    : name+"_ok",
							"type"  : "button",
							"value" : ""
					})
					buttonHTML = confirmButtonOk;
					break;					
			}
			return buildHTML("div", buttonHTML, {"class" : "buttons"});
		}
		
		this.dialog = function(addCSS) {
			content = "";
			content += this.title ? buildHTML("h2", this.title, {}) : "";
			content += this.text ? buildHTML ("p", this.text, {}) : "";
			if(this.showButton) {
				content += this.buttons(this.type, this.name, this.caption);
			}
			addCSS = addCSS ? " "+addCSS : " ";
			html = buildHTML("div", content, {"class" :"dialogContent"+addCSS})
			return buildHTML("div", html, {"id" :"tapeDialog"})
		}
		
		buildHTML = function(tag, html, attrs) {
			  if (typeof(html) != 'string') {
			    attrs = html;
			    html = null;
			  }
			  var h = '<' + tag;
			  for (attr in attrs) {
			    if(attrs[attr] === false) continue;
			    h += ' ' + attr + '="' + attrs[attr] + '"';
			  }
			  return h += html ? ">" + html + "</" + tag + ">" : "/>";
		}
}

function disconnectUser() {
	FacebookWrapper.disconnect();
}

function activateSocialMode() {
    getSocialModeConnect(function(ret){
    	socialModeSuccess=ret;
	});
    
    FacebookWrapper.enableSocialMode = true;
    
    trace("socialModeSuccess: " + socialModeSuccess);
 	if (socialModeSuccess == "register") {
		FB.login(function(response) {
 		   if (response.authResponse) {
 		     FB.api('/me', function(response) {
 		    	 var res = loginUser(response.email,response.id,true,false);
 		    	 if(res) {
 					$.ajax({
 						url : '/tapeMVC/services/facebook/connect',
 						dataType : 'text',
 						async : false,
 						success : function(data) {
	 			 			 getSocialModeConnect(function(ret){
	 			 				socialModeSuccess = ret;
	 			 			})
 						}
 					});			 		
 		    	 }
 		     });
 		   } else {

 		   }
		}, {scope: 'email,publish_actions'});
 	}
 	else if (socialModeSuccess == "login") {
		$(FB.login(function(response) {
			   if (response.authResponse) {
			     FB.api('/me', function(response) {
				    if(loginUser(response.email,response.id,true,false)) {
				 		 getSocialModeConnect(function(ret){
				  			socialModeSuccess = ret;
				  		});
				    }
		         });
			   } else {
			     //showOverlay(101);
			   }
			 }, {scope: 'email,publish_actions'})
	     ).ready(function() {
 
	     })
	    		 
 	}
  	
 	if (socialModeSuccess != "<timelineconnect></timelineconnect>") {
 		socialModeSuccess = null;
 	}
 	return socialModeSuccess;
}

function getSocialModeConnect(callback) {
	var ret = null;
	FB.getLoginStatus(function(response) {
		if (response.authResponse) {
			trace("Fuehre connect durch");
			$.ajax({
				url : '/tapeMVC/services/facebook/connect',
				dataType : 'text',
				async : false,
				success : function(data) {
					xmlDoc = $.parseXML(data);
                    $xml = $(xmlDoc);
					$action = $xml.find("action");
					action = $action.text();
					if (action != "") {
					    return callback.call(this, action);
					} else {
						ret = "<timelineconnect></timelineconnect>";
						return callback.call(this, ret);
					}
				}
			});
		  } else {
			return callback.call(this, "login");
		  }
		});
}

function trace(msg) {
	 if (window.console) {
		 console.info(msg);
     }
}

/**
 * ONTAPE methods
 */
//var FB_AUTH_URL			= 'https://www.facebook.com/dialog/oauth?client_id=107036659385505';
//var REDIRECT_URI		= 'http://fbconnect.tape.tv/api/tapeTvPlayer.php%3Faction=handleFacebookRedirect';
var FB_AUTH_URL			= 'https://www.facebook.com/dialog/oauth?client_id=118299841586510';
var REDIRECT_URI		= 'http://chat.ontape.tv/tapechat/api/onTapePlayer.php%3Faction=handleFacebookRedirect%26src=tape';
var MAX_AUTH_RETRIES	= '600';
var RETRY_TIME			= '1000';
var PLAYER_ID			= 'PID';
var RETRY_NUMBER		= 0;
var TIMEOUT_HANDLE		= null;
var CLIENT_ID			= '';


/**
* Opens the fb authentification popup window
* @param integer playerId
* @return boolean success
*/
function openFacebookAuthWindow(playerId)
{
	CLIENT_ID = playerId;
	RETRY_NUMBER = 0;

	window.open
	(
		FB_AUTH_URL +
		'&display=popup' +
		'&scope=publish_stream' +
		'&redirect_uri='+ REDIRECT_URI +
		'%26'+ PLAYER_ID +'='+ playerId,
		'_blank',
		'width=700,height=400'
	);
	TIMEOUT_HANDLE =  window.setTimeout("waitForAuthCookie()", RETRY_TIME);

	return true;
}


/**
* Looks for the authentification cookie
* @return string/false cookie result
*/ 
function getAuthCookie()
{
	var exp = 'tc_fb_auth=' + CLIENT_ID;
	var reg = new RegExp(exp);

	if(reg.exec(document.cookie) == null)
	{
		return false;
	}

	return reg.exec(document.cookie);
}


/**
* Waits until the  timeout or the authentification has been reached
* @return boolean success
*/
function waitForAuthCookie()
{
	var authCookie = getAuthCookie();

	if
	(
		! authCookie
		||
		MAX_AUTH_RETRIES <= RETRY_NUMBER
	)
	{
		if(MAX_AUTH_RETRIES > RETRY_NUMBER)
		{
			RETRY_NUMBER++;
			TIMEOUT_HANDLE = window.setTimeout("waitForAuthCookie()", RETRY_TIME);
		}

		return false;
	}

	if(TIMEOUT_HANDLE)
	{
		clearTimeout(TIMEOUT_HANDLE);
	}

	notifyTapePlayer((authCookie == 'tc_fb_auth=' + CLIENT_ID ? true : false));
	return true;
}

/**
* Notify the flash player about the authentification result
* @param boolean status
* @return boolean success
*/
function notifyTapePlayer(status)
{
	swfobject.getObjectById(playerId).callbackFacebookAuth(status);
	return true;
}

function layerOn() 
{
	try 
	{
		parent.turnLayerOn();
	} 
	catch (err) {}
}

function layerOff() 
{
	try 
	{
		parent.turnLayerOff();
	} 
	catch (err) {}
}

function doCount(counter)
{
	try 
	{
		parent.count(counter);
	} 
	catch (err) {}
}

function doRemoveCounter()
{
	try 
	{
		parent.removeCounter();
	} 
	catch (err) {}
}

