/*
 * 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();

		   this.addEventsControls();
		   this.addEventControls();
		   
		   this.embedlyWall();
		
		   $('.jq-button').button();

			/*live for embeded clicks*/
		  $('a.embedly').live("click", function(e){
		    e.preventDefault();
		    $(this).parent().parent().find('.embed').toggle();
		  });		  
	}   

   
   
};

SB.profile.prototype.embedlyWall = function() {
	$('.embed-container').remove();
	
	/*faster approach: embedly does join of URLs and only one call to the embedly site. We need to go with own scripts inside - javascript or php..*/
	$('.profile-wall-activity-text, .comment-wall-item').linkify();
	$('.profile-wall-activity-text a, .comment-wall-item a').embedly( {maxWidth:300}, function(oembed, dict){ 
											 var output = "<div class='embed-container'><div class='embed-preview'><a class='embedly' href='#'><img src='"+oembed.thumbnail_url+"' /></a></div>";
										   output += "<div class='embed-info'><a class='embedly' href='#'><span class='embed-title'>"+oembed.title+"</span></a><br>"+dict.node.attr("href") +"<div class='embed-description'>"+oembed.description+"</div></div>";
		   								 output += oembed['code'];
											 output += "<div class='clr'></div></div>";	
												dict.node.after(output);
								});

/*
	$('.profile-wall-record .profile-wall-activity-text').each(function(){
		      var embedlink = "";
		      var profilerecord = $(this);
			  	var hrefs = jQuery("<div />", { id:"temp-tad", html: $(this).html()}).linkify().find("a");
				  	if (hrefs.size() > 0) embedlink = $(hrefs).attr("href");
				  	$("#temp-tad").remove();
				     if (embedlink!='') {
								$.embedly(embedlink, { maxWidth:300 }, function(oembed){ 
											 var output = "<div class='embed-container'><div class='embed-preview'><a class='embedly' href='#'><img src='"+oembed.thumbnail_url+"' /></a></div>";
										   output += "<div class='embed-info'><a class='embedly' href='#'><span class='embed-title'>"+oembed.title+"</span></a><br>"+embedlink+"<div class='embed-description'>"+oembed.description+"</div></div>";
		   								 output += oembed['code'];
											 output += "<div class='clr'></div></div>";	
												$(profilerecord).append(output);
								});
				     		
				     }
		
	});
	*/
};

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 */
	}
}

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);
		/*this is a hack and possible security problem*/
			cookie = SESSION_COOKIE;
	
				$("#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,
					'sizeLimit'          : 4096000,
					'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() {

     /*add controls to the activity feed*/
		 var code;
			
			/**correct duplications !!!*/		
			/*	
		 code = "<a href='#' onclick='this.blur(); initWallComment($(this).parent().parent().parent().attr(\"cmntid\"));return false;' class='profile-activity-add-comment' title='přidat komentář'><img src='/css/gfx/icon-bubble.png' alt='přidat komentář' /></a>";
     $('.profile-wall-record-controls[cmntid!=""]').append(code);
     code = "<a href='#' onclick='this.blur(); return false;' class='profile-activity-send-pm' title='poslat zprávu'><img src='/css/gfx/icon-message.png' alt='poslat zprávu' /></a>";
     $('.profile-wall-record-controls[actuid!='+SBuser.uid+']').append(code);
     code = "<a href='#' onclick='this.blur(); SBprofile.deleteActivity($(this).parent().parent().parent());return false;' class='profile-activity-delete' title='smazat'><img src='/css/gfx/icon-cross.png' alt='smazat' /></a>";
     $('.profile-wall-record-controls[actuid='+SBuser.uid+']').append(code);
		 */

     /*
     $('.profile-activity-delete').hide();
		 $(".profile-wall-record").mouseover(function() {
					$(this).find('.profile-activity-delete').show();
						}).mouseout(function() {
					$(this).find('.profile-activity-delete').hide();
				});
     */

		var context = this;
   if (this.uid == SBuser.uid) {
     /*append action for new post*/
     $('#profile-wall-addpost').unbind();
     $('#profile-wall-addpost').click(function(){
       		var message = $('#profile-wall-new-post').val();
       		if (message == "" || message == $('#profile-wall-new-post').attr('prefilled')) return false;
     		  SBuser.addActivity(message, '', '', '', '', function(data){
							$(data).hide().prependTo('#profile-wall-activities').slideDown("slow");
					   $('#profile-wall-new-post').val('');
					   context.embedlyWall();
					   /*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','#ffffff');
			});

			/*embedly implemetayion to the add activity textarea*/
			$('#profile-wall-new-post').bind('keyup mouseup',function(event){
				  if ( (event.type == 'keyup' && (event.keyCode == 32 || event.keyCode == 13 || event.keyCode == 86)) || event.type == 'mouseup') {
				  	var link = "";
				  	var hrefs = jQuery("<div />", { id:"temp-tad", html: $(this).val()}).linkify().find("a");
				  	if (hrefs.size() > 0) link = $(hrefs).attr("href");
				  	$("#temp-tad").remove();
				     if (link!='') {
								$.embedly(link, { maxWidth:300 }, function(oembed){ 
												$("#profile-wall-embedview").show();
										   var output = "<div class='embed-container'><div class='embed-preview'><a class='embedly' href='#'><img src='"+oembed.thumbnail_url+"' /></a></div>";
										   output += "<div class='embed-info'><a class='embedly' href='#'><span class='embed-title'>"+oembed.title+"</span></a><br>"+link+"<div class='embed-description'>"+oembed.description+"</div></div>";
		   								 output += oembed['code'];
											 output += "<div class='clr'></div></div>";	
												$('#profile-wall-embedview').html(output);
								});
				     		
				     }
					}
		   });
				   
	    $('#profile-wall-new-post').val('Napište co máte právě na mysli.');
	    $('#profile-wall-new-post').css('color','#bbbbbb');
  } 
};

SB.profile.prototype.deleteActivity = function(act) {
		var actid = act.attr('actid');
		thConfirm("Skutečně chcete smazat tento záznam?","Smazat záznam?", function(ret) {
		   if (ret) {
					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;
	var context = this;
		$.get("/ws/", params, function(data){
			    if (data == "") {
			     $('#profile-wall-show-more').hide();
			  } else {
					   $('#profile-wall-activities').append(data);	
					   context.embedlyWall();
				}
	  	});
	  
	
};

SB.profile.prototype.addPersonalControls = function() {
      var editbutton = "<li><a href='#' onclick='return SBprofile.editPersonalData();' id='profile-edit'>editovat moje údaje</a></li>";
      var changepwdbutton = "<li><a href='#' onclick='return SBprofile.changePassword();' id='profile-changepwd'>změnit heslo</a></li>";
      var pmbutton = "<li><a href='#' onclick='this.blur(); newMessage(\""+this.uid+"\");return false' id='profile-send-pm'>poslat zprávu</a></li>";
      var intbutton = "<li><a href='#' onclick='return SBprofile.setInterests();' id='profile-edit-interests'>nastavit mé zájmy</a></li>";
   if (this.uid == SBuser.uid) {
    	$('#profile-toolbar').append(editbutton + changepwdbutton + intbutton);
   } else {
    	$('#profile-toolbar').append(pmbutton);
  }   
}



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 = "<li><a href='#'  onclick='return SBprofile.getPersonalData();' id='profile-edit'>Zrušit</a></li>";
   var savebtn = "<li><a href='#' onclick='return SBprofile.savePersonalData();'>Uložit</a></li>";
   $('#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.changePassword = function(callback) {
   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();
							 if (callback) callback(data);
						});
 						
						
					},
					"Zrušit": function() { 
						$(this).dialog("close");
						$('#profile-changepwd-dialog').remove();
					}
				}	
			  });
}

SB.profile.prototype.setInterests = function(callback) {
	var params = {}
	params["ws"] = "getInterests";
	params["for"] = "user";
	
	if (!callback) callback = function() {document.location.reload();};
	
	var context = this;
		$.get("/ws/", params, function(data){
			  var code = "<span style='text-align:left;' id='interest-dialog'><ul>";
			  var userInterests = data['user'];
				for (i in data) if (i!='user'){
				  var id = i;
				  var q = data[i];
				  var ch = "";
				  if ($.inArray(i,userInterests) != -1 ) ch = " checked ";
				  code += "<li><input type='checkbox' name='interest-dialog-option'  value='"+i+"' " + ch + "/>&nbsp;"+q+"</li>";
				}
				code += "</ul></span>";
				
				thDialog(code, "Vyberte Vaše zájmy", function(r) {
					if (!r) return;
					var params = {}
					params["ws"] = "setInterests";
					params["for"] = "user";
					$("#interest-dialog").find("input[@name='interets-dialog-option']:checked").each(function() {
						params["interest-" + $(this).val()] = $(this).val();
					}); 
					$.get("/ws/", params, function(data){
							if (data == "") data = "Uloženo.";
							thAlert(data,"Zájmy uživatele", function() {
								if (callback) callback(data);
								});
					});
			
					
					});
		},"json");
};

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;
		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();
   
   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.addPhotoGalleriesControls = function() {
   if (this.uid == SBuser.uid) {
     var code = "<a href='#' onclick='SBprofile.addPhotogallery();return false;' class='fr'><span>nová galerie</span></a>";
     $('#photo-toolbar').append(code);
     $('.jq-button').button();
     
  } 
};


SB.profile.prototype.addPhotogallery = function() {
	thPrompt("Zadejte název nové fotogalerie", "", "Nová galerie", function(r,v){
		if (!r) return;
		location.href = '/fotogalerie/'+this.uid+'/new/' + v + '/';
	})
};

/*

SB.profile.prototype.addPhotoGalleryControls = function() {
   
   $('#photogallery-toolbar').html('');
   if (this.uid == SBuser.uid) {
     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);
    this.photoGalleryID = $('#photogallery').attr('pgid');
     if ($('#photogallery').attr('new') == '1') this.addPhotos();
 
   }
   
   code = "<a href='/foto/"+this.uid+"/' class='buttonLike fr'><span>Zpět k fotogaleriím</span></a>";
   $('#photogallery-toolbar').append(code);

}

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;
		
			
			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);
			cookie = SESSION_COOKIE;
			
				$("#uploadify-image").uploadify({
					'buttonText'		 : 'Vybrat',
					'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();
												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);
											  } 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) {
									
						}
				});
				
				$('.jq-button').button();
				   
};

SB.profile.prototype.editPhotoGallery = function() {
   $('#photo-upload').hide('slow');
   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>"; 
   var desccode = "<tr><td>Popis: </td><td><textarea name='photogallery-edit-desc' id='photogallery-edit-desc' class='photogallery-edit-desc'>" + desc + "</textarea></td></tr>"; 
   var permcode = "<tr><td>Oprávnění: </td><td>" + this.permsSelect('gperm') + "</td></tr>";
   var ctrlcode = "<table>"+namecode+desccode+permcode+"</table>";
   $('#photogallery').prepend(ctrlcode);
   $('#perm_gperm').val($('#photogallery').attr('perm'));
   $('#photogallery-name').remove();
   $('#photogallery-desc').remove();

 
    $('.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);
      $(this).show();
   });
   var editcode = "<input type='radio' name='photo-default'>Titulní foto<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);
    	   });
    	}
    }

   
   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;

    $('textarea[name=photogallery-photo-desc-edit]').each(function() {
      var val = $(this).val();
      var id = $(this).parent().parent().attr('photo');
      params['comment' + id] = val;
   });
   
   $('#photogallery').find("input[name=photo-default]").each(function() {
      if ($(this).attr('checked')) {
      	params['photo'] = $(this).parent().attr('photo');
      }
   });
   
   $('#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);
					context.addPhotoGalleryControls();
					$('a[rel*=lightbox]').lightBoxClone(); 
	  	});
};


*/

/*EVENTS CODE */

SB.profile.prototype.addEventsControls = function() {
		if (0==1) {
     var code = "<a href='#' onclick='SBprofile.addEvent();return false;' class='fr'>nová událost</a>";
     $('#events-toolbar').append(code);   
		}
};

SB.profile.prototype.addEvent = function() {
	thPrompt("Zadejte název nové události", "", "Nová událost", function(r,v){
		if (!r) return;
		location.href = '/event/new/' + v + '/';
	})
};

SB.profile.prototype.addEventControls = function() {
		/*recognize who can add events*/
		 var code = "";
     code += "<a href='#' onclick='SBprofile.editEvent(); return false;' class='fr'><span>upravit</span></a>";
     code += "<a href='#' onclick='SBprofile.deleteEvent(); return false;' class='fr'><span>smazat</span></a>";
		 code += "<a href='#' onclick='SBprofile.setEventInterests(); return false;' class='fr'>nastavit zájmy</a>";
     $('#event-toolbar').append(code);     	     	
     this.eventID = $('#event').attr('eid');
};

SB.profile.prototype.editEvent = function() {
   var context = this;
   
   $('.event-property').each(function() {
      var val = $(this).html();
      var key = $(this).attr('key');
      if (key=="event-desc") {
      	/*replace <br> to newline to the textarea.*/
      	val = str_replace("<br>","\n",val);
      	var code = "<textarea name='"+key+"' id='"+key+"'>" + val + "</textarea>";
      } else {
      	var code = "<input type='text' name='"+key+"' value='"+val+"' id='"+key+"'>";
      }
      $(this).html(code);
   });
   
   /*customize the form*/
   
   
   AnyTime.picker( "event-start",{ format: "%d.%m.%Y %H:%i"} );
   AnyTime.picker( "event-end",{ format: "%d.%m.%Y %H:%i"} );
	 
	 /*
	 var rangeDemoFormat = "%d.%m.%Y %H:%i";
   var rangeDemoConv = new AnyTime.Converter({format:rangeDemoFormat});

		$("#event-start").change( function(e) { 
		      var fromDay = rangeDemoConv.parse($("#event-start").val()).getTime();
		      $("#event-end").
		          AnyTime_noPicker().
		          val(rangeDemoConv.format(fromDay)).
		          AnyTime_picker(
		              { earliest: fromDay,
		                format: rangeDemoFormat
		              } );
		      });

	*/
  /* $('#event-start, #event-end').datepicker( { altFormat: 'dd.mm.yy', dateFormat: 'dd.mm.yy' } );*/
   /*$('#event-start, #event-end').addClass('dateCZ');*/

   var cancelbtn = "<a href='#'  onclick='return SBprofile.getEvent();' id='event-edit' class='fr'>Zrušit</a>";
   var savebtn = "<a href='#' onclick='return SBprofile.saveEvent();' class='fr'>Uložit</a>";
   $('#event-toolbar').html(savebtn + cancelbtn);
   return false;
};


SB.profile.prototype.deleteEvent = function() {
	
		var context = this;
		var params = {}
		params["ws"] = "deleteEvent";
		params["id"] = this.eventID;
		
		thConfirm("Skutečně chcete smazat tuto událost?","Smazat událost?", function(ret) {
		   if (ret) {
				$.get("/ws/", params, function(data){
						window.location = '/events/' + context.uid + '/';
				});
		   }
		});
		return false;	
};

SB.profile.prototype.getEvent = function() {
	$("#event-start").AnyTime_noPicker();
	$("#event-end").AnyTime_noPicker();
	
	var params = {}
	params["ws"] = "getEventHTML";
	params["id"] = this.eventID;
	$.get("/ws/", params, function(data){
    $('#event').replaceWith(data);
    $('#event-toolbar').html('');
    SBprofile.addEventControls();
	});	
	return false;
  
};

SB.profile.prototype.saveEvent = function() {
    /*check data*/
    /*
    if (!$('#form-profile-user-properties').valid()) {
       return false;
    }
    */
    
    /*get the data*/
    var params = {}
    params['id'] = this.eventID;
		$('#event').find("input, textarea, select").each(function() { 
			params[ this.name ] = this.value; 
		});
	 var context = this; 
	 $.post("/ws/?ws=saveEvent", params, function(data){
      $('#event-toolbar').html('');
      context.getEvent();
	 });
   return false;
};

SB.profile.prototype.setEventInterests = function() {
	var params = {}
	params["ws"] = "getInterests";
	params["for"] = "event";
	params["id"] = this.eventID;
	
	var context = this;
		$.get("/ws/", params, function(data){
			  var code = "<span style='text-align:left;' id='interest-dialog'><ul>";
			  var eventInterests = data['event'];
				for (i in data) if (i!='event'){
				  var id = i;
				  var q = data[i];
				  var ch = "";
				  if ($.inArray(i,eventInterests) != -1 ) ch = " checked ";
				  code += "<li><input type='checkbox' name='interest-dialog-option'  value='"+i+"' " + ch + "/>&nbsp;"+q+"</li>";
				}
				code += "</ul></span>";
				
				thDialog(code, "Vyberte zájmy události", function(r) {
					if (!r) return;
					var params = {}
					params["ws"] = "setInterests";
					params["for"] = "event";
					params["id"] = context.eventID;
					$("#interest-dialog").find("input[@name='interets-dialog-option']:checked").each(function() {
						params["interest-" + $(this).val()] = $(this).val();
					}); 
					$.get("/ws/", params, function(data){
							if (data == "") data = "Uloženo.";
							thAlert(data,"Zájmy události", function() {
								document.location.reload();
								});
					});
			
					
					});
		},"json");
};



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.welcome = function(msg, callback) {
		$('#welcome-message').remove();
		var params = {
			buttons: {
				"Vstoupit do klubu": function() { 
					$(this).dialog("close");
					if (callback) callback('Ok');
				}
			},
			height: 300,
			width: 400,
			modal: true
		}
		jQuery("<div />", { id:"welcome-message", html: msg.replace(/\n/, "<br />"), "title": "Vítejte v CVMAGIC" }).dialog(params);
}
