var loadedStats = null;
var foldedTab = false;
var $obj = false;

$("li.subMenu").mouseenter(function() {
	$("#enbloggMenu").find("ul.top_dropDownMenu").hide();
	var $dropdown = $(this).find("ul.top_dropDownMenu");
	if ( $dropdown.length ) {
		var p = $(this).position();
		var menuH = 22; //p.top+$(this).height()+5
		$dropdown.css({left: p.left + 10, top: menuH }).show();
	}
	$obj = false;
}).mouseleave(function(e) {
	$obj = $(this);
	setTimeout('hideMenu($obj);', 400)
});

function hideMenu($menu) {
	if ( $menu ) {
		$($menu).find("ul.top_dropDownMenu").css("display","none");
	}
}

$("ul.top_dropDownMenu li.menuItem").click(function() {
	if ( $(this).attr("id") == "gotoNewShortBlog" ) {
		$.facebox({ajax: "/p/editBlogQuick.html"});
		return false;
	} else {
		document.location.href = $(this).find("a").attr("href");
	}
});

/*$('#enbloggMenu').hover(
	function (e) {
		var scrollTop = $(window).scrollTop();
		if(scrollTop != 0){
			$('#enbloggMenu').stop().animate({'opacity':'1'},400);
		}
	},
	function (e) {
		var scrollTop = $(window).scrollTop();
		if(!foldedTab && scrollTop != 0){
			$('#enbloggMenu').stop().animate({'opacity':'0.2'},400);
			$("#enbloggMenu ul.top_dropDownMenu").css("display","none");
		}
	}
);*/

$("#gotoFollow").click(function() {
	$(this).css("opacity", 0.5);
	$.getJSON("/p/ajax.html", {action: "savefriend", 
							friend: 0, 
							diaryname: diaryName, 
							name: diaryName,
							groupChooser: 0,
							comment: '' },
							function() {
								$("#gotoFollow").hide();
							}
	);
	
	return false;
});

$("#gotoOverview").click(function() {
	$(this).toggleClass("selected");
	
	if ( parseInt($("#overview").css("top")) > 0 ) {
		$("#overview").animate({top: (0-$("#overviewContent").height()-25)+"px"}, 400, function() {
			$("#right,object").css('visibility', 'visible');
			foldedTab = false;
		});
	} else {
		$("#right,object").css('visibility', 'hidden');

		$("#themeBuilder").stop().animate({top: "-290px"}, 400);
		$("#topSpacerDiv").stop().animate({height: "0px"}, 400);
		$("#themeBuilderShow").removeClass("selected");
		$("#friends").stop().animate({top: "-"+$("#friends").height()+"px"}, 400);
		$("#gotoFriends").removeClass("selected");
		
		var d=new Date();
		if ( loadedStats != null ) {
			if ( d.getTime() - loadedStats > 1000*60 ) {
				$("#overviewContent").load("/p/overview_content.html");
				loadedStats = d.getTime();
			}
		} else {
			$("#overviewContent").load("/p/overview_content.html", function() {$("#overviewContent").hide().slideDown();});
			loadedStats = d.getTime();
		}
		loadedStats = new Date();
		$("#overview").animate({top: ($("#enbloggMenu").height()-1)+"px"}, 400);
		foldedTab = true;
	}
	
	return false;
});

$("#themeBuilderShow").click(function() {
	$(this).toggleClass("selected");
	
	if ( parseInt($("#themeBuilder").css("top")) > 0 ) {
		$("#themeBuilder").animate({top: "-290px"}, 400, function() {
			$("#right,object").css('visibility', 'visible');
			foldedTab = false;
		});
		$("#topSpacerDiv").animate({height: "0px"}, 400);
	} else {
		$("#right,object").css('visibility', 'hidden');
		$("#friends").stop().animate({top: "-"+$("#friends").height()+"px"}, 400);
		$("#overview").stop().animate({top: (0-$("#overviewContent").height()-25)+"px"}, 400);
		$("#gotoFriends,#gotoOverview").removeClass("selected");
		
		$("#themeBuilderListSelector li:first").click();

		//if ( $("#themeBuilderContent").html().length == 0 ) {
			$("#themeBuilderContent").load("/p/themeBuilder.html");
		//}
		$("#themeBuilder").animate({top: ($("#enbloggMenu").height()-1)+"px"}, 400);
		foldedTab = true;
	}
	
	return false;
});

$("#gotoFriends").click(function() {
	$(this).toggleClass("selected");
	
	if ( parseInt($("#friends").css("top")) > 0 ) {
		$("#friends").animate({top: "-"+$("#friends").height()+"px"}, 400,function(){
			$("#right,object").css('visibility', 'visible');
			$(this).hide();
		});
		foldedTab = false;
	} else {
		$("#right,object").css('visibility', 'hidden');
		$("#themeBuilder").stop().animate({top: "-290px"}, 400);
		$("#topSpacerDiv").stop().animate({height: "0px"}, 400);
		$("#overview").stop().animate({top: (0-$("#overviewContent").height()-25)+"px"}, 400);
		$("#themeBuilderShow,#gotoOverview").removeClass("selected");

		$("#friends").css("height", ($("#friendsContent").height()+40)+"px");
		$("#friendsContent").load("/p/friends_content.html", function() {
			$("#friends").animate({height: ($("#friendsContent").height()+40)+"px"}, 400);
		});
		$("#friends").css({top: "-"+$("#friends").height()+"px"}).show().animate({top: ($("#enbloggMenu").height()-1)+"px"}, 400);
		foldedTab = true;
	}
	return false;
});
	
	
$(document).ready(function() {
	$('a[rel*=facebox]').facebox({opacity: 0.7});
	if (jQuery.browser.msie) {
		$('#login a').facebox({opacity: 0.7});
	}

	/*$(window).scroll(function(){
		var scrollTop = $(window).scrollTop();
		if(!foldedTab && scrollTop != 0)
			$('#enbloggMenu').stop().animate({'opacity':'0.2'},400);
		else
			$('#enbloggMenu').stop().animate({'opacity':'1'},400);
	});*/


	// Favourites bar
	$("#favBlogsFavourites").sortable({
								items: 'div.favFriend', 
								axis: 'y',
								helperclass: 'sortHelper',
								stop : function() {
									var serialized = "";
									$("#favBlogsFavourites").find("div").each(function() {
										serialized += $(this).attr("id").substr(10) + ",";
									});
									$.post("/p/ajax.html", {action: "enbloggSetFavOrder", order: serialized});
									}
								});
	
	$("#friendBar .favFriend").live('mouseover',function() {
		$(this).stop().animate({left: "15px"}, {queue:false,duration:200});
		$(this).find("img").css('opacity',1);
	});
	$("#friendBar .favFriend").live('mouseout',function() {
		if ( !$(this).hasClass("highlighted") ) {
			$(this).stop().animate({left: "0px"}, {queue:false,duration:200});
			$(this).find("img").css('opacity',0.8);
		}
	});
	
	$("#friendBarHide").click(function() {
		$("#favBlogsFavourites").slideUp();
	});
});

var title=document.title;
var fullUpdate = 0;
function updateMenu() {
	var query = "";
	if ( fullUpdate % 5 == 0 ) {
		query = "&type=fullUpdate";
	}
	fullUpdate ++;

	$.getJSON("/p/ajax.html?action=enbloggUpdateMenu" + query,
	function(data) {
		var menuAlert = 0;
		var img;
		if ( data.newComments > 0 ) {
			$("#menuAlertComments").html("(" + data.newComments + ")");
			if ( !soclog.isFrontpage ) {
				for ( index in data.latestComment ) {
					showPopupForFriend(data.latestComment[index].userid, 1, data.latestComment[index], "friendbar_comment.png");
					if ( typeof liveCommentsUpdate == 'function' ) {
						liveCommentsUpdate(data.latestComment[index]);
					}
				}
			}
			menuAlert += parseInt(data.newComments);
			$("#gotoBlog").children("a").css("color", "#ff9900");
			
		} 
		else if ( typeof(data.newComments) != 'undefined' ) {
			$("#menuAlertComments").html("");
		}

		if ( !soclog.isFrontpage ) {
			if ( data.newLikes > 0 ) {
				for ( index in data.likes ) {
					if ( data.likes[index].score == 2 ) {
						showPopupForFriend(data.likes[index].userid, 1, data.likes[index], "friendbar_poll.png");
					} else {
						showPopupForFriend(data.likes[index].userid, 1, data.likes[index], "friendbar_like.png");
					}
				}
			}
		}
		
		if ( typeof(data.updatedForumThreads) != 'undefined' ) {
			$("#menuAlertForum").html("");
			if ( data.updatedForumThreads > 0 ) {
				$("#menuAlertForum").html("(" + data.updatedForumThreads + ")");
				menuAlert += parseInt(data.updatedForumThreads);
			}
		}

		if ( typeof(data.updatedFriends) != 'undefined' ) {
			$("#menuAlertFriends").html("");
		}
		if ( data.newFriends > 0 ) {
			$("#menuAlertFriends").html( soclog.newFriendText );
			menuAlert += parseInt(data.newFriends);
		}
		if ( data.updatedFriends > 0 ) {
			$("#menuAlertFriends").html("(" + data.updatedFriends + ")");
			if ( !soclog.isFrontpage ) {
				for ( index in data.updatedFriendInfo ) {
					if ( data.updatedFriendInfo[index].type == "image" ) {
						img = "friendbar_image.png";
					} else {
						img = "friendbar_post.png";
					}
					showPopupForFriend(data.updatedFriendInfo[index].userid, 1, data.updatedFriendInfo[index], img);
				}
			}
			menuAlert += parseInt(data.updatedFriends);
		} 

		if ( typeof(data.bloglovin) != 'undefined' ) {
			if ( data.bloglovin > 0 ) {
				$("#menuAlertBloglovin").html("(" + data.bloglovin + ")");
				menuAlert += parseInt(data.bloglovin);
			} else {
				$("#menuAlertBloglovin").html("");
			}
		}

		if ( data.newPM > 0 ) {
			$("#menuAlertInbox").html("(" + data.newPM + ")");
			menuAlert += parseInt(data.newPM);
			$("#gotoBlog").children("a").css("color", "#ff9900");
		} else {
			$("#menuAlertInbox").html("");
		}
		
		
		if ( menuAlert ) {
			document.title = "* "+title;
		}
		
		/*if ( data.liveComments && data.liveComments.length > 0 ) {
			arr = data.liveComments;
			arrTick = 0;
			displayTick();
		}*/
		
		if ( data.quickspots ) {
			quickspot = data.quickspots;
			$("#quickspotLiHolder").fadeOut('fast', function() {
				clearTimeout(quickspot_timer);
				quickspot_cnt = parseInt(Math.random()*quickspot.length);
				flipQuickspot();
			});
		}
		
		setTimeout("updateMenu()", 20000 );
	});
}

function closeAndReload() {
	jQuery(document).trigger('close.facebox')
	document.location.reload();
}

function showPopupForFriend(userid, type, userArr, img) {
	if ( $("#favFriendPopup"+userid).length == 0 ) {
		$friend = $("#favFriend_"+userid);
		if ( $friend.length == 0 ) {
			if ( userArr.userid != 0 ) {
				$("#friendBar").append("<div class='favFriend highlighted' id='favFriend_"+userid+"'> \
				<a href='http://"+userArr.user+".soclog.se/' target='_top'>\
				<img src='"+userArr.avatar+"' class='friendAvatar' alt='"+userArr.user+"' title='"+userArr.user+"'> \
				</a>\
				</div>");
			} else {
				$("#friendBar").append("<div class='favFriend highlighted' id='favFriend_"+userid+"'> \
				<img src='"+userArr.avatar+"' class='friendAvatar' alt='"+userArr.user+"' title='"+userArr.user+"'> \
				</div>");
			}
	
			$friend = $("#favFriend_"+userid);
		}
	
		//var pos = $friend.position();
	    $('<div id="favFriendPopup'+userid+'" class="favFriendPopupBalloon"><img src="http://cdn03.dayviews.com/cdn/img/enblogg/icons/'+img+'"></div>').css( {
	        position: 'relative',
	        display: 'none',
	        top: "-48px",
	        left: "34px"
	    }).appendTo("#favFriend_"+userid)
	    .fadeIn(200)
   		.attr("href", userArr.link);
   		$("#favFriendPopup"+userid+",#favFriend_"+userid+" a").click(function() {
	    	if ( $(this).attr("href") ) {
	    		if ( userArr.link.substr(0,7) == "http://" ) {
		    		document.location.href = userArr.link;
	    		} else {
		    		document.location.href = "http://" + soclog.username + ".soclog.se" + userArr.link;
	    		}
	    		return false;
	    	}
	    });
	    $friend.addClass("highlighted")
	    		.stop().animate({left: "15px"}, {queue:false,duration:200})
	    		.find("img")
	    		.css('opacity',1);
	}
}

function removeFavFriend(userid) {
	$("#favFriend_"+userid).slideUp(function() { $(this).remove(); });
	$("#favFriendPopup"+userid).remove();
}

function addFavFriend(userid, $i) {
	var username = $i.attr("title");
	var avatar = $i.attr("src");

	$("#favBlogsFavourites").prepend("<div class='favFriend' id='favFriend_"+userid+"'> \
	<a href='http://"+username+".soclog.se/'>\
	<img src='"+avatar+"' class='friendAvatar' alt='"+username+"' title='"+username+"'> \
	</a>\
	</div>");
}

