/**
 * @author ugur bozkaya
 * samsun
 */
 
var fbcUserId = -1;
var fbcFlashReady = -1;
var fbcERRORRESPONSE = "<xml><response result=\"ERROR\"/></xml>";
var fbcErrorAlert = -1;
var fbcUserIdRequestCount = 0;
var fbcFlashObjectId = "flashObj";
 
//http://www.w3schools.com/JS/js_cookies.asp
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date();
	exdate.setDate(exdate.getDate()+expiredays);
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}

//http://www.w3schools.com/JS/js_cookies.asp
function getCookie(c_name)
{
	if (document.cookie.length>0)
	  {
	  c_start=document.cookie.indexOf(c_name + "=");
	  if (c_start!=-1)
	    {
	    c_start=c_start + c_name.length+1;
	    c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	    }
	  }
	return "";
}


function fbcSetFlashObjectId(strId)
{
	fbcFlashObjectId = strId;
}
 
function fbcIsPopupLogin()
{
	var strCurrentURL = window.location.href;
	if(strCurrentURL.indexOf('doorId=414')>-1 )
		return true;
	
	return false;
}
 
function fbcSwitchAlertMode()
{
	if (fbcErrorAlert > 0) {
		fbcErrorAlert = 0;
		alert("Alert mode is OFF!");
	}
	else {
		fbcErrorAlert = 1;
		alert("Alert mode is ON!");
	}
}
 
function myAlert(strIn)
{
	if(fbcErrorAlert>0)
		alert(strIn);
}
 
function getFlashMovie(movieName){
	var isIE = navigator.appName.indexOf("Microsoft") != -1;
	return (isIE) ? window[movieName] : window.document[movieName];
}
 
function isArray(obj) {
	if(obj==null || obj == undefined)
		return false;
		
   if (obj.constructor.toString().indexOf("bject") == -1 && obj.constructor.toString().indexOf("rray") == -1)
      return false;
   else
      return true;
}
 
function CallFlash(strFunctionName, strFunctionArg){
	if(fbcFlashReady<1)
		return;
		
	myAlert(strFunctionName +'\n' +strFunctionArg);
	
	try {
		getFlashMovie(fbcFlashObjectId)[strFunctionName](strFunctionArg);
	}
	catch(err) {
		myAlert("CallFlash failed:" +strFunctionName +'\n' +strFunctionArg +'\n' +err.description);
	}
}	
 
function fbcPopupManualLogin(){
	
	var strDomainPrefix = 'http://host';
	var strURL=window.location.href;
	var strHostOffset = strURL.indexOf(".oddcast");
	if(strHostOffset>-1)
	{
		strDomainPrefix = strURL.substr(0,strHostOffset)				
	}
	
	var strPopupURL = strDomainPrefix +'.oddcast.com/includes/fbconnectpopup.html?appKey=' +fbcApplicationKey;
	var newwindow = window.open(strPopupURL, 'FacebookConnect', 'height=425,width=750');
	newwindow.moveTo(300,300);
	newwindow.focus()
	return false;
}
 
//This function is called from the popup window when user logs in
function fbcManualLoginDone(user_id)
{	
	FB.Connect.requireSession(false, function(){fbcGetConnectState(user_id);});	
}
 

function fbcPopupStreamPermissions(){

	if(fbcRequestStreamPermissions != true)
		return;	
	
	FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(perms){			
			if (perms!=1) {
				FB.Connect.showPermissionDialog("publish_stream", function(perms){
					myAlert("perms: " + perms);
					fbcPopupEmailPermissions();
				});
			}else {
				fbcPopupEmailPermissions();
			}
						
		}
	);
}
 

function fbcPopupEmailPermissions(){
	
	if(fbcRequestEmailPermissions != true)
		return;	
	
	FB.Facebook.apiClient.users_hasAppPermission("email", function(perms){			
			if (perms!=1) {
				FB.Connect.showPermissionDialog("email", function(perms){
					myAlert("perms: " + perms);
				});
			}			
		}
	);
}
 
//If the loged in user has extended permission for publishing streams
//it will return 1, else it will return 0
function fbcGetUserStreamPermissions(){
	
	FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(perms){			
			if (perms!=1) {
				CallFlash("fbcSetUserStreamPermissions", 0);
			}	
			else{
				CallFlash("fbcSetUserStreamPermissions", 1);
			}		
		}
	);
} 

//If the loged in user has extended permission for accesing his email address 
//it will return 1, else it will return 0
function fbcGetUserEmailPermissions(){
	
	FB.Facebook.apiClient.users_hasAppPermission("email", function(perms){			
			if (perms!=1) {
				CallFlash("fbcSetUserEmailPermissions", 0);
			}	
			else{
				CallFlash("fbcSetUserEmailPermissions", 1);
			}		
		}
	);
} 



function fbcOnConnected(user_id) {
		
	myAlert("fbcOnConnected: " +user_id);
		
	fbcFlashReady = 1;	
	fbcUserId = user_id;
	if (user_id == null || user_id == undefined) {
		
		if (fbcUserIdRequestCount < 6) {
			setTimeout(function(){
				FB.Connect.ifUserConnected(fbcOnConnected, fbcOnNotConnected)
			}, 500);
			fbcUserIdRequestCount++;
		}
		else{
			myAlert("Please refresh the page, something went wrong with facebook connect!");	
		}
	}
	else {
		try{
						
	     if (user_id > 0) {
		 	
			var curDate = new Date();		
			
		 	if (getCookie('fbcExtendedPermissionRequestTime') < curDate.getTime()) 
			{
				//this will first popup stream permissions then email permission (if required)
				fbcPopupStreamPermissions();
				
				var expTime = curDate.getTime();
				expTime += (300 * 1000); //expires in 60*5 seconds
				setCookie('fbcExtendedPermissionRequestTime', expTime, 1);
			}
		 }
		}catch(e){}		
	
		CallFlash("fbcSetConnectState", fbcUserId);
	}
}
 
function fbcOnNotConnected() {
	fbcFlashReady = 1;
	fbcUserId = 0;
	CallFlash("fbcSetConnectState", fbcUserId);
}
 
 
function fbcGetLoggedInUser() {
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.users_getLoggedInUser(function(result, ex) { 
			CallFlash("fbcSetLoggedInUser", fbcUserId);
		});
	 });
}
 
function fbcLogin() {
	
	if(fbcIsPopupLogin()){
		fbcPopupManualLogin();
		return;
	}
	
	FB.ensureInit (  function () {
		FB.Connect.requireSession(true);
	 });	 
}
 
function fbcLogout() {
	FB.ensureInit (  function () {
		FB.Connect.logout(null);
	});
}

function fbcGetConnectState(user_id) {
	
	//http://developers.facebook.com/docs/authentication/permissions
	//read_requests, read_stream, user_videos,user_status, user_events, user_activities, user_groups, user_likes, user_online_presence,user_notes, 
	//email, publish_stream, 
	//friends_activities,friends_events, friends_groups, friends_likes, friends_notes, friends_online_presence, friends_videos, 
	
	/*
	strDefaultPermissions = "user_about_me, user_birthday, user_education_history, read_friendlists,user_hometown, user_interests, user_location,";
	strDefaultPermissions+= "user_photo_video_tags, user_photos, user_relationships, user_religion_politics, user_website, user_work_history,";
	strDefaultPermissions+= "friends_about_me, friends_birthday, friends_education_history, friends_hometown, friends_interests,";
	strDefaultPermissions+= "friends_location, friends_photo_video_tags, friends_photos,";
	strDefaultPermissions+= "friends_relationships, friends_religion_politics, friends_status, friends_website, friends_work_history";
	*/
	
	strDefaultPermissions = "user_about_me, user_activities, user_birthday, user_education_history, user_events, user_groups, user_hometown,";
	strDefaultPermissions+= "user_interests, user_likes, user_location, user_notes, user_online_presence, user_photo_video_tags, user_photos,";
	strDefaultPermissions+= "user_relationships, user_relationship_details, user_religion_politics, user_status, user_videos, user_website,";
	strDefaultPermissions+= "user_work_history, email, read_friendlists, read_insights, read_mailbox, read_requests, read_stream, xmpp_login,";
	strDefaultPermissions+= "ads_management, user_checkins, friends_about_me, friends_activities, friends_birthday, friends_education_history,";
	strDefaultPermissions+= "friends_events, friends_groups, friends_hometown, friends_interests, friends_likes, friends_location, friends_notes,";
	strDefaultPermissions+= "friends_online_presence, friends_photo_video_tags, friends_photos, friends_relationships, friends_relationship_details,";
	strDefaultPermissions+= "friends_religion_politics, friends_status, friends_videos, friends_website, friends_work_history, friends_checkins";
	
	
	/*
	strDefaultPermissions = "";
	strDefaultPermissions += "user_about_me, friends_about_me, user_photo_video_tags, friends_photo_video_tags, user_photos, friends_photos";
	strDefaultPermissions += ", friends_location, user_location, read_stream";
	*/
	
	
	
	strPermissions = strDefaultPermissions;
	//If the permissions are not set just use the default permissions
	try{	
		if(typeof(fbcRequiredApplicationPermissions)==undefined){
			//strPermissions = strDefaultPermissions;
		}else{
			strTemp = '';
			strTemp += fbcRequiredApplicationPermissions;
			
			if(strTemp.length>5){			
				strPermissions = fbcRequiredApplicationPermissions;
			}
		}
	}catch(err){
		strPermissions = strDefaultPermissions;
	}	
	
	myAlert(strPermissions);
	var initObject = new Object();		
	initObject.ifUserConnected = fbcOnConnected;
	initObject.ifUserNotConnected = fbcOnNotConnected;	
	initObject.permsToRequestOnConnect = strPermissions;	
	
	if(fbcUserId == null || fbcFlashReady<1) {		
		FB_RequireFeatures(["Api"], function(){
  			FB.Facebook.init(fbcApplicationKey, "/plugins/fbconnect/xd_receiver.php", initObject);  			
  		});
	}
	else {	
		CallFlash("fbcSetConnectState", fbcUserId);
	}
}
 
function fbcArrayToXML(inputArray)	{
 
	var retVal = "";
	var key ="";
	
	try {
		for (key in inputArray)	{		
			if(isArray(inputArray[key])) {
				retVal = retVal + "<" +key +">";
				retVal = retVal + fbcArrayToXML(inputArray[key]);
				retVal = retVal + "</" +key +">\n"
			}
			else {				
			   retVal = retVal + "<" +key +">";
			   var strTempVal = inputArray[key];
			   if (inputArray[key] != null && inputArray[key] != undefined) {
			   		//retVal = retVal + inputArray[key];
			   		
			   		strTempVal = strTempVal + '';
			   		strTempVal = strTempVal.replace(/</g, " ");
			   		strTempVal = strTempVal.replace(/>/g, " ");
			   		retVal = retVal + strTempVal;			   		
			   }
			   retVal = retVal + "</" +key +">\n";
	   		}
		}
	}
	catch(err) {
		myAlert("fbcArrayToXML failed!\n" +key +"\n" +inputArray[key] +"\n" +err.name +"\n" +err.message +"\n" +err.description);		
	}
	
	return retVal;
}
 
function fbcGetUserInfo() {
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.users_getInfo(fbcUserId, "uid, name, pic_square, pic_big, current_location, sex", function(result, ex) { 
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{					
				retVal = "<xml><response result=\"OK\">";			
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>";			
			}
			CallFlash("fbcSetUserInfo", retVal);
		});
	 });
}
 

function fbcGetDetailedUserInfo(strFriendId) {
	 
	
	var strFQLfields = "";
	/*
	strFQLfields += "uid , first_name , middle_name , last_name , name , pic_small , pic_big , pic_square , pic , "
	strFQLfields += "affiliations , profile_update_time , timezone , religion , birthday , birthday_date , sex , "
	strFQLfields += "hometown_location , meeting_sex , meeting_for , relationship_status , significant_other_id , political , "
	strFQLfields += "current_location , activities , interests , is_app_user , music , tv , movies , books , quotes , about_me , "
	strFQLfields += "hs_info , education_history , work_history , notes_count , wall_count , status , has_added_app , online_presence , "
	strFQLfields += "locale , proxied_email , profile_url , email_hashes , pic_small_with_logo , pic_big_with_logo , pic_square_with_logo , "
	strFQLfields += "pic_with_logo , allowed_restrictions , verified , profile_blurb , family , username , website , is_blocked , contact_email , email "
	*/
	
	strFQLfields += "uid, name, current_location, sex, meeting_sex, birthday, hometown_location, education_history, "
	strFQLfields += "books, activities, interests, movies, music, political, relationship_status, "
	strFQLfields += "significant_other_id, work_history, tv, family"
	
	
	//strFQLfields += "hometown_location, relationship_status, birthday_date, political, religion, meeting_sex"
	//strFQLfields += ", activities, interests, music, tv, movies, books, quotes, about_me"
	//strFQLfields += ", education_history, work_history"

	
	var strFQL = 'SELECT ' +strFQLfields +' FROM user WHERE uid=\'' +strFriendId +'\''
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) { 				
			
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			
			CallFlash("fbcSetDetailedUserInfo", retVal);			
		});
	 }); 
}


function fbcGetFriendsInfo(bIncludeYourSelf, nNumberOfFriends) {
		
	var strQueryLimit = '';
	if(nNumberOfFriends!=undefined)
		strQueryLimit = ' LIMIT ' +nNumberOfFriends;
 
	var strFQL = 'SELECT uid, name, pic_square, pic_big, current_location, sex, meeting_sex, relationship_status FROM user WHERE ( uid IN ';
	strFQL += ' ( SELECT uid2 FROM friend WHERE uid1=\'' +fbcUserId +'\' )';
 
 	if (bIncludeYourSelf != undefined && bIncludeYourSelf == true) {
		strFQL += ' OR uid=\'' + fbcUserId + '\'';
	}
	
	strFQL += ' ) '; //end of user id restrictions
 
	strFQL += ' AND strlen(pic_square)>7  ';
	strFQL += ' AND strpos(name, "\'")<0  ';
	
	strFQL += ' AND (strlen(current_location)<1 OR (';		
	strFQL += '		strpos(current_location.city, "\'")<0  ';	
	strFQL += ' AND strpos(current_location.state, "\'")<0  ';
	strFQL += ' AND strpos(current_location.country, "\'")<0  ';
	strFQL += ' AND strpos(current_location.zip, "\'")<0  )) ';
	
	
	
	strFQL += ' ORDER BY name DESC ' +strQueryLimit;
	
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) { 				
			
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			
			CallFlash("fbcSetFriendsInfo", retVal);			
		});
	 }); 
}
 
 
function fbcGetSubjectsFromPictureId(nPictureId){
			
	var strFQL = 'SELECT subject, text, xcoord, ycoord FROM photo_tag WHERE pid=' +nPictureId;
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
 
				CallFlash("fbcSetSubjectsFromPictureId", retVal);
			}
			else
			{
				CallFlash("fbcSetSubjectsFromPictureId", retVal);
			}
		});
	 });
}
 
function fbcGetUserPictures(nNumberOfPictures, nCallNumber) {
	
	var strQueryLimit = '';
	if(nNumberOfPictures!=undefined)
		strQueryLimit = 'LIMIT ' +nNumberOfPictures;
		
	var strFQL = 'SELECT pid, src, src_big, src_small, created FROM photo WHERE pid IN ';
	strFQL += ' ( SELECT pid FROM photo_tag WHERE subject=\'' +fbcUserId +'\' ) ';
	strFQL += ' AND strlen(src_big)>7 ';	
	strFQL += ' ORDER BY created DESC ' +strQueryLimit;
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
 
				CallFlash("fbcSetUserPictures", retVal);
			}
			else if(nCallNumber!=1) 
			{
				fbcGetUserPictures(nNumberOfPictures, 1);
			}
			else
			{
				CallFlash("fbcSetUserPictures", retVal);
			}
		});
	 });
}
 
 
function fbcGetFriendsPictures(fbcFriendId, nNumberOfPictures) {
	
	var strQueryLimit = '';
	if(nNumberOfPictures!=undefined)
		strQueryLimit = 'LIMIT ' +nNumberOfPictures;
		
	var strFQL = 'SELECT pid, src, src_big, src_small, created FROM photo WHERE pid IN ';
	strFQL += ' ( SELECT pid FROM photo_tag WHERE subject=\'' +fbcFriendId +'\' ) ';
	strFQL += ' AND strlen(src_big)>7 ';	
	strFQL += ' ORDER BY created DESC ' +strQueryLimit;
	
	myAlert("fbcFriendId: "+fbcFriendId +"\nnNumberOfPictures: " +nNumberOfPictures);
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			CallFlash("fbcSetFriendsPictures", retVal);	
		});
	 });
}
 
 
 
function fbcGetProfileAlbum(strFriendId, nNumberOfPictures) {
	
	var requestedId = fbcUserId;
	
	if(strFriendId!=undefined)
		requestedId = strFriendId;
	
	var strQueryLimit = '';
	if(nNumberOfPictures!=undefined)
		strQueryLimit = 'LIMIT ' +nNumberOfPictures;
		
	var strFQL = 'SELECT pid, src, src_big, src_small, created FROM photo WHERE aid IN ';
	strFQL += ' ( SELECT aid FROM album WHERE type=\'profile\' AND owner=\'' +requestedId +'\' )';
	strFQL += ' AND strlen(src_big)>7 ';	
	strFQL += ' ORDER BY created DESC ' +strQueryLimit;
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			CallFlash("fbcSetProfileAlbum", retVal);	
		});
	 }); 
}
 
function fbcGetProfileAlbumCover(strFriendId) {
	
	var requestedId = fbcUserId;
	
	if(strFriendId!=undefined)
		requestedId = strFriendId;
	
	var strFQL = 'SELECT pid, src, src_big, src_small, created FROM photo WHERE pid IN ';
	strFQL += ' ( SELECT cover_pid FROM album WHERE type=\'profile\' AND owner=\'' +requestedId +'\' )';
	strFQL += ' AND strlen(src_big)>7 ';	
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			CallFlash("fbcSetProfileAlbumCover", retVal);	
		});
	 }); 
}
 
 
function fbcSendNotifications(fbcFriendIds, strNotification) {
		
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.notifications_send(fbcFriendIds, strNotification, function(result, ex) {  
			myAlert("Notification is sent to: " +result);	
		});
	 });
}
 
function randOrd()
{
	return (Math.round(Math.random())-0.5); 
}
 
function fbcSendRandomNotifications(strNotification, nNumberOfNotifications)
{			
	if(nNumberOfNotifications==undefined)
		nNumberOfNotifications = 100;
	  
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.friends_get(null, function(result, ex) { 
					
			var strFriendIds = "";		
			result.sort( randOrd );
			var nCtr = 0;
			
			for (key in result)	{
				if(key!= 0)
				{
					strFriendIds = strFriendIds + ", ";
				}
				
				strFriendIds = strFriendIds + result[key]
				nCtr++;
				if(nCtr>nNumberOfNotifications)
					break;
			}
							
			myAlert("sending notification to: " +strFriendIds);			
			FB.Facebook.apiClient.notifications_send(strFriendIds, strNotification, function(result, ex) {  
							myAlert("Notification is sent to: " +result);			
			});		
		});
	});
}
 
 
function fbcPublishStream(nFriendId, strTitle, strMessageContent, strName, strCaption, strDescription, strVideSource, strImageSource, strHref)
{	
	strTitle 			= unescape(strTitle);
	strMessageContent 	= unescape(strMessageContent);
	strName  			= unescape(strName);
	strCaption   		= unescape(strCaption);
	strDescription    	= unescape(strDescription);
	strVideSource	 	= unescape(strVideSource);
	strImageSource	  	= unescape(strImageSource);
		
	myAlert(nFriendId +"\n" +strTitle +"\n" +strMessageContent +"\n" +strName +"\n" +strCaption +"\n" +strDescription +"\n" +strVideSource +"\n" +strImageSource +"\n" +strHref +"\n");	
	
	FB.ensureInit (  function () {
				
		var attachment = { 'name':strName,
		'href':strHref,
		'caption':strCaption,
		'description':strDescription,
		'media':[{
		'type': 'video',
	    'video_src':   strVideSource, 
	    'preview_img': strImageSource
		}]};
						
		myAlert("debug fbcPublishStream: " +strHref);
 		FB.Connect.streamPublish(strMessageContent, attachment, null, nFriendId, strTitle, function(result, ex) {  
			myAlert("fbcPublishStream result: " +result);
		});
	 });		
}
 
function fbcPublishStream2(nFriendId, strTitle, strMessageContent, strName, strCaption, strDescription, strVideSource, strImageSource, strHref, strImgW, strImgH, strVidW, strVidH)
{	
	strTitle 			= unescape(strTitle);
	strMessageContent 	= unescape(strMessageContent);
	strName  			= unescape(strName);
	strCaption   		= unescape(strCaption);
	strDescription    	= unescape(strDescription);
	strVideSource	 	= unescape(strVideSource);
	strImageSource	  	= unescape(strImageSource);
			
	FB.ensureInit (  function () {
				
		var attachment = { 
		'name':strName,
		'href':strHref,
		'caption':strCaption,
		'description':strDescription,
		'media':[{
		
		'type': 'flash',
	    'swfsrc':   strVideSource, 
	    'imgsrc': strImageSource,
		'width':           strImgW, 
	    'height':          strImgH,
	    'expanded_width':  strVidW,
	    'expanded_height': strVidH
		}]};		
						
		//myAlert("debug fbcPublishStream2: " +strHref);
		myAlert("debug fbcPublishStream2 id:" +nFriendId);
 		
		FB.Connect.streamPublish(strMessageContent, attachment, null, nFriendId, strTitle, function(result, ex) {  
			myAlert("fbcPublishStream2 result: " +result);
		});
	 });		
}


function fbcPublishStreamDirectly(nFriendId, strName, strCaption, strDescription, strImageSource, strHref)
{	
	strName  			= unescape(strName);
	strCaption   		= unescape(strCaption);
	strDescription    	= unescape(strDescription);
	strImageSource	  	= unescape(strImageSource);
			
	FB.ensureInit (  function () {
				
		var attachment = { 
		'name':strName,
		'href':strHref,
		'caption':strCaption,
		'description':strDescription,
		
		'media':[{		
		'type': 'image',
	    'src':   strImageSource, 
	    'href':  strHref
		}]};		
						
		myAlert("debug fbcPublishStreamDirectly: " +strHref);			
	
		//work around for the following issue: http://bugs.developers.facebook.com/show_bug.cgi?id=8491
		 FB.Facebook.apiClient.users_hasAppPermission('publish_stream', function(result, ex) {

		if(!(FB.Connect._singleton._perms))
		{
		//alert("creating a new object");
		//Create the object
		FB.Connect._singleton._perms = new Object();
		FB.Connect._singleton._perms.extended = ["read_stream","share_item","publish_stream"];
		}

        	if (result == 0) {
          	FB.Connect.showPermissionDialog('publish_stream', function(granted) {
				FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
				FB.Connect.streamPublish(null, attachment, null, nFriendId, null, function(result, ex) {  
				myAlert("fbcPublishStreamDirectly result1: " +result);
				},true);
          		});
        	}
        	else {
          		FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
          		FB.Connect.streamPublish(null, attachment, null, nFriendId, null, function(result, ex) {  
				myAlert("fbcPublishStreamDirectly result2: " +result);
				},true);
        	}
      	});

	 });		
}


function fbcPublishRandomStreamDirectly(nNumberOfStreams, strName, strCaption, strDescription, strImageSource, strHref)
{
	if(nNumberOfStreams==undefined)
		nNumberOfStreams = 25;
	
	if(nNumberOfStreams>50)
		nNumberOfStreams = 50;
	  
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.users_hasAppPermission("publish_stream", function(perms){			
			if (perms!=1) {
				myAlert("no stream publishing permissions! ");			
			}
			else {
				FB.Facebook.apiClient.friends_get(null, function(result, ex) { 
					result.sort( randOrd );
					var nCtr = 1;			
					for (key in result)	{	
						myAlert("fbcPublishRandomStreamDirectly: " + result[key]);				
						fbcPublishStreamDirectly(result[key], strName, strCaption, strDescription, strImageSource, strHref)
						nCtr++;
						if(nCtr>nNumberOfStreams)
							break;
					}					
				});
			}			
		});		
	});
}

//This function will call fbcSetUsersEmail and will pass either proxied or real email address of the user
function fbcGetUsersEmail() {
		
	var strFQL = 'SELECT email FROM user WHERE uid=\'' +fbcUserId +'\'';	
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) {  
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			CallFlash("fbcSetUsersEmail", retVal);	
		});
	 }); 
}



function fbcGetUserFanInfo(strUserId, strPageId) {

	var strFQL = 'SELECT uid, page_id, type FROM page_fan WHERE uid=\'' +strUserId +'\' AND page_id=\'' +strPageId +'\'';	
	
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) { 
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			CallFlash("fbcSetUserFanInfo", retVal);		
		});
	 }); 
}


function fbcGetStreams(nNumberOfStreams) {
	
	var nNumberOfStreams = parseInt(nNumberOfStreams);
	if(isNaN(nNumberOfStreams))
		nNumberOfStreams = 10;
	
		
	var strQueryLimit = '';
	if(nNumberOfStreams>0)
		strQueryLimit = ' LIMIT ' +nNumberOfStreams;
 
	var strFQL = 'SELECT post_id, viewer_id, app_id, source_id, updated_time, created_time, filter_key, attribution, actor_id, target_id, message ';
	strFQL += ' FROM stream WHERE ';
	//strFQL += ' filter_key in (SELECT filter_key FROM stream_filter WHERE uid = ' +fbcUserId +')';
	strFQL += ' source_id=\'' +fbcUserId +'\' ';	
	//strFQL += '  ORDER BY created_time DESC ';
	strFQL += '  ' +strQueryLimit;
		
	FB.ensureInit (  function () {
		FB.Facebook.apiClient.fql_query(strFQL, function(result, ex) { 				
			
			var retVal = fbcERRORRESPONSE;
			if(result!=null && result[0]!= undefined)
			{
				retVal = "<xml><response result=\"OK\">";   
				retVal = retVal + fbcArrayToXML(result);
				retVal = retVal + "</response></xml>"; 
			}
			
			myAlert(retVal);
			CallFlash("fbcSetStreams", retVal);			
		});
	 }); 
}

function fbcPublishImageStream2(nFriendId, strTitle, strMessageContent, strName, strCaption, strDescription, strImageSource, strHref)
{	
	strTitle 			= unescape(strTitle);
	strMessageContent 	= unescape(strMessageContent);
	strName  			= unescape(strName);
	strCaption   		= unescape(strCaption);
	strDescription    	= unescape(strDescription);
	strImageSource	  	= unescape(strImageSource);
		
	FB.ensureInit (  function () {
				
		var attachment = { 
		'name':strName,
		'href':strHref,
		'caption':strCaption,
		'description':strDescription,
		'media':[{		
		'type': 'image', 
	    'src': strImageSource,
		'href': strHref
		}]};		
						
		myAlert("debug fbcPublishImageStream2: " +strHref);
 		FB.Connect.streamPublish(strMessageContent, attachment, null, nFriendId, strTitle, function(result, ex) {  
			myAlert("fbcPublishImageStream2 result: " +result);
		});
	 });		
}
