var L={isUndefined:function(a){return typeof a==="undefined"},isNumber:function(a){},isString:function(a){return typeof a==="string"},isObject:function(a){return(a&&(typeof a==="object"||L.isFunction(a)))},trim:function(a){try{return a.replace(/^\s+|\s+$/g,"")}catch(b){return a}}};$(document).ready(function(){D.init(gConfig)});
var D = {
	/**
	 * 
	 */
	init:function(config){
		this.setLang();
		D.config = config;
		D.uid = 0;
		
		this.menu("mmenu");
		var tabs = $(".tabs");
		if( tabs.length > 0 ){
			tabs.tabs({ 
				cache: false, 
				fx: { opacity: 'toggle', selected:3 },
				load: function(event, ui) {
					D.bindAutoGrow();
					D.bindLinks();
					D.beutifyButtons();
				}
			});
		}
			
		// bind links to be loaded by ajax
		D.bindLinks();

		if( D.config.isLogged ){
			// setup update online status events
			D.TB.init(D.config.notifications);
			D.searchFriends();
		}
		D.beutifyButtons();
		// setup any autogrow textareas
		D.bindAutoGrow();
		
		$("div.roundTop").each(function(){$(this).corner("top 7px");});
		$("div.roundBottom").each(function(){$(this).corner("bottom 7px");});
		$("div.round").each(function(){$(this).corner("7px");});
		$(".d-button:not(.ui-state-disabled)").hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		)
		.mousedown(function(){
				$(this).parents('.d-buttonset-single:first').find(".d-button.ui-state-active").removeClass("ui-state-active");
				if( $(this).is('.ui-state-active.d-button-toggleable, .d-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
				else { $(this).addClass("ui-state-active"); }	
		})
		.mouseup(function(){
			if( !$(this).is('.d-button-toggleable, .d-buttonset-single .d-button,  .d-buttonset-multi .d-button') ){
				$(this).removeClass("ui-state-active");
			}
		});
	},
	time:function(){
		var d = new Date();
		return d.getTime();
	},
	/**
	 * 
	 */
	beutifyButtons:function(){
		$("button, :submit").addClass("ui-state-default").addClass("ui-corner-all").hover(function(){ 
				$(this).addClass("ui-state-hover"); 
			}, function(){ 
				$(this).removeClass("ui-state-hover"); 
		});
	},
	/**
	 * 
	 */
	scrollTop:function(){
		$('html, body, #scrollWrap').animate({scrollTop:0}, 'slow');
	},
	/**
	 * 
	 */
	scrollBottom:function(sel){
		$(sel).animate({scrollTop:$(sel).attr("scrollHeight")}, 'slow');
	},
	/**
	 * 
	 */
	postForm : function(formId, url, onSuccess, onFailure, beforeSubmit){
		var form = $("#"+formId);
		var submitBtn = form.find("input[type=submit]");
		var status = $("<div class='' />").insertAfter(submitBtn);
		form.submit(function(e){
			e.preventDefault();
			status.removeClass("notice").removeClass("error").html(D.image('loading1.gif'));
			if( $.isFunction(beforeSubmit) ){
				beforeSubmit();
			}
			submitBtn.attr("disabled",true);
			$.post(url, form.serialize(), function(response){
				submitBtn.attr("disabled",false);
				status.html("");
				if( D.isOk(response) ){
					if( $.isFunction(onSuccess) ){
						onSuccess(response);
					}else{
						status.addClass("notice").removeClass("error").html(lang['changesSaved']);
					}
				}else{
					if( $.isFunction(onFailure) ){
						onFailure(response);
					}else{
						status.addClass("error").removeClass("notice").html(response.error);
					}
				}
			}, "json");
		});
	},
	/**
	 * 
	 */
	searchFriends:function(){
		$("#searchFriendsAC").jac({
			'buildUrl' : function(params){
				return D.url('friends', 'searchFriendsAC','q',params.q);
			},
			'width' : 200,
			'formatResult' : function(item){
				return '<div><img src="' + item.photo + '" class="img" style="width:35px;height:35px"> ' + item.name + '</di>';
			},
			'onSelect' : function(item){
					D.goTo( D.url('profile','id',item.id) );
			},
			'helpText':lang['friendsQSearch']
		});
	},
	/**
	 * 
	 */
	guid:function(){
		if( typeof D.uid == 'undefined'){
			D.uid = 0;
		}
		return "DRUID" + (++D.uid);
	},
	/**
	 * 
	 */
	url:function(){
		var url=D.config.baseUrl;
		for(var i=0;i<arguments.length;i++){
			if(L.isUndefined(arguments[i])){
				continue;
			}
			if(i>0){
				url+='/';
			}
			arguments[i].toString().replace("/","_");
			url+=arguments[i];
		}
		return encodeURI(url+'.'+D.config.lang+'.html');
	},
	/**
	 * checks if result of JSON response indicates success
	 */
	isOk : function(response){
		if( D.config.isLogged && parseInt(response.auth) == 0 ){
			response.error = lang['sessTimeout'];
		}
		return ( parseInt(response.result) == 1 );
	},
	/**
	 * 
	 */
	error:function(wrap, e ){
		$("#"+wrap).removeClass("notice").addClass("error").removeClass("hidden").html(e);
	},
	/**
	 * 
	 */
	notice:function(wrap, n ){
		$("#"+wrap).removeClass("error").addClass("notice").removeClass("hidden").html(n).show();
	},
	/**
	 * deletes something, and removes it's containing div
	 */
	deleteIt : function( url, pars, wrapId, confirmation, onSuccess){
		function post(){
			$.post(url,pars,function(response){
				if( D.isOk(response) ){
					if( $.isFunction(onSuccess) ){
						onSuccess(response);
						return;
					}
					$("#"+wrapId).fadeOut("slow",function(){
						$(this).remove();
					});	
				}else if( response.error.length > 1 ){
					D.alert(response.error);
				}
			}, "json");
		}
		if( !L.isUndefined(confirmation) ){
			D.confirm(confirmation, lang["confirm"], function(){
				post();
			});
		}else{
			post();
		}
	},
	/**
	 * 
	 */
	alert:function(msg,title){
		var aId = D.guid();
		var a = $('<div id='+aId+'><p class="fs7">' + msg + "</p></div>");
		bs = {};
		bs[lang["close"]] = function(){
			$(this).dialog('destroy');
			$("#"+aId).remove();
		};
		
		a.dialog({
			bgiframe: true,
			resizable: false,
			modal: true,
			dialogClass: 'alert',
			'title': title,
			buttons: bs
			
		});
	},
	
	/**
	 * 
	 */
	confirm:function(question,title,onOk, onCancel){
		var a = $('<div><p class="fs7">' + question + "</p></div>");
		bs = {};
		bs[lang["yes"]] = function() {
			$(this).dialog('destroy');
			if( $.isFunction(onOk) ){
				onOk(true);
			}
		};
		bs[lang["cancel"]] = function() {
			$(this).dialog('destroy');
			if( $.isFunction(onCancel) ){
				onCancel(false);
			}
		};
		
		a.dialog({
			bgiframe: true,
			resizable: false,
			modal: true,
			dialogClass: 'alert',
			'title': title,
			buttons: bs
			
		});
	},
	
	/**
	 * 
	 */
	image:function(img, className, buildLink){
		
		buildLink = ( L.isUndefined(buildLink) ) ? true : buildLink;
		var link = D.config.imagesDir + img;
		if( !buildLink ){
			return link;
		}
		className = ( L.isUndefined(className) ) ? 'img' : className;
		return '<img src="' + link + '" class="' + className + '" />';
	},
	
	/**
	 * 
	 */
	reloadWindow:function(){
		window.location.href = window.location.href;
	},
	
	/**
	 * 
	 */
	goTo:function(href){
		window.location.href=href;
	},
	
	/**
	 * 
	 */
	show:function(sel, text){
		var el = $(sel);
		if( !L.isUndefined(el) ){
			if( !L.isUndefined(text) ){
				el.text(text);
			}
			el.removeClass("hidden");
		}
	},
	
	/**
	 * 
	 */
	hide:function(sel, clear){
		var el = $(sel);
		if( !L.isUndefined(el) ){
			el.addClass("hidden");
			if(clear==true){
				el.text("");
			}
		}
	},
	
	/**
	 * 
	 */
	toggle:function(sel){
		var el = $(sel);
		if( L.isUndefined(el) ){
			return;
		}
		if( !el.hasClass("hidden") ){
			el.fadeOut("slow", function(){
				el.addClass("hidden").css({display:"none", visibility:"hidden"});
			});
		}else{
			el.removeClass("hidden").css({display:"block", visibility:"visible"});
		}
	},
	/**
	 * 
	 */
	cookie:function(n, v){
		if( L.isUndefined(v) ){
			return $.cookie(n);
		}
		$.cookie(n,v,{ expires: 0, path: '/'});
	},
	/**
	 * 
	 */
	fadeOut : function(sel){
		$(sel).fadeOut("slow",function(){
			$(this).remove();
		});
	},
	/**
	 * 
	 */
	getFileExtention:function(fileName){
		if( fileName.length < 2 ){
			return '';
		}
		var dotPos = fileName.lastIndexOf(".");
		if( dotPos==-1 ){
			return '';
		}
		if( dotPos == fileName.length-1 ){
			return '';
		}
		return fileName.substr(dotPos+1, fileName.length).toLowerCase(); 
	},
	/**
	 * 
	 */
	isImageFile : function(fileName){
		var ext = D.getFileExtention(fileName);
		return ( ext == 'jpg' || ext == 'jpeg' || ext == 'gif' || ext == 'png' );
	},
	/**
	 * 
	 */
	bindLinks:function(){
		$('a.ajax').each(function(link){
			link = $(this);
			var href= link.attr('href');
			link.attr('href', '');
			link.removeClass("ajax");
			link.click(function(e){
				e.preventDefault();
				var targetSel = "#"+link.attr("rev");
				D.load(href, targetSel);
			});
		});
	},
	inlineScripts:function(el){
		if( typeof el == "string" ){
			el = $("#"+el);
		}
		
		el.children("script").each(function(e){
			
      	  // try{
      		   eval(this.text);
      	   // }
      	   // catch(e){
      	   // }
		});
	},
	/**
	 * 
	 */
	bindAutoGrow:function(){
		$('textarea.autogrow').each(function(){
			$(this).autogrow({
				maxHeight: 300,
				lineHeight: 16
			});
			$(this).removeClass('autogrow');
		});
		
	},
	/**
	 * 
	 */
	load:function(href, targetSel, showStatus){
		var target = $(targetSel);
		//if(!L.isUndefined(showStatus) && showStatus==true ){
			target.html(D.image('loading1.gif'));
		//}
		$.get(href, function(data){
			target.html(data);
			D.inlineScripts(target);
			D.bindLinks();
			D.bindAutoGrow();
			D.beutifyButtons();
		});
	},
	/**
	 * 
	 */
	setLang:function(e, lang){
		$("a[rev=setLang]").each(function(){
			var link = $(this);
			link.click(function(e){
				e.preventDefault();
				link.html('wait...');
				$.post(D.url('actions','setLanguage'),{'lang':link.attr("rel")}, function(response){
					if( D.isOk(response) ){
						D.goTo(response.goTo);
					}
				}, "json");
			});
		});
	},
	/**
	 * overlay
	 */
	OL:{
		/**
		 * 
		 */
		container:null,
		/**
		 * shows overlay
		 * 
		 * @param url:
		 *            url of the page to be loaded in the overlay
		 */
		open:function(url, pTitle){
			var id = D.guid();
			if( typeof pTitle == 'undefined' ){
				pTitle = '';
			}
			
			this.container = $('<div id="'+id+'"></div>');
			
			this.container.dialog({
				bgiframe: true,
				autoOpen: true,
				modal: true,
				width:600,
				draggable:true,
				resizable: true,
				position: ['center',50],
				
				title : pTitle,
				close: function() {
					$(this).dialog('destroy');
					$("#"+id).remove();
				}
			});
			D.load(url, $("#"+id+''), true);
		},
		/**
		 * closes the overlay
		 */
		close:function(){
			this.container.dialog('close');
			
		}
	}
};
/**
 * 
 */
D.profile={
	/**
	 * 
	 */
	init:function(){
		/** "member status" edit in place settings */
		$('#mStatus').editable(D.url('actions','changeMemberStatus'), {
	            width:"620px",
	            height:"60px",
	            maxlength:"512",
	            name:"newStatus",
	            loadtype:"POST",
	            placeholder:lang["clickToEditStatus"],
	            event:'click.editable',
	            indicator : D.image('loading1.gif'),
	            tooltip   : lang["clickToEditStatus"],
	            submit : lang["publish"],
	            cancel : lang["cancel"],
	            type:'textarea'
		});
		/** invoke editor using extra link */
		$("#editMStatus").bind("click",function() {
			$('#mStatus').trigger("click.editable");
	    });
	},
	/**
	 * 
	 */
	popularityVote:function(memberId){
		$.post(D.url('actions','popularityVote'), {'memberId':memberId}, function(response){
			D.alert(D.isOk(response) ? lang["votingSuccess"]: response.error );
		}, "json");
	},
	/**
	 * 
	 */
	deleteNewsfeedEntry:function(newsId){
		$.post(D.url("actions","deleteNewsfeedEntry"),{"newsid":newsId}, function(response){
			if( D.isOk(response) ){
				D.fadeOut('#newsEntry'+newsId);
			}
		},"json");
        
	},
	/**
	 * 
	 */
	deleteAllNewsFeed:function(container){
		$.post(D.url("actions","deleteAllNewsfeed"),{},function(response){
			if( D.isOk(response) ){
				var e=$("div.newsfeedEntry");
				e.each(function(){
					$(this).remove();
				});
			}
		},"json");
	},
	/**
	 * 
	 */
	approveFriendRequest:function(otherId, approve){
		$.post(D.url('actions','approveFriendRequest'),{'otherId':otherId,'approve':approve}, function(response){
			if( D.isOk(response) ){
				D.fadeOut("#friendRequest"+otherId);
			}
		},"json");
	},
	/**
	 * 
	 */
	sendGreeting:function(otherId){
		D.confirm(lang["confGreet"], lang["greet"], function(){
			$.post(D.url('actions','sendGreeting'), {"otherId":otherId},function(response){
				if( D.isOk(response) ){
					D.alert(lang["greetingSent"]);
				}
			},"json");
		});
	},
	/**
	 * 
	 */
	deleteGreeting:function(greetingId){
		$.post(D.url("actions","deleteGreeting"), {"gid":greetingId}, function(response){
			if( D.isOk(response) ){
				D.fadeOut("#greeting"+greetingId);
			}
		},"json");
	},
	/**
	 * 
	 */
	addFriend:function(mId){
		D.confirm(lang["confAddFriend"], lang["confirm"], function(){
			$.post(D.url("actions","addFriend"),{"mid":mId},function(response){
				if( D.isOk(response) ){
					D.alert(lang["friendRequestSent"]);
				}
			},"json");
		});
	},
	/**
	 * 
	 */
	deleteFriend:function(friendId,friendName){
		D.deleteIt(D.url("actions","deleteFriend"), {"friendId":friendId}, "friend"+friendId, lang["confRemoveFriend"]);
	},
	/**
	 * 
	 */
	ignoreUser:function(mId, ignore){
		var conf = (ignore == 'true') ? lang["confIgnoreUser"]:lang["confDeignoreUser"];
		D.confirm(conf, lang["confirm"], function(){
			$.post(D.url("actions","ignoreMember"),{"mid":mId, "ignore":ignore},function(response){
				D.isOk(response) && D.reloadWindow();
			},"json");
		});
	},
	/**
	 * 
	 */
	wall:{
		/**
		 * initialize member wall
		 */
		init:function(){
			D.postForm("wallPostForm", D.url('actions','writeOnWall'), function(response){
				if( D.isOk(response) ) {
					var tabs = $("div.tabs").tabs();
					tabs.tabs('load', tabs.tabs('option','selected'));
				}
			}); 
		},
		deleteEntry:function(eId, oId){
			$.post(D.url('actions','deleteWallEntry'), {'entryId':eId,'ownerId':oId}, function(response){
				if( D.isOk(response) ){
					D.fadeOut("#wallEntry"+eId);
					}
				},'json');
		}
	},
	/**
	 * 
	 */
	edit:{
		
		/**
		 * 
		 */
		photo:function(){ 
			$("#uploadProfilePhotoForm").jup({
				"validate" : function(fields){
					if( fields.userfile.length == 0 ){
						D.error("photoUploadStatus", lang['photoUpNotSelected']);
						return false;
					}
					if( !D.isImageFile(fields.userfile) ){
						D.error("photoUploadStatus", lang['photoExtNotice']);
						return false;
					}
					$("#photoUploadStatus").removeClass("error").html("");
					return true;
				},
				"beforeUpload":function(){
					D.notice("photoUploadStatus", lang["photoUploading"] + D.image("loading1.gif"));
				},
				"onComplete":function(response){
					if( D.isOk(response) ){
						D.notice("photoUploadStatus", response.msg);
						$("#newProfilePhoto").attr("src", response.newPhotoUrl);
						$("#newPhotoUrlContainer").removeClass("hidden");
					}else{
						D.error("photoUploadStatus", response.error);
					}
				}
			});
		},
		
		/**
		 * 
		 */
		reloadContacts:function(){
			var listDiv=$("#contactsList");
			listDiv.fadeOut("slow");
			$.get(D.url('actions','editContacts','act','get'),{},function(response){
				listDiv.html(response);
				listDiv.fadeIn("slow");
			});
		},
		/**
		 * 
		 */
		deleteContact:function(contactId){
			$.post(D.url('actions','editContacts','act','delete'),{'contactId':contactId},function(response){
				D.fadeOut("#c"+contactId);
			},"json");
		}
	}
};

D.mailbox={
	/**
	 * 
	 */
	inbox:function(){
		// bind read inbox message links
		$("a[rel=readInboxMsg]").click(function(e){
			e.preventDefault();
			D.mailbox.getMsg(this.id,"inbox");
		});

	},
	/**
	 * 
	 */
	outbox:function(){
		$("a[rel=readOutboxMsg]").click(function(e){
			e.preventDefault();
			D.mailbox.getMsg(this.id,"outbox");
		});
	},
	/**
	 * handle "send message" form
	 */
	post:function(formId){
		D.postForm(formId, D.url('mailbox','sendMsg'), function(){
			var wrap = $("#"+formId).parent();
			wrap.html('<div style="color:brown;font-size:60px;padding:50px">' + lang["msgSent"] + '</div>');
			setTimeout(function(){
				D.OL.close();
			},2000);
			
		});
	},
	/**
	 * 
	 */
	getIdPre:function(type){
		if(type=="outbox"){
			return "o";
		}
		return "";
	},
	/**
	 * 
	 */
	checkAll:function(type, checked){
		var pre = D.mailbox.getIdPre(type);
		$("."+pre+"mbCheck").each(function(){
			$(this).attr("checked",checked);
		});
	},
	/**
	 * 
	 */
	getMsg:function(id,type){
		var pre=D.mailbox.getIdPre(type);
		var mRow = $("#"+pre+"mBodyRow"+id);
		var mBody = $("#"+pre+"mBody"+id);
		if( !mRow.hasClass("hidden") ){
			mRow.addClass("hidden");
			return;
		}
		mRow.removeClass("hidden");
		if(mRow.hasClass("downloaded")){
			return;
		}
		mBody.html(D.image("loading1.gif"));
		$.get(D.url("mailbox","getmsg","id",id,"from",type), function(msg){
			mBody.html(msg);
			mRow.addClass("downloaded");
			if(type=='inbox'){
				$("#"+id).removeClass("fwB");
			}
		});
	},
	/**
	 * 
	 */
	hideMsg:function(id,type){
		var pre=D.mailbox.getIdPre(type);
		$("#"+pre+"mBodyRow"+id).addClass("hidden");
	},
	/**
	 * 
	 */
	empty:function(type){
		D.confirm(lang["confEmptyMail"], lang['confirm'], function(){
			$.post(D.url('mailbox','deleteAllMail'), {'type':type}, function(response){
				if( D.isOk(response) ){
					var tabs = $("div.tabs").tabs();
					tabs.tabs('load', tabs.tabs('option','selected')); 
				}
			},"json");
		});
	},
	deleteSelected:function(type){
		D.confirm(lang["confDelSelectedMsgs"], lang['confirm'] ,function() {
			var pre=D.mailbox.getIdPre(type);
			var e=$("."+pre+"mbCheck");
			var selected = [];
			e.each(function(){
				if( this.checked == true){
					var id = this.id.substr(1,this.id.length-1);
					selected.push(id);
				}
			});
			D.mailbox.deleteMsgs(selected.join("-"), type);
		});
	},
	/**
	 * 
	 */
	deleteMsgs:function(ids,type){
		var pre=D.mailbox.getIdPre(type);
		$.post(D.url('mailbox','deletemsg'), {'type':type, 'ids':ids}, function(deleted){
			var deleted = eval(deleted);
			for(i=0; i < deleted.length; i++){
				D.fadeOut("#"+pre+"mr"+deleted[i]);
				D.fadeOut("#"+pre+"mBodyRow"+deleted[i]);
			}
		});
	},
	/**
	 * 
	 */
	markAsUnread:function(){
		var selected = [];
		$(".mbCheck").each(function(){
			if( this.checked == true){
				var id = this.id.substr(1,this.id.length-1);
				selected.push(id);
			}
		});
		$.post(D.url("mailbox","markunread"),{"ids":selected.join('-')}, function(marked){
			marked = eval(marked);
			for(i=0;i<marked.length; i++){
				$("#"+marked[i]).addClass("fwB");
			}
			D.mailbox.checkAll('inbox', false);
		});
	}
};
D.cache = {
	data : [],
	set : function(id,value, ttl){
	D.cache.data[id] = {};
	
	D.cache.data[id].ttl = D.time() + ttl
	D.cache.data[id].value = value;
	},
	isSet:function(id){
		var t = typeof D.cache.data[id];
		if( t != 'undefined' ){
			if( D.cache.data[id].ttl > D.time() ){
				return true;
			}
		}
		return false;
	},
	get : function(id){
		return D.cache.data[id].value;
	}
};

D.album = {
	/**
	 * 
	 */
	uploadCntr:0,
	/**
	 * 
	 */
	deleteAlbum:function(albumId){
		D.confirm(lang["confDelAlbum"], lang['confirm'] ,function(result) {
			$.post(D.url('albums','deleteAlbum'), {'aid':albumId}, function(response){
				if( D.isOk(response) ){
					D.goTo(D.url('albums'));
				}else if( response.error.length>0 ){
					D.alert(response.error);
				}
			},"json");
		});
	},
	/**
	 * 
	 */
	deleteComment:function(mid,aid,cid){
		D.deleteIt(D.url('albums','deleteComment','mid',mid,'aid',aid), {'cid':cid}, "comment"+cid, lang["confDelComment"]);
	},
	/**
	 * 
	 */
	postComment:function(mid, aid, pid){
		D.postForm("postPhotoComment", D.url('albums','postPhotoComment','mid',mid,'aid',aid,'pid',pid), function(){
			$("#postPhotoComment").fadeOut("slow",function(){
				$(this).parent().html('<div class="notice">' + lang["commentSuccess"] + '</div>');
			});
		});
	},
	/**
	 * 
	 */
	createForm:function(action){
		var dId = D.guid();
		var fId = D.guid();
		var form = $('<form id="' + fId + '" method="post" enctype="multipart/form-data" action="' + action + '" class="mform" />');
		$('<input type="file" name="userfile" />').appendTo(form);
		$('<input type="submit" value="'+lang['vUpload']+'" />').appendTo(form);
		form.appendTo("#UploadPhotosWrap");
		form.jup({
			"beforeUpload":function(){
				D.album.uploadCntr++;
				D.album.updateUploadStatus();
			},
			"validate" : function(fields){
				if( fields.userfile.length == 0 || !D.isImageFile(fields.userfile) ){
					return false;
				}
				return true;
			},
			"onComplete":function(response, e, f){
				D.album.uploadCntr--;
				D.album.updateUploadStatus();
				if( D.isOk(response) ){
					var html = '<img src="' + response.url + '" class="img i50">';
					$("#uploadedPhotos").append(html);
					D.show("#uploadedPhotos");
					form.remove();					
				}else{
					alert(response.error);
				}
			}
		});
	},
	/**
	 * 
	 */
	updateUploadStatus:function(){
		if( D.album.uploadCntr == 0 ){
			D.hide("#uploadPhotosStatus");
		}else{
			$("#uploadPhotosStatus").html("جاري رفع " + D.album.uploadCntr + " صور، الرجاء عدم اغلاق هذه الصفحة حتى تتم العملية " + D.image('loading1.gif'));
			D.show("#uploadPhotosStatus");
		}
	},
	/**
	 * 
	 */
	editPhotoTitle:function(mid,aid,pid,link){
		var title = L.trim( $("#photoTitle"+pid).attr("value") );
		if(title.length=0){
			return;
		}
		link = $(link);
		var statusId = 'editTitleStatus'+pid;
		var status = link.parent().find("#"+statusId);
		if( parseInt(status.length) == 0 ){
			link.parent().append(' <span id="'+statusId+'" class="notice"></span>');
			status = link.parent().find("#"+statusId);
		}
		status.html(lang["processing"]);
		$.post(D.url('albums','editPhotos','mid',mid,'aid',aid), {'act':'title','pid':pid,'title':title}, function(response){
			if(D.isOk(response)){
				status.html(lang["done"]);
			}else{
				status.html(lang["unknownError"]);
			}
		}, "json");
	},
	/**
	 * 
	 */
	deletePhoto:function(mid,aid,pid,link){
		D.confirm(lang["confDelPhoto"], lang['confirm'] ,function(result) {
			link = $(link);
			var statusId = 'deleteStatus'+pid;
			var status = link.parent().find("#"+statusId);
			if( parseInt(status.length) == 0 ){
				link.parent().append(' <span id="'+statusId+'" class="notice"></span>');
				status = link.parent().find("#"+statusId);
			}
			status.html(lang["processing"]);
			$.post(D.url('albums','editPhoto','mid',mid,'aid',aid), {'act':'delete','pid':pid}, function(response){
				if(D.isOk(response)){
					D.goTo(D.url('albums', 'album','mid',mid,'aid',aid));
				}else{
					status.html(lang["unknownError"]);
				}
			}, "json");
		});
	},
	/**
	 * 
	 */
	setThumbnail:function(mid,aid,pid,link){
		link = $(link);
		var statusId = 'setThumbnailStatus'+pid;
		var status = link.parent().find("#"+statusId);
		if( parseInt(status.length) == 0 ){
			link.parent().append(' <span id="'+statusId+'" class="notice"></span>');
			status = link.parent().find("#"+statusId);
		}
		status.html(lang["processing"]);
		$.post(D.url('albums','editPhoto','mid',mid,'aid',aid), {'act':'thumbnail','pid':pid}, function(response){
			status.html(lang["done"]);
		}, "json");
	}
};
D.group = {
	editLogo:function(formId, groupId){
		$("#"+formId).jup({
			"validate" : function(fields){
				if( fields.logoFile.length == 0 ){
					D.error("editGroupLogoStatus", lang['photoUpNotSelected']);
					return false;
				}
				if( !D.isImageFile(fields.logoFile) ){
					D.error("editGroupLogoStatus", lang['photoExtNotice']);
					return false;
				}
				$("#editGroupLogoStatus").removeClass("error").html("");
				return true;
			},
			"beforeUpload":function(){
				D.notice("editGroupLogoStatus", lang["photoUploading"] + D.image("loading1.gif") );
			},
			"onComplete":function(response){
				// submitBtn.attr("disabled",false);
				if( D.isOk(response) ){
					D.notice('editGroupLogoStatus', lang["success"]);
					// uStatus.addClass("notice").removeClass("error").html(lang["success"]);
				}else if( response.error.length > 0 ){
					D.error('editGroupLogoStatus', response.error);
					// uStatus.addClass("error").removeClass("notice").html(response.error);
				}
			}
		});
		
		return false;
	},
	wall:{
		post:function(formId){
			D.postForm(formId,  D.url('group','postToWall'), function(response){
				var tabs = $("div.tabs").tabs();
				tabs.tabs('load', tabs.tabs('option','selected'));
				
			});
		},
		deleteEntry:function(groupId, entryId){
			D.deleteIt(D.url('group','deleteWallEntry'), {'groupId':groupId, 'entryId':entryId}, "gwEntry"+entryId, lang["confDelMsg"]);
		}
	},
	members:{
		addAdmin:function(groupId, memberId){
			$.post(D.url('group','editAdmin'),{'act':'add','id':groupId, 'mid':memberId},function(response){
				if(D.isOk(response)){
					$("#grMemberLink"+memberId).html(lang["done"]);
					
				}
			}, "json");
		},
		removeAdmin:function(groupId, memberId){
			$.post(D.url('group','editAdmin'),{'act':'remove','id':groupId, 'mid':memberId},function(response){
				if(D.isOk(response)){
					$("#grMemberLink"+memberId).html('<button onclick="D.group.members.addAdmin('+groupId+','+memberId+')" class="actBtn">'+lang["addToAdmins"]+'</button>');
					D.fadeOut("#grAdmin"+memberId);
					
				}
			}, "json");
		},
		removeMember:function(groupId, memberId){
			D.confirm(lang["confRemoveFromGroup"], lang["confirm"], function(){
				$.post(D.url('group','deleteMember'),{'id':groupId, 'mid':memberId},function(response){
					if(D.isOk(response)){
						D.fadeOut("#grMember"+memberId);
						D.fadeOut("#grAdmin"+memberId);	
					}
				}, "json");
			});
		},
		approveJoin : function(groupId, memberId, approve){
			$.post(D.url('group','joinApplications','id', groupId, 'mid', memberId),{'approve':approve},function(response){
				if(D.isOk(response)){
					D.fadeOut("#jap"+memberId);
				}
			}, "json");
		}
	},
	deleteGroup:function(groupId){
		D.confirm(lang["confDelGroup"], lang["confirm"], function(){
			$.post(D.url('groups','deleteGroup'),{'id':groupId},function(response){
				if(D.isOk(response)){
					D.goTo(D.url('groups','my'));	
				}
			}, "json");
		});
	},
	newTopic:function(){
		var editor = D.editor("#newTopicBody","400px");
		D.postForm("newTopicForm",  D.url('group','newTopic'), function(response){
				var u=D.url('group','topic','id',response.topicId, 'gid',response.groupId);
				D.goTo(u);
		},null, function(){
			$('#newTopicBody').val(editor.get_html());
		});
	},
	editTopic:function(topicId, groupId){
		var editor = D.editor("#topicBody","400px");
		var form = $("#editTopicForm");
		var url = D.url('group','editTopic','tid',topicId,'gid',groupId);
		var submitBtn = form.find("input[type=submit]");
		form.submit(function(e){
			e.preventDefault();
			$('#topicBody').val(editor.get_html());
			submitBtn.attr("disabled",true);
			$.post(url, form.serialize(), function(response){
				submitBtn.attr("disabled",false);
				if( D.isOk(response) ){
					var u=D.url('group','topic','id',topicId, 'gid', groupId);
					D.goTo(u);
				}else{
				}
			}, "json");
		});
	},
	editReply:function(replyId, topicId, groupId){
		var editor = D.editor("#replyBody","400px");
		var form = $("#editTopicReplyForm");
		var url = D.url('group','editTopicReply','rid',replyId,'tid',topicId,'gid',groupId);
		var submitBtn = form.find("input[type=submit]");
		var status = $("#editTopicReplyStatus");
		form.submit(function(e){
			e.preventDefault();
			$('#replyBody').val(editor.get_html());
			submitBtn.attr("disabled",true);
			status.addClass("notice").removeClass("error").html(D.image("loading1.gif"))
			$.post(url, form.serialize(), function(response){
				submitBtn.attr("disabled",false);
				if( D.isOk(response) ){
					var u=D.url('group','topic','id',topicId, 'gid', groupId);
					D.goTo(u);
				}else if(response.error.length>1){
					status.addClass("error").removeClass("notice").html(response.error)
				}
			}, "json");
		});
	},
	deleteTopic:function(topicId, groupId){
		D.confirm(lang["confDelTopic"], lang["confirm"], function(){
			$.post(D.url('group','deleteTopic'),{'tid':topicId, 'gid':groupId},function(response){
				if( D.isOk(response) ){
					D.goTo(D.url('group','id',groupId));	
				}
			}, "json");
		});
	},
	topicReply:function(topicId, groupId){
		var editor = D.editor("#replyArea","200px");
		var form = $("#topicReplyForm");
		var url = D.url('group','topicReply','tid',topicId,'gid',groupId);
		var submitBtn = form.find("input[type=submit]");
		
		form.submit(function(e){
			e.preventDefault();
			$('#replyArea').val(editor.get_html());
			submitBtn.attr("disabled",true);
			$.post(url, form.serialize(), function(response){
				submitBtn.attr("disabled",false);
				if( D.isOk(response) ){
					var u=D.url('group','topic','id',topicId, 'gid', groupId);
					D.goTo(u);
				}else{
				}
			}, "json");
		});
	},
	closeTopic:function(topicId, groupId, close){
		var act = (close) ? 'close':'reopen';
		D.confirm(lang["confCloseTopic"], lang["confirm"], function(){
			$.post(D.url('group','closeTopic'), {"topicId":topicId, "groupId":groupId, 'act':act}, function(response){
				if( D.isOk(response) ){
					D.reloadWindow();
				}else{
					D.alert(response.error);
				}
			}, "json");
		});
	},
	deleteTopicReply:function(replyId, topicId, groupId){
		D.deleteIt(D.url('group','deleteTopicReply'), {'rid':replyId,'tid':topicId, 'gid':groupId}, "reply"+replyId, lang["confDelReply"]);
	},
	joinGroup:function(groupId, topicId){
		D.confirm(lang["confJoinGroup"], lang["confirm"], function(){
			$.post(D.url('group','joinGroup'),{'gid':groupId},function(response){
				if(D.isOk(response)){
					if( response.extraMsg.length > 0 ){
						D.alert(response.extraMsg);
						return;
					}
					if( !L.isUndefined(topicId) ){
						D.goTo(D.url('group','topic','id',topicId,'gid',groupId));
					}else{
						D.goTo(D.url('group','id',groupId));
					}
				}else if(response.error.length>1){
					D.alert(response.error);
				}
			}, "json");
		});
	},
	leaveGroup:function(groupId){
		D.confirm(lang["confLeaveGroup"], lang["confirm"], function(){
			$.post(D.url('group','leaveGroup'),{'gid':groupId},function(response){
				if( D.isOk(response) ){
					D.goTo(D.url('group','id',groupId));	
				}else if(response.error.length>1){
					D.alert(response.error);
				}
			}, "json");
		});
	},
	addGroupPhoto : function(){
		$("#uploadGPhotoForm").jup({
			"validate" : function(fields){
				if( fields.userfile.length == 0 ){
					D.error("uploadGPhotoStatus", lang['photoUpNotSelected']);
					return false;
				}
				if( !D.isImageFile(fields.userfile) ){
					D.error("uploadGPhotoStatus", lang['photoExtNotice']);
					return false;
				}
				$("#uploadGPhotoStatus").removeClass("error").html("");
				return true;
			},
			"beforeUpload":function(){
				$("#uploadGPhotoStatus").addClass("notice").removeClass("error")
				.html(lang["photoUploading"] + D.image("loading1.gif"));
			},
			"onComplete":function(response){
				if( D.isOk(response) ){
					D.notice("uploadGPhotoStatus", lang["photoUpSuccess"]);
				}else{
					D.error("uploadGPhotoStatus", response.error);
				}
			}
		});
	},
	deleteAlbumPhoto : function(groupId, photoId){
		D.deleteIt(D.url('group','album','act','deletePhoto'), {'groupId':groupId, 'photoId':photoId}, "photo"+photoId, lang["confDelPhoto"]);
	},
	deleteNewsEntry:function(groupId, entryId, adminNews){
		var type = (adminNews==true) ? "admin":"normal";
		$.post(D.url('group','deleteNewsfeedEntry'),{"groupId":groupId,"entryId":entryId,"type":type},function(response){
			if( D.isOk(response) ){
				D.fadeOut("#gNews"+entryId);
			}else{
				D.alert(response.error);
			}
		},"json");
	},
	stickyTopic : function(topicId, act){
		$.post(D.url('group','stickTopic'),{'topicId':topicId,'act':act}, function(response){
			if( D.isOk(response) ){
				if( act == 'remove' ){
					D.fadeOut("#stickyTopic"+topicId);
				}else{
					D.alert(lang['done']);
				}
			}else{
				D.alert(response.error);
			}
		},"json");
	}
};
D.music =  {
	upload:function(){
		function validateAddMusic(fields){
			if( fields.artistName.length == 0  && fields.artistId.length == 0 ){
				D.error("addMusicStatus", lang['podcastSelectArtist']);
				return false;
			}
			if( fields.title.length == 0){
				D.error("addMusicStatus", lang['podcastNoTitle']);
				return false;
			}
			if( fields.userfile.length == 0 ){
				D.error("addMusicStatus", lang['podcastNotSelected']);
				return false;
			}
			var ext = D.getFileExtention( fields.userfile );
			if( ext != 'mp3' ){
				D.error("addMusicStatus", lang['podcastExtNotice']);
				return false;
			}
			return true;
		};
		$("#addMusicForm").jup({
			"validate" : validateAddMusic,
			"beforeUpload":function(){
				D.notice("addMusicStatus", D.image("loading1.gif"));
			},
			"onComplete":function(response){
				if( D.isOk(response) ){
					D.goTo(D.url('music','track','id',response.trackId));
				}else{
					D.error("addMusicStatus", response.error);
				}
			}
		});
	},
	deleteArtistWallEntry:function(artistId, entryId){
		D.deleteIt(D.url('music','artist','id',artistId,'act','deleteArtistWallEntry'), {'entryId':entryId}, "wallEntry"+entryId, lang["confDelComment"]);
	},
	deleteTrackComment:function(commentId){
		D.deleteIt(D.url('music','deleteTrackComment'), {"commentId":commentId}, "tComment"+commentId, lang["confDelComment"]);
	},
	addRemoveFan:function(artistId, addOrRemove){
		var act = ( addOrRemove == false ) ? "remove":"add";
		$.post(D.url('music','addRemoveFan'),{'id':artistId, 'act':act},function(response){
			if( D.isOk(response) ){
				$("#addRemoveFanWrap").html(lang['success']);
			}
		},"json");
	},
	addArtistPhoto:function(){
			$("#uploadAPhotoForm").jup({
				"validate" : function( fields ){
					if( fields.userfile.length == 0 ){
						D.error("uploadAPhotoStatus", lang['photoUpNotSelected']);
						return false;
					}
					if( !D.isImageFile(fields.userfile) ){
						D.error("uploadAPhotoStatus", lang['photoExtNotice']);
						return false;
					}
					return true;
				},
				"beforeUpload" : function(){
					D.notice("uploadAPhotoStatus", lang["photoUploading"]+D.image("loading1.gif") );
				},
				"onComplete" : function(response){
					if( D.isOk(response) ){
						D.notice("uploadAPhotoStatus", lang["photoUpSuccess"]);
					}else{
						D.error("uploadAPhotoStatus", response.error);
					}
				}
			});
	},
	deleteArtistPhoto : function(photoId){
		D.deleteIt(D.url('music','deleteArtistPhoto'), {'photoId':photoId}, "photo"+photoId, lang["confDelPhoto"]);
	}
};
D.photos = {
	deleteComment : function(commentId, wrapId){
		D.deleteIt(D.url('photos','deletePhotoComment'), {"commentId":commentId}, wrapId, lang["confDelComment"]);
	},
	uploadPhoto : function(){
		var form = $("#uploadPhotoForm");
		form.jup({
			"validate" : function(fields){
				if( fields.userfile.length == 0 ){
					D.error("progressDiv", lang['photoUpNotSelected']);
					return false;
				}
				if( !D.isImageFile(fields.userfile) ){
					D.error("progressDiv", lang['photoExtNotice']);
					return false;
				}
				var flag = false;
				for(i=1; !flag && i<6; i++){
					if( L.trim(fields["tag"+i]).length > 0 ){
						flag = true;
					}
				}
				if( !flag ){
					D.error("progressDiv", lang["photoTagMissing"]);
					return false;
				}
				return true;
			},
			"beforeUpload":function(){
				D.notice("progressDiv", lang["photoUploading"] + D.image("loading1.gif"));
			},
			"onComplete":function(response){
				D.isOk(response) ? D.notice("progressDiv",lang["photoUpSuccess"]) : D.error("progressDiv",response.error);
				form.find("input[type=file]").each(function(){
					$this = $(this);
					$this.hide();
					$('<input type="file" name="userfile" />').insertBefore($this);
					$this.remove();
				});
				form.find("input[type=text],textarea").each(function(){
					$(this).val("");
				});
			}
		});
	}
};
D.starRating = function(settings){
	this.showRating = function(){
		if( settings.div.length == 0 ){
			return;
		}
		var html='<ul>';
		var i=0;
		for(;i<settings.rating;i++){
			html+='<li><a href="javascript:" class="full" id="'+settings.id+'star'+i+'"></a></li>';
		}
		for(;i<5;i++){
			html+='<li><a href="javascript:" class="empty"  id="'+settings.id+'star'+i+'"></a></li>';
		}
		html+='</ul>';
		extra=(settings.rating>0)?' | '+settings.ratingCntr+' '+lang["votes"]:'';
		html+='<div id="'+settings.id+'alt">'+settings.txt[settings.rating]+extra+'</div>';
		settings.div.html(html);
		if( settings.canRate ){
			for(i=0; i<5; i++){
				$("#"+settings.id+'star'+i).bind("mouseover", {pos:i+1},function(e){
					var pos = e.data.pos;
					if( settings.posting || settings.done ){
						return;
					};
					var i=0;
					for(; i<pos; i++){
						$("#"+settings.id+'star'+i).addClass("highlighted").removeClass("full").removeClass("empty");
					}
					for(;i<5;i++){
						$("#"+settings.id+'star'+i).addClass("empty").removeClass("full").removeClass("highlighted");
					}
					$("#"+settings.id+'alt').html(settings.txt[pos]);
				}).bind("mouseout", function(e){
					if( settings.posting || settings.done ){
						return;
					}
					var i=0;
					for( ; i < settings.rating; i++ ){
						$("#"+settings.id+'star'+i).addClass("full").removeClass("empty").removeClass("highlighted");
					}
					for(;i<5;i++){
						$("#"+settings.id+'star'+i).addClass("empty").removeClass("full").removeClass("highlighted");
					}
					extra = ( settings.rating>0) ? ' | ' + settings.ratingCntr + ' ' + lang["votes"] : '';
					$("#"+settings.id+'alt').html( settings.txt[settings.rating] + extra );
				}).bind("click", {rating:i+1}, function(e){
					if( !settings.canRate || settings.posting || settings.done ){
						return;
					}
					var param = $.extend({"rating":e.data.rating}, settings.extraParams);
					$.post(settings.url, param, function(response){
						if( D.isOk(response) ){
							settings.done = true;
							settings.canRate = false;
							$("#"+settings.id+'alt').html(lang["ratingSuccess"]);
						}else{
							D.alert(lang["cantAddVote"]);
						}
					}, "json");
				});
			}
		}
	};
	var defaults = {
			url : null,
			divId : null,
			rating : null,
			canRate : true,
			ratingCntr : 0,
			extraParams : null
	};
	settings.id=D.guid();
	settings.div=$("#"+settings.divId);
	settings.posting=false;
	settings.done=false;
	settings.txt= lang["photoRatings"];
	this.showRating();
};

D.questions = {
	deleteQuestion:function(questionId){
		D.deleteIt(D.url('questions','deleteQuestion'),{'questionId':questionId}, null, lang['confDelQuestion'], function(){
			D.alert("تم حذف السؤال بنجاح");
			D.load(D.url("questions"), "#questionsWrap");
		});
	},
	closeQuestion:function(questionId){
		$.post(D.url('questions','closeQuestion'),{'questionId':questionId},function(response){
			if( D.isOk(response) ){
				D.load(D.url("questions","question","id",questionId), "#questionsWrap");
			}else{
				D.alert(response.error);
			}
		},"json");
	},
	deleteAnswer:function(questionId, answerId, wrapId){
		D.deleteIt(D.url('questions','deleteAnswer'),{'questionId':questionId, 'answerId':answerId}, wrapId, lang["confDelAnswer"]);
	},
	setBestAnswer:function(questionId, answerId){
		$.post(D.url('questions','setBestAnswer'),{'questionId':questionId, 'answerId':answerId},function(response){
			if( D.isOk(response) ){
				D.load(D.url("questions","question","id",questionId), "#questionsWrap");
			}else{
				D.alert(response.error);
			}
		},"json");
	}
};
D.video = {
	addToDB:function(videoId){
		$.post(D.url('video','addToSite'), {"videoId":videoId}, function(response){
			if( D.isOk(response) ){
				D.alert(lang['addVThank']);
			}
		},"json");
	}
};
D.editor=function(selector, height){
	var editor = $(selector).css("height",height).css("text-align","right").htmlbox()
	   .idir(D.config.baseUrl+"js/jquery/plugins/htmlbox/images/")
	    .button("bold").button("italic").button("underline")
	    .separator("dots").button("fontsize").button("fontcolor")
	    .separator("dots").button("right").button("center").button("left").button("justify")
	    .separator("dots",2).button("hyperlink",2).button("unlink",2).button("image",2).button("quote",2)
	    .separator("dots",2).button("removeformat",2);
	editor.init();
	return editor;
};
D.menu = function(id){
	// s$("#"+id).superfish();
	// return;
	var transition = {overtime:300, outtime:300};
	var menu = $("#"+id);
	var active=null;
	var headers = menu.children("li");
	headers.hover(function(e){
		var item = $(this);
		item.addClass('selected');
		if( item.hasClass("ui-corner-left") ){
			item.removeClass("ui-corner-left").addClass("ui-corner-left-inactive");
		}
	},function(e){
		var item = $(this);
		item.removeClass('selected');
		if( item.hasClass("ui-corner-left-inactive") ){
			item.removeClass("ui-corner-left-inactive").addClass("ui-corner-left");
		}
	});
	
	headers.each(function(i){
		$(this).attr("id", "m"+D.guid());
		var ch = $(this).children("ul");
		if( ch.length == 0 ){
			return;
		}
		var top = $(this).css({zIndex: 100-i});
		top.hover(function(e){
			var el = $(this);
			var ul = el.children("ul");
			var oActive;
			
			function show(){
				if( active!= null && active != el.attr("id") ){
					return;
				}
				ul.fadeIn('fast');
				active = el.attr("id");
			}
			setTimeout(show, 1);
				
		},function(e){
			var el = $(this);
			var oTar = $(e.relatedTarget);
			
			function hide(){
				// alert(el.attr("tagName")+el.attr("id")+"-----"+active+":");
				
				var p = el.parent().parent();
				if( el.attr("id") == oTar.attr("id") ){
					return
				}
				el.children("ul").fadeOut("fast");
				active  = null;
			};
			setTimeout(hide, 0);
		});
	});
	menu.find("ul").css({display:'none', visibility:'visible'});
	
};
D.TB = {
	activePanel : null,
	notis : [],
	notiPanel : "#notiPanel",
	init:function(notifications){
		if( !D.config.isLogged ){
			return;
		}
		D.TB.active = true;
		D.TB.refreshIn = 40000;
		D.TB.res = notifications;
		D.TB.display();
		if( D.cookie('TBActive') == 'noti' ){
			D.TB.toggleNoti();
		}
		if( D.cookie('TBActive') == 'friends' ){
			D.TB.friends.toggle();
		}
		D.TB.onlineStatus.show();
		setTimeout(D.TB.update, D.TB.refreshIn);
	},
	
	hideActive:function(){
		D.hide("#qLinksPanel");
		if( D.TB.activePanel == null ){
			return;
		}
		D.hide(D.TB.activePanel);
		
		$(D.TB.activePanel).parent().children("a").removeClass('ui-state-active');
		D.TB.activePanel = null;
		D.cookie('TBActive',null);
	},
	toggleNoti:function(){
		
		var panel = $(D.TB.notiPanel);
		if( !panel.hasClass("hidden") ){
			D.hide(D.TB.notiPanel);
			panel.parent().children("a").removeClass('ui-state-active');
			D.cookie('TBActive',null);
			return;
		}
		D.TB.hideActive();
		D.cookie('TBActive','noti');
		D.TB.activePanel = D.TB.notiPanel;
		panel.removeClass("hidden");
		panel.parent().children("a").addClass('ui-state-active');
		if( D.TB.res.newNotis > 0 ){
			$.post(D.url('profile','notifications','act','setRead'),{'readAt' : D.TB.res.readAt}, function(response){
				if(D.isOk(response)){
					D.TB.res.newNotis = 0;
				}
			},"json");
		}
		
	},
	update:function(){
			if( !D.TB.active ){
				return;
			}
			$.get(D.url('profile','notifications','readAt',D.TB.res.readAt),{},function(response){
				D.TB.res = response;
				D.TB.display();
				setTimeout(D.TB.update, D.TB.refreshIn);
			}, "json");
	},
	display:function(){
			if( !D.isOk(D.TB.res) ){
				return;
			}
			
			if(D.TB.res.mbCounter > 0){
				$("#mbNotiCntr").html(D.TB.res.mbCounter).addClass("ui-state-highlight");	
			}else{
				$("#mbNotiCntr").html(D.TB.res.mbCounter).removeClass('ui-state-highlight');
			}
			if( parseInt(D.TB.res.friendRequests) == 0){
				D.hide("#mbFriendRequests");
			}else{
				D.show("#mbFriendRequests");
				$("#mbFRCntr").html(D.TB.res.friendRequests).addClass("ui-state-highlight");
			}
			if( D.TB.res.newNotis > 0 ){
				D.show("#notiCntr", D.TB.res.newNotis);
				$("#notiCntr").addClass("ui-state-highlight");
			}else{
				D.hide("#notiCntr");
			}
			$(D.TB.notiPanel + " > div ").html('');
			for(i=0; i < D.TB.res.notis.length; i++ ){
				$(D.TB.notiPanel + " > div ").append('<p class="borderB1">'+D.TB.res.notis[i] + '</p>');
			}
			
			
	},
	onlineStatus:{
		setting:false,
		show:function(){
			$("#tbOnlineStatus > img").attr("src", D.config.showOnlineStatus ? D.image("online.gif", "mr0", false) : D.image("offline.gif", "mr0", false) );
			$("#tbOnlineStatus > span").html(D.config.showOnlineStatus ? lang["amOnline"] : lang["amOffline"]);
			D.show("#tbOnlineStatus");
		},
		toggle:function(){
			if(D.TB.onlineStatus.setting){
				return;
			}
			D.TB.onlineStatus.setting = true;
			var show = ( D.config.showOnlineStatus ) ? "false" : "true";
			$("#tbOnlineStatus > img").attr("src",D.image("working.gif","", false));
			$.post(D.url('actions','updateShowOnlineStatus'),{"show":show}, function(response){
				if( D.isOk(response) ){
					D.config.showOnlineStatus = (response.show == "true");
					D.TB.onlineStatus.show();
					D.TB.onlineStatus.setting = false;
				}
				$("#tbOnlineStatus").removeClass("ui-state-active");
			},"json");
		}
	},
	themesToggler:function(){
		var panel = $("#themePanel");
		if( !panel.hasClass("hidden") ){
			D.hide(panel);
			panel.parent().children("a").removeClass('ui-state-active');
			return;
		}
		panel.removeClass("hidden");
		panel.parent().children("a").addClass('ui-state-active');
		panel.find('div > p').html(D.image('loading2.gif'));
		$.get(D.url('themes','get'),{},function(response){
			panel.find('div > p').html(response);
		});
	},
	friends:{
		panelId : "#friendsPanel",
		active : false,
		toggle : function(){
			panel = $(D.TB.friends.panelId);
			if( !panel.hasClass("hidden") ){
				D.hide(panel);
				panel.parent().children("a").removeClass('ui-state-active');
				D.cookie('TBActive',null);
				D.TB.friends.active = false;
				return;
			}
			D.TB.friends.active = true;
			D.TB.hideActive();
			D.cookie('TBActive','friends');
			D.TB.activePanel =panel;
			panel.removeClass("hidden");
			panel.parent().children("a").addClass('ui-state-active');
			$(D.TB.friends.panelId +" > div").html( D.image('loading1.gif') );
			D.TB.friends.update();
		},
		update:function(){
			if( !D.TB.friends.active ){
				return;
			}
			panel = $(D.TB.friends.panelId);
			
			var cId = 'tbOFriends';
			if( D.cache.isSet(cId) ){
				var cache = D.cache.get(cId);
				$(D.TB.friends.panelId + " > div").html(cache);
			}
			else{
				$.get(D.url('friends','onlineFriends'),{},function(response){
					$(D.TB.friends.panelId + " > div").html(response);
					D.cache.set(cId, response, 55000);
					setTimeout(D.TB.friends.update, 60000);
				});
			}
		}
	},
	qLinks:{
		panelId:'#qLinksPanel',
		toggle:function(){
			panel = $(D.TB.qLinks.panelId);
			if( !panel.hasClass("hidden") ){
				D.hide(panel);
				panel.parent().children("a").removeClass('ui-state-active');
				D.cookie('TBActive',null);
				D.TB.qLinks.active = false;
				return;
			}
			D.TB.qLinks.active = true;
			D.TB.hideActive();
			panel.removeClass("hidden");
			panel.parent().children("a").addClass('ui-state-active');
			D.TB.qLinks.load();
		},
		load : function(){
			var div = $(D.TB.qLinks.panelId +" > div");
			div.html( D.image('loading1.gif') );
			$.get(D.url('profile','quickLinks'),{},function(response){
				div.html(response);
			});
		},
		add : function(){
			var title = $("#tbFavAddTitle").val();
			var url = document.location.href;
			if( title.length == 0 ){
				return;
			}
			$("#tbFavAddStatus").removeClass('error').html(D.image('loading1.gif'));
			$.post(D.url('actions','quickLink','act','add'),{'url':url, 'title':title},function(response){
				if( D.isOk(response) ){
					D.TB.qLinks.load();
				}
			},"json");
		},
		remove : function(linkId){
			$.post(D.url('actions','quickLink','act','remove'),{'linkId':linkId}, function(response){
				if( D.isOk(response) ){
					D.fadeOut("#tbFavEntry"+linkId);
				}
			},"json");
		}
	}
};
$(document).ready(function(){D.init(gConfig);});