/*
 * JavaScript interface to the SB network.
 * class SB.profile - manipualtion with the profile
 *
 * Requirements: jQuery library 1.4.2 and above
 * Copyright (C) 2010 Tomas Hnilica.   All Rights Reserved.
 */
 
/**
Interface to the profile
*/ 

SB.profile = function(uid, init) {
	 if (init == null) init = true;
   this.uid = uid;
   if (init) {
		   this.addProfilePhotoControls();
		   this.addActivityControls();
		   this.addPersonalControls();
		   this.addBlogControls();
		   this.addBlogPostControls();
		   this.addPhotoGalleriesControls();
		   this.addPhotoGalleryControls();
		   this.addProfileControls();
		   
		
		   $('.jq-button').button();
	}   

   
   
};

SB.profile.prototype.permsSelect = function(key) {
      var code = "&nbsp;<select id='perm_"+key+"'  name='perm_"+key+"'><option value='0'>Všichni</option><option value='5'>Přátelé</option><option value='10'>Nikdo</option></select>";
      return code;
}

SB.profile.prototype.addProfileControls = function() {
	if (this.uid == SBuser.uid) {
	  /** add to friends button if not a friend and if registered */
	  
	  /* lector section*/
	   $("#userLectors li").each(function() {
	   		var code = "<a href='#' alt='odebrat' class='fr' onclick='SBuser.remSKLector(\""+$(this).attr('uid')+"\");return false;'><img class='cross' alt='odebrat' src='/css/gfx/cross.png'></a>";
	  		$(this).append(code);
	  	});

	  /* friends section*/
	   $("#userFriendsList li").each(function() {
	   		var code = "<a href='#' alt='odebrat' class='fr' onclick=\"SBuser.removeFriend('"+$(this).attr('uid')+"');return false;\"><img class='cross' alt='odebrat' src='/css/gfx/cross.png'></a>";
	  		$(this).append(code);
	  	});
	  	
	}
}

SB.profile.prototype.addProfilePhotoControls = function() {
	if (this.uid == SBuser.uid) {
		  $('#profile-photo').attr('title','Kliknutím změníte svoji profilovou fotku');
		  $('#profile-photo').css('cursor','pointer');
      $('#profile-photo').tipsy({gravity: 's'});	
      var context = this;
      $('#profile-photo').click(function(){
       	context.changeProfilePhoto();
      });
	}
}

SB.profile.prototype.changeProfilePhoto = function() {
	    
			var uploadHTML = "";
			uploadHTML += '<input id="profile-image-upload" name="profile-image-upload" type="file" />';
			/*uploadHTML +='	  <a href="#" onclick="$(\'#uploadify-image\').uploadifyUpload(); return false;" class="jq-button">Nahrát</a>';*/

	jQuery("<div />", { id:"profile-photo-dialog", html: uploadHTML, "title": "Nahrát profilovou fotku" }).dialog({
		  width: 420, 
		  height: 200,
		  modal: true,
			buttons: {
				"Nahrát": function() { 
					$('#profile-image-upload').uploadifyUpload();
					/*$(this).dialog("close");*/
				},
				"Zrušit": function() { 
					$(this).dialog("close");
					$('#profile-photo-dialog').remove();
				}
			}	
		  });
			
			/*get the session ID from cookies. The uploadify is flash based and the session is not correct  - Adobe bug*/
			var start = document.cookie.indexOf("PHPSESSID=");
			var end = document.cookie.indexOf(";", start); // First ; after start
			if (end == -1) end = document.cookie.length; // failed indexOf = -1
			var cookie = document.cookie.substring(start+10, end);

				$("#profile-image-upload").uploadify({
					'buttonText'		 : 'Vybrat',
					'uploader'       : '/swf/uploadify.swf',
					'folder'         : '/images',
					'fileDesc'			 : 'Fotografie (*.jpg)',
					'cancelImg'      : '/css/uploadify/cancel.png',
					'fileExt'				 : '*.jpg;',
					'script'				 : '/ws/?ws=uploadProfilePhoto',
					'multi'          : false,
					'scriptData'     : { 'PHPSESSID': cookie  },
					'onComplete'	 : function (evt, queueID, fileObj, response, data) {
									$('#profile-photo').replaceWith(response);
									$('#profile-photo-dialog').dialog("close");
									$('#profile-photo-dialog').remove();
									SBprofile.addProfilePhotoControls();
									
						}
				});
 
}

/*append controls for the activity part */
SB.profile.prototype.addActivityControls = function() {
	 var context = this;
   if (this.uid == SBuser.uid || $('#profile-wall-new-post').length) {
     /*add controls to the activity feed*/
     var code = "<a href='#' onclick='this.blur(); SBprofile.deleteActivity($(this).parent().parent());return false;' class='buttonLike fr profile-activity-delete'><span>smazat</span></a>";
     $('.profile-wall-record-controls[actuid='+SBuser.uid+']').html(code);
     /*$('.jq-button').button();*/

     $('.profile-activity-delete').hide();
		 $(".profile-wall-record").mouseover(function() {
					$(this).find('.profile-activity-delete').show();
						}).mouseout(function() {
					$(this).find('.profile-activity-delete').hide();
				});
     
     
     /*append action for new post*/
     $('#profile-wall-addpost').unbind();
		if (this.uid == SBuser.uid) {
     		/*write on logged uses wall*/
		     $('#profile-wall-addpost').click(function(){
		     		  var message = $('#profile-wall-new-post').val();
		     		  SBuser.addActivity(message, 'ownwall', '', '', '', function(data){
									$(data).hide().prependTo('#profile-wall-activities').slideDown("slow");
							   $('#profile-wall-new-post').val('');
							   SBprofile.addActivityControls();
		     		  });
		     		  return false;
		     	});
			} else {
				 /*write on other user wall*/
				 $('#profile-wall-addpost span').html('vložit na zeď');
		     $('#profile-wall-addpost').click(function(){
		     		  var message = $('#profile-wall-new-post').val();
		     		  SBuser.addActivity(message, 'wall', '', '', context.uid, function(data){
									$(data).hide().prependTo('#profile-wall-activities').slideDown("slow");
							   $('#profile-wall-new-post').val('');
							   SBprofile.addActivityControls();
		     		  });
		     		  return false;
		     	});
			}

     	/*append some style to the new post area*/
			$('#profile-wall-new-post').focus(function() {
	     	  $('#profile-wall-new-post').val('');
	     	  $('#profile-wall-new-post').css('color','#000000');
			});

	    $('#profile-wall-new-post').val('Napište co máte právě na mysli.');
	    $('#profile-wall-new-post').css('color','#bbbbbb');
			/*
			$('#profile-wall-new-post').focusout(function() {
	     	  $('#profile-wall-new-post').val('Napište co máte právě na mysli.');
	     	  $('#profile-wall-new-post').css('color','#bbbbbb');
			});
			$('#profile-wall-new-post').trigger('focusout');
			*/
    
  } 
};

SB.profile.prototype.deleteActivity = function(act) {
		var actid = act.attr('actid');
		SBuser.deleteActivity(actid, function() {
		   act.hide('slow', function() {act.remove()});
		});
		return false;

};

SB.profile.prototype.moreActivity = function() {
  var offset = $('.profile-wall-record').size();
	var params = {}
	params["ws"] = "moreActivity";
	params["uid"] = this.uid;
	params["offset"] = offset;
	if ($('#profile-wall-activities').attr('content') == 'wallPosts') {
		params["ws"] = "moreWallPosts";
	}
	var context = this;
		$.get("/ws/", params, function(data){
			    if (data == "") {
			     $('#profile-wall-show-more').hide();
			  } else {
					   $('#profile-wall-activities').append(data);	
					   context.addActivityControls();

				}
	  	});
};

/**
	show only posts on the wall
*/
SB.profile.prototype.wallPosts = function() {
	var params = {}
	params["ws"] = "wallPosts";
	params["uid"] = this.uid;
	var context = this;
		$.get("/ws/", params, function(data){
					   $('#profile-wall-activities').html(data).attr('content','wallPosts');				   
	  	});
};


SB.profile.prototype.addPersonalControls = function() {
   if (this.uid == SBuser.uid) {
      var editbutton = "<a href='#' class='buttonLike fr' onclick='return SBprofile.editPersonalData();' id='profile-edit'><span>Upravit</span></a>";
      var changepwdbutton = "<a href='#' class='buttonLike fr' onclick='return SBprofile.chagePassword();' id='profile-changepwd'><span>Změnit heslo</span></a>";
      $('#profile-toolbar').html(editbutton + changepwdbutton);
   }   
}



SB.profile.prototype.editPersonalData = function() {
   /*change the data divs to editable*/
   var context = this;
   $('.profile-user-property-value').each(function() {
      var val = $(this).html();
      var key = $(this).attr('key');
      if (key=="about") {
      	/*replace <br> to newline to the textarea.*/
      	val = str_replace("<br>","\n",val);
      	var code = "<textarea name='"+$(this).attr('key')+"' id='personal-"+$(this).attr('key')+"'>" + val + "</textarea>";
      } else {
      	var code = "<input type='text' name='"+$(this).attr('key')+"' value='"+val+"' id='personal-"+$(this).attr('key')+"'>";
        code += "&nbsp;" + context.permsSelect(key);
        var perm = $(this).attr('perm');
      }
      $(this).html(code);
      $('#perm_' + key).val(perm);
   });

   var pcode = this.permsSelect("profile");
   var gperms = "<div class='profile-user-property'><div class='profile-user-property-label'>Práva prohlížet profil:</div><div class='profile-user-property-value'>" + pcode + "</div></div>";
   $('#profile-user-properties').prepend(gperms);
   var gp = $('#profile-user-properties').attr('perm');
   $('#perm_profile').val(gp);
   
   
   /*change toolbar*/
   var cancelbtn = "<a href='#' class='buttonLike fr' onclick='return SBprofile.getPersonalData();' id='profile-edit'><span>Zrušit</span></a>";
   var savebtn = "<a href='#' class='buttonLike fr' onclick='return SBprofile.savePersonalData();'><span>Uložit</span></a>";
   $('#profile-toolbar').html(savebtn + cancelbtn);
   /*$('.jq-button').button();*/
   /*customize the form*/
  /* $('#personal-birthdate').datepicker( { altFormat: 'dd. mm. yy', dateFormat: 'dd. mm. yy' } );*/
  
   /*append form validation methods, add fields to check */
   /*$('#personal-birthdate').addClass('dateCZ');*/
   
   $('form-profile-user-properties').validate();
   
   return false;
   
}

SB.profile.prototype.chagePassword = function() {
   var code = "<table>";
   code += "<tr><td>Původní heslo:</td><td><input type='password' name='profile-changepwd-original' id='profile-changepwd-original' size=20></td></tr>";
   code += "<tr><td>Nové heslo:</td><td><input type='password' name='profile-changepwd-new' id='profile-changepwd-new' size=20></td></tr>";
   code += "<tr><td>Nové heslo znovu:</td><td><input type='password' name='profile-changepwd-new2' id='profile-changepwd-new2' size=20></td></tr>";
   code += "</table>";
		jQuery("<div />", { id:"profile-changepwd-dialog", html: code, "title": "Změna hesla" }).dialog({
			  width: 320, 
			  height: 200,
			  modal: true,
				buttons: {
					"Změnit": function() { 
						var oldpwd = $('#profile-changepwd-original').val();
						var newpwd1 = $('#profile-changepwd-new').val();
						var newpwd2 = $('#profile-changepwd-new2').val();
						if (oldpwd == '') {thAlert("Původní helo musí být vyplněné!","Změna hesla");return false;}
						if (newpwd1 != newpwd2 || newpwd1 == "") {thAlert("Obě pole pro nové heslo se musí shodovat!","Zm2na hesla");return false;}
						var params = {}
						params["ws"] = "changePassword";
						params["oldpwd"] = oldpwd;
						params["newpwd"] = newpwd1;
						var dlg = this;
						$.get("/ws/", params, function(data){
							 var msg;
						   if (data == "1") msg = "Vaše heslo bylo změněno.";
						   else msg = "Při změně hesla došlo k chybě a heslo nebylo změněno.";
						   
						   thAlert(msg, "Změna hesla");
							 $(this).dialog("close");
							 $('#profile-changepwd-dialog').remove();
						});
 						
						
					},
					"Zrušit": function() { 
						$(this).dialog("close");
						$('#profile-changepwd-dialog').remove();
					}
				}	
			  });
}

SB.profile.prototype.savePersonalData = function() {
    /*check data*/
    if (!$('#form-profile-user-properties').valid()) {
       return false;
    }
    
    /*get the data*/
    var params = {}
   	$('#profile-user-properties').find("input, textarea, select").each(function() { 
			params[ this.name ] = this.value; 
		});
	 var context = this; 
   SBuser.saveUserProperties(params, function() {
      context.getPersonalData();
   });
   return false;

};
  
SB.profile.prototype.getPersonalData = function() {
	var params = {}
	params["ws"] = "getUserProfileHTML";
	params["uid"] = this.uid;
	$.get("/ws/", params, function(data){
    $('#profile-user-properties').replaceWith(data);
    SBprofile.addPersonalControls();
    $('.jq-button').button();
	});	
	return false;
  
  
};

/*
CREATE BLOG OBJECT INSTEAD?
*/

SB.profile.prototype.addBlogControls = function() {
   if (this.uid == SBuser.uid) {
     /*add controls to the blog posts list */
     var code = "<a href='#' onclick='SBprofile.addBlog();return false;' class='buttonLike fr'><span>nový zápis</span></a>";
     $('#blog-toolbar').append(code);
  } 
};

SB.profile.prototype.addBlog = function() {
	thPrompt("Zadejte název nového zápisu", "", "Nový zápis do blogu", function(r,v){
		if (!r) return;
		if (v == "") {
			thAlert("Musíte zadat název nového zápisu.","Nový zápis do blogu");
			return;
		}
		location.href = '/blog-zapis/'+this.uid+'/new/' + v + '/';
	})
}

SB.profile.prototype.addBlogPostControls = function() {
   
   $('#blog-entry-toolbar').html('');
   if (this.uid == SBuser.uid || SBuser.superUser() ) {
     /*add controls to the blog post */
     var code = "<a href='#' onclick='SBprofile.editBlogPost(); return false;' class='buttonLike fr'><span>upravit</span></a>";
     code += "<a href='#' onclick='SBprofile.deleteBlogPost(); return false;' class='buttonLike fr'><span>smazat</span></a>";
     $('#blog-entry-toolbar').append(code);

     /*save ID of the blog to this object */
     this.blogID = $('#blog-post-title').attr('blogid');
     
     if ($('#blog-post-title').attr('new') == '1') {
     	this.editBlogPost();
     }
 
   }
   
   /*append back button*/
   code = "<a href='/blog/"+this.uid+"/' class='buttonLike fr'><span>Zpět k blogu</span></a>";
   $('#blog-entry-toolbar').append(code);
	 
	 /*$('.jq-button').button();*/

}

SB.profile.prototype.editBlogPost = function() {
   /*change the data divs to editable*/
   var context = this;
      
   var title = $('#blog-post-title').attr('title');
   var content = $('#blog-post-text').html();  
   
   var titlecode = "<tr><td>Nadpis: </td><td><input type='text' name='blog-entry-head' value='"+title+"' id='blog-entry-head' class='blog-entry-head'></td>"; 
   var permcode = "<tr><td>Oprávnění: </td><td>" + this.permsSelect('perm') + "</td></tr>";
   var ctrlcode = "<table>" + titlecode + permcode + "</table>";
   $('#blog-post').prepend(ctrlcode);
   $('#perm_perm').val($('#blog-post-title').attr('perm'));
   $('#blog-post-title').html('');
   

   var textcode = "<textarea name='blog-entry-text' id='blog-entry-text' class='blog-entry-text'>" + content + "</textarea>"; 
   $('#blog-post-text').html(textcode);
   
   
   /*change toolbar*/
   var cancelbtn = "<a href='#' class='buttonLike fr' onclick='SBprofile.getBlogPost(); return false;' id='profile-edit'><span>zrušit</span></a>";
   var savebtn = "<a href='#' class='buttonLike fr' onclick='SBprofile.saveBlogPost(); return false;'><span>uložit</span></a>";
   var deletebtn = "<a href='#' onclick='SBprofile.deleteBlogPost(); return false;' class='buttonLike fr'><span>smazat</span></a>";
   $('#blog-entry-toolbar').html(savebtn + cancelbtn + deletebtn);
   $('.jq-button').button();

   /*customize the form (add wysiwyg, etc...)*/
   $('#blog-entry-text').wysiwyg();
   
   $('#profile-right').hide();
   
   return false;
   
}

SB.profile.prototype.deleteBlogPost = function() {
	var bid = this.blogID;
		var context = this;
		var params = {}
		params["ws"] = "deleteBlogPost";
		params["id"] = bid;
		
		thConfirm("Skutečně chcete smazat tento záznam?","Smazat záznam?", function(ret) {
		   if (ret) {
				$.get("/ws/", params, function(data){
						window.location = '/blog/' + context.uid + '/';
				});
		   }
		});
		return false;
}

/*retrieve blog entry code */
SB.profile.prototype.getBlogPost = function() {
		var params = {}
		params["ws"] = "getBlogPost";
		params["id"] = this.blogID;
		var context = this;
		$.get("/ws/", params, function(data){
					$('#blog-post').html(data);
					/*update controls*/
					context.addBlogPostControls();
	  	});
	  $('#profile-right').show();
		
}

/*save the blog data  */
SB.profile.prototype.saveBlogPost = function() {
    var params = {}
    params['head'] = $('#blog-entry-head').val();
    params['text'] = $('#blog-entry-text').val();
    params['perm'] = $('#perm_perm').val();
    params['id'] = this.blogID;
    var context = this;

		$.post("/ws/?ws=saveBlogPost", params, function(data){
			    if (data && data.ap) {
			       context.informAboutPoints(data)
			    }
			    context.getBlogPost();
	  	}, "json");
	  	return false;
   
}




/*
CREATE PHOTOGALLERY OBJECT INSTEAD?
*/


SB.profile.prototype.addPhotogallery = function() {
	thPrompt("Zadejte název nové fotogalerie", "", "Nová galerie", function(r,v){
		if (!r) return;
		if (v == "") {
			thAlert("Musíte zadat název nové fotogalerie.","Nová galerie");
			return;
		}
		location.href = '/fotogalerie/'+this.uid+'/new/' + v + '/';
	})
};

SB.profile.prototype.addPhotoGalleriesControls = function() {
   if (this.uid == SBuser.uid) {
     /*add controls to the blog posts list */
     var code = "<a href='#' onclick='SBprofile.addPhotogallery();return false;' class='buttonLike fr'><span>nová galerie</span></a>";
     $('#photo-toolbar').append(code);
     $('.jq-button').button();
     
  } 
};

SB.profile.prototype.addPhotoGalleryControls = function() {
   
   $('#photogallery-toolbar').html('');
   if (this.uid == SBuser.uid) {
     /*add controls to the photogallery */
     var code = "<a href='#' onclick='SBprofile.addPhotos(); return false;' class='buttonLike fr'><span>přidat fotky</span></a>";
     code += "<a href='#' onclick='SBprofile.editPhotoGallery(); return false;' class='buttonLike fr'><span>upravit</span></a>";
     code += "<a href='#' onclick='SBprofile.deletePhotoGallery(); return false;' class='buttonLike fr'><span>smazat</span></a>";
     $('#photogallery-toolbar').append(code);

     /*save ID of the blog to this object */
     this.photoGalleryID = $('#photogallery').attr('pgid');
     if ($('#photogallery').attr('new') == '1') this.addPhotos();
 
   }
   
   /*append back button*/
   code = "<a href='/foto/"+this.uid+"/' class='buttonLike fr'><span>Zpět k fotogaleriím</span></a>";
   $('#photogallery-toolbar').append(code);
	 
	 /*$('.jq-button').button();*/

}

SB.profile.prototype.addPhotos = function() {
			$('#photo-upload').show('slow');
			var uploadHTML = "<h3>Nahrát fotografie</h3>";
			uploadHTML += '<div id="dialog-image-browser-fileQueue"></div>';
			uploadHTML +='	  <input type="file" name="uploadify-image" id="uploadify-image" />';
			uploadHTML +='	  <div style="margin-top:0px; padding-top:0px; display:inline; position:relative; top:-12px;">';
			uploadHTML +='	  <a href="#" onclick="$(\'#uploadify-image\').uploadifyUpload(); return false;" class="jq-button">Nahrát fotky</a>  <a href="#" onclick="$(\'#uploadify-image\').uploadifyClearQueue(); return false;" class="jq-button">Vyčistit frontu</a>';
      uploadHTML +='    <a href="#" onclick="$(\'#photo-upload\').hide(\'slow\');  return false;" class="jq-button">Zavřít</a>';
			uploadHTML +='	  </div>';
			$('#photo-upload').html(uploadHTML);
			var context = this;
			
			/*get the session ID from cookies. The uploadify is flash based and the session is not correct  - Adobe bug*/
			var start = document.cookie.indexOf("PHPSESSID=");
			var end = document.cookie.indexOf(";", start); // First ; after start
			if (end == -1) end = document.cookie.length; // failed indexOf = -1
			var cookie = document.cookie.substring(start+10, end);


				$("#uploadify-image").uploadify({
					'buttonText'		 : 'Vybrat',
					'buttonImg'      : '/css/uploadify/browse.png',
					'uploader'       : '/swf/uploadify.swf',
					'script'         : '',
					'cancelImg'      : '/css/uploadify/cancel.png',
					'folder'         : '/images',
					'queueID'        : 'dialog-image-browser-fileQueue',
					'fileDesc'			 : 'Fotografie (*.jpg)',
					'fileExt'				 : '*.jpg;',
					'auto'           : false,
					'multi'          : true,
					'scriptData'     : { 'PHPSESSID': cookie },
					'onAllComplete'	 : function (event, data) {
						           
												$('#photo-upload').hide();
												/*post feed about this action*/
												var link = jQuery.url.attr("path"); 
												if ($('#photogallery').attr('new') == '1' ) {
											    SBuser.addActivity('založil novou [[a href='+link+' ]]fotogalerii[[/a]]', 'photogallery', context.photoGalleryID, link);
												  /*add points*/
											    var pd = {};
											    pd['ap'] = "1";
											    pd['apCat'] = "4";
											    pd['apText'] = "Byl vám připsán 1 bod v kategorii Aktivita za nahrání fotografií.";
											    pd['apTotal'] = context.pointsFromPage("4") + 1;
												  context.informAboutPoints(pd);
											  } else {
											    SBuser.addActivity('přidal nové fotky do galerie [[a href='+link+' ]]'+$('#photogallery-name').html()+'[[/a]]','photogallery', context.photoGalleryID, link);
											  }
												context.getPhotoGallery();
												
						}
						,
					'onComplete'	 : function (evt, queueID, fileObj, response, data) {
									/*if (response != '1') alert(response);*/
									/*if (SBuser.uid == 'musla') alert(response);*/
									
						}
				});
				
				$('.jq-button').button();
				   
};

SB.profile.prototype.editPhotoGallery = function() {
   /*close possibly open upload */
   $('#photo-upload').hide('slow');
   
   /*change the data divs to editable*/
   var context = this;
   var name = $('#photogallery-name').html();
   var desc = $('#photogallery-desc').html();  
   
   var namecode = "<tr><td>Název: </td><td><input type='text' name='photogallery-edit-name' value='"+name+"' id='photogallery-edit-name' class='photogallery-edit-name'></td></tr>"; 

   //$('#photogallery-name').html(namecode);

   var desccode = "<tr><td>Popis: </td><td><textarea name='photogallery-edit-desc' id='photogallery-edit-desc' class='photogallery-edit-desc'>" + desc + "</textarea></td></tr>"; 
   //$('#photogallery-desc').html(desccode);
   
   var permcode = "<tr><td>Oprávnění: </td><td>" + this.permsSelect('gperm') + "</td></tr>";
   //$('#photogallery').prepend(permcode);
   
   var ctrlcode = "<table>"+namecode+desccode+permcode+"</table>";
   
   $('#photogallery').prepend(ctrlcode);
   $('#perm_gperm').val($('#photogallery').attr('perm'));
   $('#photogallery-name').remove();
   $('#photogallery-desc').remove();

 
   /*edit single photos*/
    $('.photogallery-photo-desc').each(function() {
      var val = $(this).html();
      var code = "<textarea name='photogallery-photo-desc-edit' class='photogallery-photo-desc-edit'>"+val+"</textarea>";
      $(this).html(code);
   });
   var editcode = "<input type='radio' name='photo-default'>Titulní foto galerie<br><input type='checkbox' name='photo-delete'>Smazat";
    $('.photogallery-photo').append(editcode);
    $('.photogallery-photo').addClass('photogallery-photo-edit');
    var titlephoto = $('#photogallery').attr('titlephoto');
    if (titlephoto!='') {
    	var titlediv = $("div[photo="+titlephoto+"]");
    	if (titlediv) {
    	   titlediv.find("input[name=photo-default]").each(function() {
    	      $(this).attr('checked',true);
    	   });
    	}
    }

   
   /*change toolbar*/
   var cancelbtn = "<a href='#' class='buttonLike fr' onclick='SBprofile.getPhotoGallery();' id='profile-edit'><span>zrušit</span></a>";
   var savebtn = "<a href='#' class='buttonLike fr' onclick='SBprofile.savePhotoGallery();'><span>uložit</span></a>";
   $('#photogallery-toolbar').html(savebtn + cancelbtn);
   $('.jq-button').button();

   return false;
   
};

SB.profile.prototype.savePhotoGallery = function() {
    var params = {}
    params['name'] = $('#photogallery-edit-name').val();
    params['desc'] = $('#photogallery-edit-desc').val();
    params['perm'] = $('#perm_gperm').val();
    params['id'] = this.photoGalleryID;
    var context = this;

    /*comments of photos*/
    $('textarea[name=photogallery-photo-desc-edit]').each(function() {
      var val = $(this).val();
      var id = $(this).parent().parent().attr('photo');
      params['comment' + id] = val;
   });
   
   /*title photo*/
   $('#photogallery').find("input[name=photo-default]").each(function() {
      if ($(this).attr('checked')) {
      	params['photo'] = $(this).parent().attr('photo');
      }
   });
   
   /*files to delete*/
   $('#photogallery').find("input[name=photo-delete]").each(function() {
   	if ($(this).attr('checked')) {
        params['delete' + $(this).parent().attr('photo')] = 'yes';
    }
   });
   
		$.post("/ws/?ws=savePhotoGallery", params, function(data){
					context.getPhotoGallery();
	  	});
	  	return false;
};


SB.profile.prototype.deletePhotoGallery = function() {
		var context = this;
		var params = {}
		params["ws"] = "deletePhotoGallery";
		params["id"] = this.photoGalleryID;
		
		thConfirm("Skutečně chcete smazat tuto fotogalerii?","Smazat fotogalerii?", function(ret) {
		   if (ret) {
				$.get("/ws/", params, function(data){
						window.location = '/foto/' + context.uid + '/';
				});
		   }
		});
		return false;	
};

SB.profile.prototype.getPhotoGallery = function() {
		var params = {}
		params["ws"] = "getPhotoGallery";
		params["id"] = this.photoGalleryID;
		var context = this;
		$.get("/ws/", params, function(data){
					$('#photogallery-box').html(data);
					/*update controls*/
					context.addPhotoGalleryControls();
					$('a[rel*=lightbox]').lightBoxClone(); 
	  	});
};


SB.profile.prototype.informAboutPoints = function(obj) {
	 /*todo: test that the element is on the user profile, may be in another user page!!!*/
	$('#user-points-' + obj.apCat).html(obj.apTotal);
	thAlert(obj.apText,"Připsání bodů");
   
}

SB.profile.prototype.pointsFromPage = function(cat) {
	var curr = parseInt($('#user-points-' + cat).html());
  return curr;   
}

SB.profile.prototype.updatePoints = function(cat) {
		var params = {}
		params["ws"] = "getPoints";
		params["cat"] = cat;
		var context = this;
		$.get("/ws/", params, function(data){
       $('#user-points-' + cat).html(data);
		});
}

SB.profile.prototype.updateAllPoints = function() {
   this.updatePoints(0);
   this.updatePoints(1);
   this.updatePoints(2);
   this.updatePoints(3);
   this.updatePoints(4);
}

SB.profile.prototype.moreFriends = function(list, limit) {
  if (limit == null) limit = "15";
  var offset = list.find('li').size();
	var params = {}
	params["ws"] = "moreFriends";
	params["offset"] = offset;
	params["limit"] = limit;
	params["uid"] = this.uid;
	var context = this;
		$.get("/ws/", params, function(data){
			    if (data == "") {
			     $('#friends-show-more').hide();
			     $('#friends-show-all').hide();
			  } else {
						 	var ret = $(data);
						 if (context.uid == SBuser.uid) {
			  		   ret.find("a").each(function() {
						   		var code = "<a href='#' alt='odebrat' class='fr' onclick='SBuser.removeFriend(\""+$(this).parent().attr('uid')+"\");return false;'><img class='cross' alt='odebrat' src='/css/gfx/cross.png'></a>";
						  		$(this).parent().append(code);
						  	});
					  }
						
					   list.append(ret);	
				}
	  	});
};


