var fbUserId = null;
var fbSession;

if(!document.getElementById)
{
	if(document.all)
	{
		document.getElementById = function()
		{
			if(typeof document.all[arguments[0]]!="undefined")
			{
				return document.all[arguments[0]];
			}
			else
			{
				return null;
			}
		};
	}
	else if(document.layers)
	{
		document.getElementById = function()
		{
			if(typeof document[arguments[0]]!="undefined")
			{
				return document[arguments[0]];
			}
			else
			{
				return null;
			}
		};
	}
};

function activateMenu(id)
{
	obj = document.getElementById('head.swf');
	obj.activateMenu(id);
}

// visa eller gom en div
	function toggle(a){
	var e=document.getElementById(a);
	if(!e) {return true;}
	if(e.style.display=="none"){
	e.style.display="block";
	} else {
	e.style.display="none";
	}
	return true;
	};

var currentPic;
function showGalleryPic(id, filename, offset, text, showFriendsToTag)
{
	//alert('showGalleryPic ' + fbUserId);
	showTagPhotoToggle(false);
	$(".vimmelPicBorder").hide();
	$("#VPB_"+id).show();
	$("#vimmelPicImg").attr("src", filename);
	
	var images = $(".vimmelImagesHolder").find(".vimmelPicBorder").map(function(){return this.id;}).get();
	var inum = jQuery.inArray('VPB_' + id, images);
	
	newPicNum = parseInt(offset)+parseInt(inum) + 1;
	$('.vimmelImage').attr("id", id);
	
	$('#imageId').attr("value", id);
	$("#picText").html(text);
	$("#picCounter").html(newPicNum);
	
	$.get("http://www.birgerjarl.nu", {go: 'FB', imageTags: id, userId: fbUserId},
		function(data){
			$("#tags").html(data);
			updateFriendsList();
		});

	currentPic = id;
	
	var url = 'http://www.birgerjarl.nu/index.php?pageId=2&gid=' + filename.match(/\d+/) + '&imageId=' + id;
	var xid = url.replace(/http:\/\//, '').replace(/\/|\?|\&|\=/ig, '.');
	
	$('#fb_comments_box').html('<fb:comments id="fb_comments" css="http://www.birgerjarl.nu/css/fbcomments4.css?v=20" url="' + url + '" xid="' + xid + '" numposts="8" width="670"></fb:comments>');
	FB.XFBML.Host.parseDomElement(document.getElementById('fb_comments_box'));

}

function updateFriendsList()
{
	$('#friendframe').contents().find('li').each(function(index){ $(this).show(); });
	$('#tags').find('a').each(function(index){
		var id = $(this).attr("href").match(/.*id=(\d+)/);
		if(id)
		{
			$('#friendframe').contents().find('#chk' + id[1]).attr('checked', false);
			$('#friendframe').contents().find('#uid' + id[1]).hide(); //css("display", "none");
		}
	});
}

function showToolbar(toolbar)
{
	//$("#"+toolbar+" a img").fadeTo("fast",0.33);
	$("#"+toolbar).fadeTo("fast", 0.66);
}

function hideToolbar(toolbar)
{
	//$("#"+toolbar+" a img").fadeOut("fast");
	$("#"+toolbar).fadeTo("fast", 0);
}

function nextPic(picLimit, currentOffset, numItems)
{ 
	var images = $(".vimmelImagesHolder").find(".vimmelPicBorder").map(function(){return this.id;}).get();
	if(!currentPic) currentPic = images[0].replace("VPB_", "");
	var index = jQuery.inArray('VPB_' + currentPic, images) + 1;


	if(index >= images.length)
	{
		index = 0;
	} 

	currentPic = images[index].replace("VPB_", "");

	showGalleryPic(currentPic, imgFile[index+1], currentOffset, imgText[index+1]);
}

function prevPic(picLimit, currentOffset, numItems)
{
	var images = $(".vimmelImagesHolder").find(".vimmelPicBorder").map(function(){return this.id;}).get();
	if(!currentPic) currentPic = images[0].replace("VPB_", "");
	var index = jQuery.inArray('VPB_' + currentPic, images) - 1;


	if(index < 0)
	{
		index = images.length - 1;
	} 

	currentPic = images[index].replace("VPB_", "");

	showGalleryPic(currentPic, imgFile[index+1], currentOffset, imgText[index+1]);
}

function isGoto(qs)
{
	if(qs!="")
		$(".contentLeft").load("index.php?"+qs);
}

function menuClicked(id)
{
	this.parent.frames['historyStack'].location.href = 'history.php?go=LoadContent&pageId='+id; 
	return false;

}

function leftLoad(qs)
{
	if(fbUserId){
		qs += '&userId=' + fbUserId;
	}
	
	this.parent.frames['historyStack'].location.href = 'history.php?go=LoadContent&'+qs; 
	return false;
}

function musicPlayerPlaying(playing)
{
	var swf = document.getElementById("head.swf");
	swf.musicPlayerPlaying(playing);
}

function changeButton(buttonType)
{
	$("#browseButton").hide();
	$("#uploadPicButton").show();
}


function switchDiv(off, on)
{
	$("#"+off).hide();
	$("#"+on).show();
}

$(document).ready(
		function() {
			blushade();	
		}	
		
);

function showTagPhoto() {	
	FB.ensureInit(function() {
		FB.Connect.ifUserConnected(showTagPhotoToggle, getLogin);
	});
}

function update_user_box (type) {
	FB.Facebook.get_sessionState().waitUntilReady(function()
	{	
		FB.Connect.requireSession(function(){
			fbUserId = FB.Facebook.apiClient.get_session().uid;
			FB.Facebook.apiClient.users_getInfo(fbUserId,['name'], function(result, ex) {
				FB.Facebook.apiClient.users_hasAppPermission("offline_access",function(res){
					if(res != 1)
					{
						FB.Connect.showPermissionDialog('publish_stream,offline_access,email', function(result){});
					}
				});

				if(fbSession != FB.Facebook.apiClient.get_session().session_key)
				{
					
					storeFBSession();
					fbSession = FB.Facebook.apiClient.get_session().session_key;
				}
				
				//FB.Connect.streamPublish("Jag har lagt till Birger Jarls Facebook-app", {'name':'Birger Jarl','href':'http://www.birgerjarl.nu'}, null, 100001274146881);
				
				var username = result[0].name;
				$("#fbProfileImage").attr("uid", fbUserId);
				$("#fbUsername").attr("href", 'http://www.facebook.com/profile.php?id=' + fbUserId);
				$("#fbUsername").text(username);
				
				$('#fb_user_area_login').hide();
				$('#fb_user_area').show();
				
				FB.XFBML.Host.parseDomElement(document.getElementById('fb_user_area'));
			});
		});
	});
 }


function streama(){
	FB.Connect.requireSession(function() {
	      FB.Facebook.apiClient.users_hasAppPermission('publish_stream,offline_access,email,auto_publish', function(has) {
	        if (has == 0) {
	          FB.Connect.showPermissionDialog('publish_stream,offline_access,email,auto_publish', function(granted) {
	            FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
	            //FB.Connect.streamPublish("Jag har lagt till Birger Jarls Facebook-app", {'name':'Birger Jarl','href':'http://www.birgerjarl.nu'}, null, 100001274146881);
	        	
	            //FB.Connect.streamPublish(stream_text, attachments, actionLinks, fb_id, prompt_text, callback, true);
	          });
	        }
	        else {
	          FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
	          //FB.Connect.streamPublish("Jag har lagt till Birger Jarls Facebook-app", {'name':'Birger Jarl','href':'http://www.birgerjarl.nu'}, null, 100001274146881);
	      	
	          //FB.Connect.streamPublish(stream_text, attachments, actionLinks, fb_id, prompt_text, callback, true);
	        }

	      });  
	});
	
	//FB.Connect.streamPublish("Jag har lagt till Birger Jarls Facebook-app", {'name':'Birger Jarl','href':'http://www.birgerjarl.nu'}, null, 100001274146881);
	//FB.Connect.streamPublish("", null, null, null, null, function(){ console.info("called back"); });
	
}

function DoLogout() { 
	FB.Connect.logout(function(response) {
		$('#fb_user_area').hide();
    	$('#fb_user_area_login').show();
        //Log.info('FB.logout callback', response);
    });
}

function getLogin() {
	/*
	FB.Connect.login(function(response) 
		{
	
			if (response.session) {
				if (response.perms) {
			      // user is logged in and granted some permissions.
			      // perms is a comma separated list of granted permissions
			    	//alert('user is logged in and granted some permissions.');
			    } else {
			      // user is logged in, but did not grant any permissions
			    	//alert('user is logged in, but did not grant any permissions'):
			    }
			} else {
			    // user is not logged in
				  //alert('user is not logged in');
			
		}); //, {perms:'read_stream,publish_stream,offline_access'});
*/
	
	//FB.showPermissionDialog('publish_stream, read_stream', hello, false, '');
	
	FB.Connect.requireSession(reload_page);
	/*
	FB.Connect.requireSession(function() {
	      FB.Facebook.apiClient.users_hasAppPermission('publish_stream,offline_access,email,auto_publish', function(has) {
	        if (has == 0) {
	          FB.Connect.showPermissionDialog('publish_stream,offline_access,email,auto_publish', function(granted) {
	            FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
	            FB.Connect.streamPublish(stream_text, attachments, actionLinks, fb_id, prompt_text, callback, true);
	          });
	        }
	        else {
	          FB.Connect._singleton._userInfo.shortStorySetting = FB.FeedStorySetting.autoaccept;
	          FB.Connect.streamPublish(stream_text, attachments, actionLinks, fb_id, prompt_text, callback, true);
	        }

	      });
	      
	});
	*/
}

function reload_page () {
	storeFBSession();
	window.location.href = "http://www.birgerjarl.nu/";
}

function showTagPhotoToggle(mode){
	if($('#filter').css('display') != 'none' || mode == false)
	{
		$("#tagphoto").html("Tagga dina v&auml;nner");
		$('#filter').hide();		
	} 
	else 
	{
		$("#tagphoto").text("Klar");
		$('#filter').show();
		$('#friendframe').contents().find('#imageId').attr("value", $(".vimmelImage").attr("id"));
	}
}

function tagImage()
{
	var form = $('#friendframe').contents().find('#friendform');

	$.post("index.php?go=FB&tagfriends=" + fbUserId, form.serialize(), function(data){
		//alert(data);
		updateTags(data);
	}, 'json');
	showTagPhotoToggle(false);
}

function updateTags(data)
{
	var tags = new Array();
	$('#friendframe').contents().find('li').each(function(index){ $(this).show(); });
	
	jQuery.each(data, function(index, obj){
		$('#friendframe').contents().find('#chk' + obj.id).attr('checked', false);
		$('#friendframe').contents().find('#uid' + obj.id).hide();
		var clearTag = "";
		if(obj.tagger == '1') clearTag = ' (<a href="javascript:clearTag(' + obj.id +')">Ta bort</a>)';
		tags.push('<a href="http://www.facebook.com/profile.php?id=' + obj.id + '">' + obj.name + '</a>' + clearTag);
		
	});
	$('#tags').html(tags.join(', '));
}

function loadDynamicFbmlCallback() {
   FB.XFBML.Host.parseDomElement($('#filter')[0]);
}

function clearTag(friendId)
{
	$.get("index.php", {go: 'FB', clearTag: currentPic, friendId: friendId}, function(data){
		updateTags(data);
	}, 'json');
}


function blushade() {
	$(".bluShade").css("opacity", "0.0");
	$(".eventBluListener").hover(
			function()
			{
				pobj = $(this).prev();
				$(pobj).fadeTo("fast", 0.4);
			},
			function()
			{
				pobj = $(this).prev();
				$(pobj).fadeTo("fast", 0);
			}
		);
}
